#!/usr/bin/env bash
# Cheshire Terminal Computer — ONE-SHOT curl entry (exclusive agent access)
# Usage:
#   curl -fsSL https://cheshireterminal.ai/api/e2b/install.sh | bash
#   CHESHIRE_API_KEY=ct_sk_... curl -fsSL https://cheshireterminal.ai/api/e2b/install.sh | bash
#   CHESHIRE_INSTALL_PACKAGES=0 curl -fsSL https://cheshireterminal.ai/api/e2b/install.sh | bash   # skip npm packages
#
# This is the ONLY way to receive a box agent (Kimi K3 / trade agent).
# Also installs Zero Clawd (clawdbot-go) + cheshire-terminal-agents when Node/npm exist.
# E2B template cheshire-terminal-computer preinstalls the same packages in the desk shell.
# Saves oneshot token to ~/.cheshire/oneshot-token (mode 600).
set -euo pipefail

ORIGIN="${CHESHIRE_SITE_ORIGIN:-https://cheshireterminal.ai}"
API_KEY="${CHESHIRE_API_KEY:-}"
AGENT_BACKEND="${CHESHIRE_AGENT_BACKEND:-kimi-k3}"
INSTALL_PACKAGES="${CHESHIRE_INSTALL_PACKAGES:-1}"
OPEN_BROWSER=1
WITH_AGENT=1
SKIP_ONESHOT=0
# Portable under macOS bash 3.2 + set -u (empty "$@" / arrays are "unbound")
while [[ $# -gt 0 ]]; do
  case "$1" in
    --no-open) OPEN_BROWSER=0 ;;
    --no-agent) WITH_AGENT=0 ;;
    --no-packages) INSTALL_PACKAGES=0 ;;
    --packages-only) INSTALL_PACKAGES=1; WITH_AGENT=0; OPEN_BROWSER=0; SKIP_ONESHOT=1 ;;
    --claude) AGENT_BACKEND=claude-code ;;
    --kimi) AGENT_BACKEND=kimi-k3 ;;
  esac
  shift
done

need() { command -v "$1" >/dev/null 2>&1 || { echo "ERROR: need $1" >&2; exit 1; }; }
need curl

HOME_DIR="${CHESHIRE_HOME:-$HOME/.cheshire}"
mkdir -p "$HOME_DIR/credentials"
chmod 700 "$HOME_DIR" "$HOME_DIR/credentials" 2>/dev/null || true

echo ""
echo "╔══════════════════════════════════════════════════════════════════╗"
echo "║  🦞 Cheshire Terminal — one-shot computer + exclusive agent      ║"
echo "╚══════════════════════════════════════════════════════════════════╝"
echo "   API:    $ORIGIN"
echo "   Agent:  $AGENT_BACKEND (oneshot-only)"
if [[ "$SKIP_ONESHOT" -eq 1 ]]; then
  echo "   Mode:   packages-only (clawdbot-go + cheshire-terminal-agents)"
fi
echo ""

OK=""; PORTAL=""; SHELL=""; PRODUCT=""; SID=""; TOKEN=""; BOX=""; COMPUTER_UI=""; AGENT_URL=""; ERR=""
SHELL_URL=""

if [[ "$SKIP_ONESHOT" -ne 1 ]]; then
  # Avoid empty-array expansion under set -u (bash 3.2 / macOS: AUTH_ARGS[@] unbound)
  WITH_AGENT_JSON=true
  if [[ "$WITH_AGENT" -ne 1 ]]; then WITH_AGENT_JSON=false; fi

  ONESHOT_BODY="{\"agentBackend\":\"${AGENT_BACKEND}\",\"withAgent\":${WITH_AGENT_JSON}}"
  if [[ -n "$API_KEY" ]]; then
    RESP="$(curl -sS -X POST "${ORIGIN}/api/e2b/oneshot" \
      -H "Authorization: Bearer ${API_KEY}" \
      -H "Content-Type: application/json" \
      -H "Accept: application/json" \
      -H "User-Agent: cheshire-oneshot-curl/1.0" \
      -d "$ONESHOT_BODY" || true)"
  else
    RESP="$(curl -sS -X POST "${ORIGIN}/api/e2b/oneshot" \
      -H "Content-Type: application/json" \
      -H "Accept: application/json" \
      -H "User-Agent: cheshire-oneshot-curl/1.0" \
      -d "$ONESHOT_BODY" || true)"
  fi

  if command -v jq >/dev/null 2>&1; then
    OK="$(echo "$RESP" | jq -r '.ok // empty' 2>/dev/null || true)"
    PORTAL="$(echo "$RESP" | jq -r '.portalUrl // empty' 2>/dev/null || true)"
    SHELL="$(echo "$RESP" | jq -r '.shellUrl // empty' 2>/dev/null || true)"
    PRODUCT="$(echo "$RESP" | jq -r '.productTerminal // empty' 2>/dev/null || true)"
    SID="$(echo "$RESP" | jq -r '.sandboxId // empty' 2>/dev/null || true)"
    TOKEN="$(echo "$RESP" | jq -r '.oneshotToken // empty' 2>/dev/null || true)"
    BOX="$(echo "$RESP" | jq -r '.agentBox.id // empty' 2>/dev/null || true)"
    COMPUTER_UI="$(echo "$RESP" | jq -r '.computerUi // .siteComputer // empty' 2>/dev/null || true)"
    AGENT_URL="$(echo "$RESP" | jq -r '.agentServiceUrl // empty' 2>/dev/null || true)"
    ERR="$(echo "$RESP" | jq -r '.error // empty' 2>/dev/null || true)"
  else
    OK=""; PORTAL=""; SHELL=""; PRODUCT=""; SID=""; TOKEN=""; BOX=""; COMPUTER_UI=""; AGENT_URL=""; ERR="$RESP"
  fi

  if [[ "$OK" != "true" || -z "$TOKEN" ]]; then
    echo "ERROR: one-shot failed"
    echo "$RESP" | head -c 900
    echo ""
    echo "Tips:"
    echo "  • Server needs E2B_API_KEY (+ UPSTASH_BOX_API_KEY for agent)"
    echo "  • Rate limit: try again later or pass CHESHIRE_API_KEY"
    echo "  • Packages only (no E2B): curl -fsSL $ORIGIN/api/e2b/install.sh | bash -s -- --packages-only"
    exit 1
  fi

  # Persist exclusive agent claim (never commit this file)
  printf '%s\n' "$TOKEN" > "$HOME_DIR/oneshot-token"
  chmod 600 "$HOME_DIR/oneshot-token" 2>/dev/null || true
  if [[ -n "$API_KEY" ]]; then
    printf '%s\n' "$API_KEY" > "$HOME_DIR/credentials/api-key"
    chmod 600 "$HOME_DIR/credentials/api-key" 2>/dev/null || true
  fi
