#!/bin/zsh
set -euo pipefail

cd "$(dirname "$0")"
ROOT_DIR="$(pwd)"

echo "CodexMobile Mac installer"
echo "Install directory: $ROOT_DIR"
echo

find_python() {
  for candidate in python3.12 python3.11 python3; do
    if command -v "$candidate" >/dev/null 2>&1; then
      if "$candidate" - <<'PY'
import sys
raise SystemExit(0 if sys.version_info >= (3, 11) else 1)
PY
      then
        echo "$candidate"
        return 0
      fi
    fi
  done
  return 1
}

PYTHON_BIN="$(find_python || true)"
if [[ -z "$PYTHON_BIN" ]]; then
  echo "Python 3.11+ is required."
  echo "Install Python from https://www.python.org/downloads/macos/ and run this installer again."
  exit 1
fi

echo "==> Creating Python virtual environment"
"$PYTHON_BIN" -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
pip install .

if [[ ! -f .env ]]; then
  echo "==> Creating .env from template"
  cp .env.example .env
  chmod 600 .env
else
  echo "==> Existing .env kept"
fi

echo "==> Installing LaunchAgent templates"
mkdir -p "$HOME/Library/LaunchAgents"
python - <<'PY'
from pathlib import Path

root = Path.cwd()
templates = {
    "deploy/com.codexmobile.mac-service.plist": "com.codexmobile.mac-service.plist",
    "deploy/com.codexmobile.mac-tunnel.plist": "com.codexmobile.mac-tunnel.plist",
    "deploy/com.codexmobile.desktop-bridge.plist": "com.codexmobile.desktop-bridge.plist",
}
target_dir = Path.home() / "Library" / "LaunchAgents"
for src, name in templates.items():
    text = (root / src).read_text(encoding="utf-8")
    text = text.replace("__CODEXMOBILE_DIR__", str(root))
    (target_dir / name).write_text(text, encoding="utf-8")
PY

echo "==> Removing quarantine flag if present"
xattr -dr com.apple.quarantine "dist/CodexMobile Menu Client.app" 2>/dev/null || true
xattr -dr com.apple.quarantine "dist/CodexMobile Mac Client.app" 2>/dev/null || true

echo
echo "Install complete."
echo "Next steps:"
echo "1. Open dist/CodexMobile Menu Client.app"
echo "2. Open Settings and fill API URL, App Token, Mac Token and project root"
echo "3. Click Refresh Connection"
echo
open "dist/CodexMobile Menu Client.app" || true
