#!/usr/bin/env bash
# Nexting Codex bridge installer.
#   curl -fsSL https://nexting.ai/install-codex | bash
# Logs you in to Nexting in your browser, installs the bridge, and makes your
# Codex sessions visible and controllable from your phone. No shim needed —
# a background daemon (launchd) pushes session snapshots to the cloud.
# Fully reversible:  nexting-cc-bridge codex-uninstall
set -euo pipefail

API="${NEXTING_API:-https://api.nexting.ai}"
WS_URL="${NEXTING_CODEX_URL:-wss://api.nexting.ai/codex-bridge/connect}"
CFG_DIR="$HOME/.nexting"
CFG="$CFG_DIR/codex-bridge.json"
CODEX_STANDALONE="${NEXTING_CODEX_STANDALONE:-$HOME/.codex/packages/standalone/current/codex}"

echo "→ Nexting Codex bridge installer"

command -v node >/dev/null 2>&1 || { echo "✗ Node.js not found. Install it first (https://nodejs.org)."; exit 1; }

if [ ! -x "$CODEX_STANDALONE" ]; then
  echo "→ Installing official Codex managed runtime…"
  curl -fsSL https://chatgpt.com/codex/install.sh | sh
fi

[ -x "$CODEX_STANDALONE" ] || {
  echo "✗ Official Codex standalone runtime not found at $CODEX_STANDALONE"
  echo "  Run: curl -fsSL https://chatgpt.com/codex/install.sh | sh"
  exit 1
}

echo "→ Starting Codex official remote-control daemon…"
"$CODEX_STANDALONE" app-server daemon bootstrap --remote-control >/dev/null 2>&1 || true
"$CODEX_STANDALONE" remote-control start --json >/dev/null || {
  echo "✗ Could not start Codex remote-control daemon."
  echo "  Run codex login if Codex is not authenticated, then rerun this installer."
  exit 1
}

# ── 1. log in to Nexting (device-code browser flow = the binding) ──
# Logging in IS the binding: the browser login authorizes this Mac for your
# account, no separate step. A token may be supplied out-of-band via
# NEXTING_CODEX_TOKEN to skip the browser login (e.g. an automated re-install).
if [ -n "${NEXTING_CODEX_TOKEN:-}" ]; then
  TOKEN="$NEXTING_CODEX_TOKEN"
  echo "✓ Using the Nexting account token provided."
else
  echo "→ Logging you in to Nexting…"
  START=$(curl -fsS -X POST "$API/api/v1/agent-bus/device/start")
  DEVICE_CODE=$(echo "$START" | node -e 'process.stdin.once("data",d=>console.log(JSON.parse(d).device_code))')
  VERIFY_URL=$(echo "$START" | node -e 'process.stdin.once("data",d=>console.log(JSON.parse(d).verify_url))')
  INTERVAL=$(echo "$START" | node -e 'process.stdin.once("data",d=>console.log(JSON.parse(d).interval||3))')

  echo "→ Opening your browser to log in:"
  echo "    $VERIFY_URL"
  ( command -v open >/dev/null 2>&1 && open "$VERIFY_URL" ) || echo "  (open the URL above manually)"

  echo "→ Waiting for you to log in & authorize…"
  TOKEN=""
  for _ in $(seq 1 100); do
    sleep "$INTERVAL"
    POLL=$(curl -fsS -X POST "$API/api/v1/agent-bus/device/poll" \
      -H 'Content-Type: application/json' -d "{\"device_code\":\"$DEVICE_CODE\"}")
    STATUS=$(echo "$POLL" | node -e 'process.stdin.once("data",d=>console.log(JSON.parse(d).status||""))')
    if [ "$STATUS" = "approved" ]; then
      TOKEN=$(echo "$POLL" | node -e 'process.stdin.once("data",d=>console.log(JSON.parse(d).token||""))')
      break
    fi
    [ "$STATUS" = "expired" ] && { echo "✗ Login expired. Re-run the installer."; exit 1; }
  done
  [ -n "$TOKEN" ] || { echo "✗ Timed out waiting for login."; exit 1; }
  echo "✓ Logged in."
fi

# ── 2. install the bridge ──
echo "→ Installing nexting-cc-bridge…"
npm install -g nexting-cc-bridge >/dev/null 2>&1 || {
  echo "  (npm global install unavailable — will run via npx instead)"
}

# ── 3. write config ──
mkdir -p "$CFG_DIR"
cat > "$CFG" <<EOF
{
  "url": "$WS_URL",
  "token": "$TOKEN"
}
EOF
chmod 600 "$CFG"
echo "✓ Config written to $CFG"

# ── 4. start the Nexting background daemon (launchd keeps it alive) ──
# Delegates to `nexting-cc-bridge codex-install`: writes a launchd plist that
# runs `nexting-cc-bridge codex-start` on login and keeps it alive. Normal Codex
# sends go through the official app-server remote-control daemon prepared above.
# Reversible: nexting-cc-bridge codex-uninstall.
echo "→ Setting up the Codex bridge daemon…"
# `codex-install` also gates Boss Mode: it verifies the superpowers/gstack Claude
# Code (Workflow tool + /loop) and exits non-zero if absent. Under `set -euo
# pipefail` that aborts this script before the `Done.` line — install the required
# Claude Code, then re-run this installer.
if command -v nexting-cc-bridge >/dev/null 2>&1; then
  nexting-cc-bridge codex-install
elif command -v npx >/dev/null 2>&1; then
  npx -y nexting-cc-bridge codex-install
else
  echo "✗ Could not run nexting-cc-bridge codex-install (no global bin / npx)."; exit 1
fi

echo
echo "Done. Your Codex sessions now appear on your phone."
echo "Open Nexting on your phone → Codex to see and co-control your sessions."
echo "Control path: phone → Nexting bridge → Codex official remote-control daemon."
echo "Remove: nexting-cc-bridge codex-uninstall"