fi

# Default agent URL. Do NOT expand CHESHIRE_AGENT_URL under set -u
# (some bash builds still trip on ${UNSET:-default} inside pipefail installs).
if [[ -z "${AGENT_URL:-}" || "${AGENT_URL}" == "null" ]]; then
  AGENT_URL="https://cheshire-agent.fly.dev"
fi
# Normalize null/empty jq leftovers
BOX="${BOX:-}"
SID="${SID:-}"
PORTAL="${PORTAL:-}"
SHELL_URL="${SHELL:-}"
PRODUCT="${PRODUCT:-}"
COMPUTER_UI="${COMPUTER_UI:-}"

if [[ "$SKIP_ONESHOT" -ne 1 ]]; then
  # agent-env.sh via printf only — NEVER unquoted <<EOF heredoc (set -u expands
  # $CHESHIRE_* inside the body before exports exist → "unbound variable").
  # POSIX function names cannot contain hyphens (dash/sh rejects them), so we define
  # cheshire_agent_* and add bash/zsh aliases with hyphens when available.
  {
    echo "# Cheshire oneshot agent env (generated by install.sh)"
    echo "# bash/zsh:  source ~/.cheshire/agent-env.sh && cheshire-agent-connect"
    echo "# sh:        . ~/.cheshire/agent-env.sh && cheshire_agent_connect"
    echo "# curl-only: curl -sS -X POST \"\$CHESHIRE_AGENT_URL/v1/connect\" -H \"X-Cheshire-Oneshot: \$CHESHIRE_ONESHOT_TOKEN\" -H 'Content-Type: application/json' -d '{}'"
    echo "export CHESHIRE_SITE_ORIGIN='$ORIGIN'"
    echo "export CHESHIRE_ONESHOT_TOKEN='$TOKEN'"
    echo "export CHESHIRE_AGENT_BOX_ID='$BOX'"
    echo "export CHESHIRE_E2B_SANDBOX_ID='$SID'"
    echo "export CHESHIRE_AGENT_URL='$AGENT_URL'"
    echo "cheshire_agent_connect() {"
    echo "  curl -sS -X POST \"\$CHESHIRE_AGENT_URL/v1/connect\" \\"
    echo "    -H \"X-Cheshire-Oneshot: \$CHESHIRE_ONESHOT_TOKEN\" \\"
    echo "    -H 'Content-Type: application/json' -d '{}'"
    echo "}"
    echo "cheshire_agent_trade() {"
    echo "  curl -sS -X POST \"\$CHESHIRE_AGENT_URL/v1/trade\" \\"
    echo "    -H \"X-Cheshire-Oneshot: \$CHESHIRE_ONESHOT_TOKEN\" \\"
    echo "    -H 'Content-Type: application/json' \"\$@\""
    echo "}"
    echo "cheshire_agent_chat() {"
    echo "  curl -sS -X POST \"\$CHESHIRE_AGENT_URL/v1/chat\" \\"
    echo "    -H \"X-Cheshire-Oneshot: \$CHESHIRE_ONESHOT_TOKEN\" \\"
    echo "    -H 'Content-Type: application/json' \"\$@\""
    echo "}"
    echo "cheshire_agent() {"
    echo "  curl -sS -X POST \"\$CHESHIRE_SITE_ORIGIN/api/boxes/trade/quick\" \\"
    echo "    -H \"X-Cheshire-Oneshot: \$CHESHIRE_ONESHOT_TOKEN\" \\"
    echo "    -H 'Content-Type: application/json' \"\$@\""
    echo "}"
    echo "# Hyphen aliases for bash/zsh (ignored on dash if alias unsupported)"
    echo "if command -v alias >/dev/null 2>&1; then"
    echo "  alias cheshire-agent-connect=cheshire_agent_connect 2>/dev/null || true"
    echo "  alias cheshire-agent-trade=cheshire_agent_trade 2>/dev/null || true"
    echo "  alias cheshire-agent-chat=cheshire_agent_chat 2>/dev/null || true"
    echo "  alias cheshire-agent=cheshire_agent 2>/dev/null || true"
    echo "fi"
  } > "$HOME_DIR/agent-env.sh"
  chmod 600 "$HOME_DIR/agent-env.sh" 2>/dev/null || true

  TOKEN_PREFIX="${TOKEN:0:12}"
  echo "✓ One-shot claim minted (agent exclusive)"
  echo "  Token    ${TOKEN_PREFIX}…  → $HOME_DIR/oneshot-token"
  echo "  Sandbox  $SID"
  echo "  Portal   $PORTAL"
  echo "  Shell    $SHELL_URL"
  if [[ -n "$BOX" ]]; then echo "  Box      $BOX  ($AGENT_BACKEND)"; fi
  echo "  Product  $PRODUCT"
  if [[ -n "$COMPUTER_UI" ]]; then echo "  Desk UI  $COMPUTER_UI"; fi
  echo "  Agent WS $AGENT_URL  (Fly Machine / Render)"
  echo ""
  echo "Connect:"
  echo "  # bash / zsh"
  echo "  source $HOME_DIR/agent-env.sh && cheshire-agent-connect"
  echo "  # plain sh (dash) — use dot + underscore name"
  echo "  . $HOME_DIR/agent-env.sh && cheshire_agent_connect"
  echo "  # always works:"
  echo "  curl -sS -X POST $AGENT_URL/v1/connect \\"
  echo "    -H \"X-Cheshire-Oneshot: $TOKEN\" -H 'Content-Type: application/json' -d '{}'"
  echo ""
