#!/usr/bin/env bash
# macOS 客户端安装：pip + Console client build + launchd Agent
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
SUPPORT="$HOME/Library/Application Support/NianNian"
LAUNCH_AGENTS="$HOME/Library/LaunchAgents"
PLIST_NAME="com.niannian.agent.plist"
SYNC_PLIST_NAME="com.niannian.pinn-sync.plist"
PLIST_SRC="$ROOT/client/mac/$PLIST_NAME"
SYNC_PLIST_SRC="$ROOT/client/mac/$SYNC_PLIST_NAME"
PLIST_DST="$LAUNCH_AGENTS/$PLIST_NAME"
SYNC_PLIST_DST="$LAUNCH_AGENTS/$SYNC_PLIST_NAME"
ENV_DST="$ROOT/client/config/client-agent.env"
LOG_DIR="$SUPPORT/logs"

echo "==> NianNian macOS client install"
echo "    repo: $ROOT"
echo "    home: $SUPPORT"

mkdir -p "$SUPPORT" "$LOG_DIR" "$LAUNCH_AGENTS"

if [[ ! -f "$ENV_DST" ]]; then
  cp "$ROOT/client/config/client-agent.env.example" "$ENV_DST"
  echo "    created $ENV_DST (edit NIANNIAN_HOME if needed)"
fi

echo "==> pip install (editable + http)"
cd "$ROOT"
python3 -m pip install -e ".[http]" --quiet

if [[ -f "$ROOT/console/web/dist/index.html" ]]; then
  echo "==> Console dist present, skip npm build"
else
  echo "==> build Console (client profile)"
  bash "$ROOT/client/scripts/build-console-client.sh"
fi

chmod +x "$ROOT/client/scripts/run-pinn-sync.sh"

echo "==> install launchd plist (agent + pinn-sync)"
sed \
  -e "s|@REPO_ROOT@|$ROOT|g" \
  -e "s|@NIANNIAN_HOME@|$SUPPORT|g" \
  "$PLIST_SRC" > "$PLIST_DST"
sed \
  -e "s|@REPO_ROOT@|$ROOT|g" \
  -e "s|@NIANNIAN_HOME@|$SUPPORT|g" \
  "$SYNC_PLIST_SRC" > "$SYNC_PLIST_DST"

launchctl bootout "gui/$(id -u)/com.niannian.agent" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST_DST"
launchctl enable "gui/$(id -u)/com.niannian.agent"
launchctl kickstart -k "gui/$(id -u)/com.niannian.agent"

launchctl bootout "gui/$(id -u)/com.niannian.pinn-sync" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$SYNC_PLIST_DST"
launchctl enable "gui/$(id -u)/com.niannian.pinn-sync"

echo "==> health check"
bash "$ROOT/client/scripts/health-check.sh"

echo ""
echo "Done. Open Console: http://127.0.0.1:18765/niannian/chat"
echo "Logs: $LOG_DIR/agent.stdout.log · pinn-sync: $LOG_DIR/pinn-sync.stdout.log"
