#!/bin/zsh
set -euo pipefail

ROOT_DIR="${0:A:h}"
INSTALL_DIR="$HOME/.codex-pilot/mobile-control"
CODEX_HOME_DIR="$HOME/.codex"
WORKSPACE_ROOT_DEFAULT="$HOME/CodexWorkspaces"
WORKSPACE_ROOT="${CODEX_MOBILE_WORKSPACE_ROOT:-$WORKSPACE_ROOT_DEFAULT}"
PORT="${CODEX_DROPBOX_PORT:-8787}"
LABEL="com.codexpilot.mobile-control"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
START_SCRIPT="$INSTALL_DIR/start-mac.sh"
TOKEN_FILE="$INSTALL_DIR/.token"
NODES_FILE="$INSTALL_DIR/codex-nodes.json"
CONNECTION_INFO="$INSTALL_DIR/connection-info.txt"
APP_FILE="$(find "$ROOT_DIR/app" -maxdepth 1 -type f -name 'CodexPilot-external-v*.apk' | sort | tail -1)"

if [ -z "$APP_FILE" ] || [ ! -f "$APP_FILE" ]; then
  echo "没有找到外部版 APK，请重新下载完整部署包。" >&2
  exit 1
fi
APP_NAME="${APP_FILE:t}"

mkdir -p "$INSTALL_DIR" "$INSTALL_DIR/data" "$INSTALL_DIR/logs" "$INSTALL_DIR/desktop-queue" "$INSTALL_DIR/uploads" "$WORKSPACE_ROOT" "$CODEX_HOME_DIR" "$HOME/Library/LaunchAgents"
cp "$ROOT_DIR/server/mac/mobile_codex_server.py" "$INSTALL_DIR/mobile_codex_server.py"
cp "$ROOT_DIR/server/mac/desktop_ui_helper.py" "$INSTALL_DIR/desktop_ui_helper.py"
cp "$ROOT_DIR/server/mac/local_transcribe.py" "$INSTALL_DIR/local_transcribe.py"
cp "$ROOT_DIR/server/mac/qrcodegen.py" "$INSTALL_DIR/qrcodegen.py"
cp "$ROOT_DIR/app-info.json" "$INSTALL_DIR/app-info.json"
mkdir -p "$INSTALL_DIR/app"
rm -f "$INSTALL_DIR"/app/CodexPilot-external-v*.apk
cp "$APP_FILE" "$INSTALL_DIR/app/$APP_NAME"

if [ ! -f "$TOKEN_FILE" ]; then
  if command -v openssl >/dev/null 2>&1; then
    openssl rand -base64 24 | tr '+/' '-_' | tr -d '=' > "$TOKEN_FILE"
  else
    uuidgen | tr '[:upper:]' '[:lower:]' > "$TOKEN_FILE"
  fi
  chmod 600 "$TOKEN_FILE"
fi

if [ ! -f "$INSTALL_DIR/workspaces.json" ]; then
  printf '[]\n' > "$INSTALL_DIR/workspaces.json"
fi
printf '[]\n' > "$NODES_FILE"

cat > "$START_SCRIPT" <<EOF
#!/bin/zsh
set -euo pipefail
cd "$INSTALL_DIR"
export CODEX_DROPBOX_HOST="0.0.0.0"
export CODEX_DROPBOX_PORT="$PORT"
export CODEX_MOBILE_DISABLE_DEFAULT_NODES="1"
export CODEX_MOBILE_NODES_FILE="$NODES_FILE"
export CODEX_MOBILE_WORKSPACE_ROOT="$WORKSPACE_ROOT"
export CODEX_MOBILE_FALLBACK_WORKSPACE_ROOT="$WORKSPACE_ROOT"
export CODEX_MOBILE_LOCAL_WORKSPACE_ROOT="$WORKSPACE_ROOT"
export CODEX_MOBILE_LAUNCHD_LABEL="$LABEL"
export CODEX_HOME="$CODEX_HOME_DIR"
export CODEX_STATE_DB="$CODEX_HOME_DIR/state_5.sqlite"
export CODEX_CONFIG_FILE="$CODEX_HOME_DIR/config.toml"
export CODEX_AUTH_FILE="$CODEX_HOME_DIR/auth.json"
export CODEX_SKILLS_ROOT="$CODEX_HOME_DIR/skills"
export PATH="/Applications/ChatGPT.app/Contents/Resources:/Applications/Codex.app/Contents/Resources:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"
exec /usr/bin/python3 "$INSTALL_DIR/mobile_codex_server.py" >> "$INSTALL_DIR/logs/server.log" 2>&1
EOF
chmod +x "$START_SCRIPT"

cat > "$PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>$LABEL</string>
  <key>ProgramArguments</key>
  <array><string>$START_SCRIPT</string></array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>WorkingDirectory</key><string>$INSTALL_DIR</string>
  <key>StandardOutPath</key><string>$INSTALL_DIR/logs/launchd.out.log</string>
  <key>StandardErrorPath</key><string>$INSTALL_DIR/logs/launchd.err.log</string>
</dict>
</plist>
EOF

launchctl bootout "gui/$(id -u)/$LABEL" >/dev/null 2>&1 || true
bootstrap_ok=0
for attempt in 1 2 3; do
  if launchctl bootstrap "gui/$(id -u)" "$PLIST"; then
    bootstrap_ok=1
    break
  fi
  sleep 1
done
if [ "$bootstrap_ok" != "1" ]; then
  echo "电脑端服务启动失败，请运行 verify-mac.command 查看原因。" >&2
  exit 2
fi
launchctl kickstart -k "gui/$(id -u)/$LABEL"
sleep 2

TOKEN="$(tr -d '\n' < "$TOKEN_FILE")"
CONNECT_URL="http://127.0.0.1:$PORT/connect"
LAN_IP="$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || echo "本机IP")"
{
  echo "电脑名称：$(scutil --get ComputerName 2>/dev/null || hostname)"
  echo "电脑地址：http://$LAN_IP:$PORT"
  echo "访问口令：$TOKEN"
  echo "工作包目录：$WORKSPACE_ROOT"
  echo "安装目录：$INSTALL_DIR"
} > "$CONNECTION_INFO"
chmod 600 "$CONNECTION_INFO"
echo
echo "Codex Pilot 电脑端已安装"
echo "手机电脑地址：http://$LAN_IP:$PORT"
echo "访问口令：$TOKEN"
echo "工作包目录：$WORKSPACE_ROOT"
echo "连接信息已保存：$CONNECTION_INFO"
echo "验证地址：http://127.0.0.1:$PORT/api/bootstrap?token=$TOKEN"
echo
service_ready=0
for attempt in {1..15}; do
  if curl -fsS --max-time 3 "http://127.0.0.1:$PORT/api/bootstrap?token=$TOKEN" >/dev/null 2>&1; then
    service_ready=1
    break
  fi
  sleep 1
done
if [ "$service_ready" = "1" ]; then
  open "$CONNECT_URL" >/dev/null 2>&1 || true
  echo "扫码配对页面已自动打开。手机安装 app/$APP_NAME 后，点“扫码连接”即可。"
else
  echo "服务尚未通过健康检查，请运行 verify-mac.command 后再打开扫码页面。" >&2
fi
