#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"

echo "=== Harmony Desktop — macOS Build ==="
echo ""

# ── 1. Check we're on macOS ──
if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "ERROR: This script must be run on macOS."
  exit 1
fi

# ── 2. Check / install Xcode CLI tools ──
if ! xcode-select -p &>/dev/null; then
  echo "[pre] Xcode Command Line Tools not found. Installing..."
  xcode-select --install
  echo "     Waiting for Xcode CLI tools installation to finish..."
  echo "     (A dialog may have appeared — click Install, then re-run this script.)"
  exit 1
fi
echo "[ok] Xcode CLI tools: $(xcode-select -p)"

# ── 3. Check / install Node.js via Homebrew ──
if ! command -v node &>/dev/null || ! command -v npm &>/dev/null; then
  echo "[pre] Node.js not found. Installing via Homebrew..."
  if ! command -v brew &>/dev/null; then
    echo "ERROR: Homebrew is required but not installed."
    echo "       Install it from https://brew.sh and re-run this script."
    exit 1
  fi
  brew install node
  echo ""
fi
echo "[ok] Node $(node -v) / npm $(npm -v)"

# ── 4. Generate .icns icon from icon.png if missing ──
if [[ ! -f "assets/icon.icns" ]]; then
  echo "[1/4] Generating macOS icon (icon.icns) from icon.png..."
  ICONSET_DIR=$(mktemp -d)/Harmony.iconset
  mkdir -p "$ICONSET_DIR"
  SRC="assets/icon.png"
  if [[ ! -f "$SRC" ]]; then
    echo "ERROR: assets/icon.png not found. Cannot generate icon."
    exit 1
  fi
  # sips ships with macOS — no extra tools needed
  sips -z   16   16 "$SRC" --out "$ICONSET_DIR/icon_16x16.png"      &>/dev/null
  sips -z   32   32 "$SRC" --out "$ICONSET_DIR/icon_16x16@2x.png"   &>/dev/null
  sips -z   32   32 "$SRC" --out "$ICONSET_DIR/icon_32x32.png"      &>/dev/null
  sips -z   64   64 "$SRC" --out "$ICONSET_DIR/icon_32x32@2x.png"   &>/dev/null
  sips -z  128  128 "$SRC" --out "$ICONSET_DIR/icon_128x128.png"    &>/dev/null
  sips -z  256  256 "$SRC" --out "$ICONSET_DIR/icon_128x128@2x.png" &>/dev/null
  sips -z  256  256 "$SRC" --out "$ICONSET_DIR/icon_256x256.png"    &>/dev/null
  sips -z  512  512 "$SRC" --out "$ICONSET_DIR/icon_256x256@2x.png" &>/dev/null
  sips -z  512  512 "$SRC" --out "$ICONSET_DIR/icon_512x512.png"    &>/dev/null
  sips -z 1024 1024 "$SRC" --out "$ICONSET_DIR/icon_512x512@2x.png" &>/dev/null
  iconutil -c icns "$ICONSET_DIR" -o "assets/icon.icns"
  rm -rf "$(dirname "$ICONSET_DIR")"
  echo "     Created assets/icon.icns"
else
  echo "[1/4] macOS icon already exists."
fi

# ── 5. Install npm dependencies ──
echo "[2/4] Installing dependencies..."
npm install

# ── 6. Build ──
echo "[3/4] Building macOS app..."
npx electron-builder --mac

# ── 7. Done ──
echo ""
echo "[4/4] Done!"
echo "Output is in ./dist/"
echo ""
ls -lh dist/*.dmg dist/*.zip 2>/dev/null || true
echo ""
echo "To install: open the .dmg and drag Harmony to Applications."
