#!/usr/bin/env bash
# Nexting Claude Code bridge installer.
#   curl -fsSL https://nexting.ai/install-cc | bash
# Logs you in to Nexting in your browser, installs the bridge, and makes `claude`
# phone-controllable (claude shim + background hub). One step: log in = installed.
# Fully reversible:  nexting-cc-bridge uninstall
set -euo pipefail

API="${NEXTING_API:-https://api.nexting.ai}"
WS_URL="${NEXTING_CC_URL:-wss://api.nexting.ai/cc-bridge/connect}"
CFG_DIR="$HOME/.nexting"
CFG="$CFG_DIR/cc-bridge.json"

echo "→ Nexting Claude Code bridge installer"

command -v node >/dev/null 2>&1 || { echo "✗ Node.js not found. Claude Code needs Node — install it first."; 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_CC_TOKEN to skip the browser login (e.g. an automated re-install).
if [ -n "${NEXTING_CC_TOKEN:-}" ]; then
  TOKEN="$NEXTING_CC_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. make `claude` phone-controllable (shim + PATH + hub daemon) ──
# Delegates to `nexting-cc-bridge install`: installs the `claude` shim (so the
# sessions you start are mirrored to + drivable from your phone), puts it on PATH,
# and keeps the hub daemon alive via launchd. Reversible: nexting-cc-bridge uninstall.
echo "→ Setting up the Claude Code manager…"
if command -v nexting-cc-bridge >/dev/null 2>&1; then
  nexting-cc-bridge install
elif command -v npx >/dev/null 2>&1; then
  npx -y nexting-cc-bridge install
else
  echo "✗ Could not run nexting-cc-bridge install (no global bin / npx)."; exit 1
fi

echo
echo "Done. Run \`claude\` as usual — it now mirrors to your phone."
echo "Open Nexting on your phone → Claude Code to see and control your sessions."
echo "Bypass once with: NEXTING_CC_DISABLE=1 claude   ·   Remove with: nexting-cc-bridge uninstall"