fi

# ── Zero Clawd (clawdbot-go) + cheshire-terminal-agents ─────────────────────
# Same packages preinstalled in the E2B template (cheshire-terminal-computer).
if [[ "$INSTALL_PACKAGES" == "1" || "$INSTALL_PACKAGES" == "true" ]]; then
  if command -v npm >/dev/null 2>&1; then
    echo "Installing Zero Clawd stack (clawdbot-go + cheshire-terminal-agents)…"
    npm install -g clawdbot-go@1.0.2 cheshire-terminal-agents@1.48.0 2>/dev/null \
      || npm install -g clawdbot-go cheshire-terminal-agents \
      || npm install --prefix "$HOME_DIR/npm" clawdbot-go cheshire-terminal-agents || true
    export PATH="$HOME_DIR/npm/bin:${PATH:-}"
    CLAWDBOT_SKIP_GO="${CLAWDBOT_SKIP_GO:-1}" CLAWDBOT_SKIP_BIRTH="${CLAWDBOT_SKIP_BIRTH:-1}" \
      npx --yes clawdbot-go skills-install --force 2>/dev/null || true
    echo "  npm:     clawdbot-go · cheshire-terminal-agents"
    echo "  package: https://www.npmjs.com/package/clawdbot-go"
    echo "  console: https://cheshireterminal.ai/zeroclawd"
    echo "  agents:  https://cheshireterminal.ai/agents"
    echo "  try:     npx clawdbot-go skills-install --force"
  else
    echo "Node/npm not found — skip local package install (E2B desk has them preinstalled)."
    echo "  Or: curl -fsSL https://raw.githubusercontent.com/Solizardking/Zero-Bruh/main/install-npm.sh | bash"
    echo "  npm:  https://www.npmjs.com/package/clawdbot-go"
    if [[ "$SKIP_ONESHOT" -eq 1 ]]; then
      exit 1
    fi
  fi
fi

if [[ "$OPEN_BROWSER" -eq 1 && -n "${PORTAL:-}${COMPUTER_UI:-}" ]]; then
  OPEN_URL="$PORTAL"
  if [[ -n "$COMPUTER_UI" ]]; then OPEN_URL="$COMPUTER_UI"; fi
  if command -v open >/dev/null 2>&1; then open "$OPEN_URL" >/dev/null 2>&1 || true
  elif command -v xdg-open >/dev/null 2>&1; then xdg-open "$OPEN_URL" >/dev/null 2>&1 || true
  else echo "Open: $OPEN_URL"
  fi
fi

echo "Done."
if [[ "$SKIP_ONESHOT" -ne 1 ]]; then
  echo "  Log into the shell and run:  cheshire status"
fi
echo "  Zero Clawd packages: clawdbot-go · cheshire-terminal-agents"
echo "  Connect: https://cheshireterminal.ai/zeroclawd"
