#!/usr/bin/env bash
# aider-watch-client installer | 2026-04-20 @ Asia/Taipei
# Mac 本機安裝腳本：
#   1. pipx install aider-watch-client（獨立 venv，不污染系統 Python）
#   2. symlink aiderw 到 /opt/homebrew/bin（讓 PATH 找得到）
#   3. 檢查 ~/.aider-watch.env（必須有 AIDER_API_URL + AIDER_WEBHOOK_SECRET）
#   4. 建工作目錄 ~/aider-watch/{buffer,logs}
#   5. 安裝 launchd flush job（每 5min）
#   6. 跑 aider-watch doctor 驗證

set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$HERE/.." && pwd)"
PY="/Users/ogt/.pyenv/versions/3.11.7/bin/python3"

echo "== aider-watch-client installer =="
echo "repo: $ROOT"
echo "python: $PY"

# ---------- 1. pipx install ----------
if ! command -v pipx >/dev/null 2>&1; then
  echo "❌ pipx 未安裝。請先 brew install pipx && pipx ensurepath"
  exit 1
fi

echo "-> pipx install -e $ROOT ..."
if pipx list | grep -q "aider-watch-client"; then
  echo "   已存在，執行 pipx reinstall..."
  pipx reinstall aider-watch-client
else
  pipx install --python "$PY" -e "$ROOT"
fi

# ---------- 2. symlink ----------
HOMEBREW_BIN="/opt/homebrew/bin"
if [[ -d "$HOMEBREW_BIN" ]]; then
  ln -sf "$HOME/.local/bin/aiderw" "$HOMEBREW_BIN/aiderw"
  ln -sf "$HOME/.local/bin/aider-watch" "$HOMEBREW_BIN/aider-watch"
  echo "✓ aiderw + aider-watch symlinked to $HOMEBREW_BIN"
fi

# ---------- 3. ~/.aider-watch.env 檢查 ----------
ENV_FILE="$HOME/.aider-watch.env"
if [[ ! -f "$ENV_FILE" ]]; then
  cat <<EOF

❌ $ENV_FILE 不存在。請建立後重跑：

cat > $ENV_FILE <<'EV'
AIDER_API_URL=http://192.168.0.120:32334/api/v1/aider/events
AIDER_WEBHOOK_SECRET=<從 /tmp/aider_webhook_secret.txt 貼過來>
AIDER_WATCH_HOSTNAME=ogt-mac
EV
chmod 600 $ENV_FILE

EOF
  exit 1
fi
chmod 600 "$ENV_FILE"

# 驗必要 env 有值
required_keys=("AIDER_API_URL" "AIDER_WEBHOOK_SECRET")
missing=()
for k in "${required_keys[@]}"; do
  if ! grep -q "^${k}=" "$ENV_FILE"; then
    missing+=("$k")
  fi
done
if [[ ${#missing[@]} -gt 0 ]]; then
  echo "❌ $ENV_FILE 缺必要 key: ${missing[*]}"
  exit 2
fi
echo "✓ $ENV_FILE 檢查通過"

# ---------- 4. 工作目錄 ----------
mkdir -p "$HOME/aider-watch/"{buffer,logs}
touch "$HOME/aider-watch/live.log"
echo "✓ ~/aider-watch/ 工作目錄就緒"

# ---------- 5. launchd ----------
DEST="$HOME/Library/LaunchAgents"
mkdir -p "$DEST"
PLIST_SRC="$ROOT/launchd/com.awoooi.aider-flush.plist"
PLIST_DST="$DEST/com.awoooi.aider-flush.plist"

cp "$PLIST_SRC" "$PLIST_DST"
launchctl unload "$PLIST_DST" 2>/dev/null || true
launchctl load -w "$PLIST_DST"

if ! launchctl list | grep -q "com.awoooi.aider-flush"; then
  echo "❌ launchd flush job 載入失敗"
  exit 3
fi
echo "✓ launchd com.awoooi.aider-flush 已註冊（每 5 min 跑）"

# ---------- 6. doctor ----------
echo ""
echo "-> aider-watch doctor"
if ! aider-watch doctor; then
  echo "❌ doctor 檢查未全過 — 請修完問題後重跑"
  exit 4
fi

echo ""
echo "🎉 安裝完成！"
echo ""
echo "使用："
echo "  aiderw --message '改 hello' --exit"
echo "  aider-watch doctor          # 檢查環境"
echo "  aider-watch flush           # 手動 flush buffer"
echo ""
echo "卸載："
echo "  launchctl unload $PLIST_DST"
echo "  pipx uninstall aider-watch-client"
echo "  rm $HOMEBREW_BIN/aiderw $HOMEBREW_BIN/aider-watch"
