#!/usr/bin/env bash
# Apigator x Claude Code CLI — one-command setup.
# Writes your Apigator config into ~/.claude/settings.json so `claude` runs on Apigator
# credits. Safe: backs up any existing settings and MERGES (keeps your other settings).
#
# Usage:
#   curl -fsSL https://apigator.ai/setup-claude-cli.sh | bash          # prompts for key
#   APIGATOR_KEY=sk-... bash <(curl -fsSL https://apigator.ai/setup-claude-cli.sh)
#
# Docs: https://apigator.ai/claude-cli   ·   raw: https://apigator.ai/claude-cli.md
set -euo pipefail

OPUS="claude-opus-4-8"
HAIKU="claude-haiku-4-5"
BASE_URL="https://claude.apigator.ai"
SETTINGS="$HOME/.claude/settings.json"

c_g() { printf "\033[32m%s\033[0m\n" "$1"; }
c_y() { printf "\033[33m%s\033[0m\n" "$1"; }
c_r() { printf "\033[1;31m%s\033[0m\n" "$1" >&2; }

command -v python3 >/dev/null 2>&1 || { c_r "python3 is required (used to safely merge JSON)."; exit 1; }

# ── Revert: switch back to your personal Claude subscription ──────────────────
#   curl -fsSL https://apigator.ai/setup-claude-cli.sh | bash -s revert
# Removes ONLY the Apigator keys this script added (keeps your other settings).
if [ "${1:-}" = "revert" ] || [ "${1:-}" = "uninstall" ]; then
  if [ ! -f "$SETTINGS" ]; then c_y "No $SETTINGS — nothing to revert."; exit 0; fi
  cp "$SETTINGS" "$SETTINGS.bak.$(date +%s 2>/dev/null || echo backup)"
  SETTINGS="$SETTINGS" python3 - <<'PY'
import json, os
p = os.environ["SETTINGS"]
try:
    with open(p) as f: cfg = json.load(f)
except Exception: cfg = {}
env = cfg.get("env")
if isinstance(env, dict):
    for k in ("ANTHROPIC_BASE_URL", "ANTHROPIC_API_KEY", "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL"):
        env.pop(k, None)
    if env: cfg["env"] = env
    else: cfg.pop("env", None)
with open(p, "w") as f:
    json.dump(cfg, f, indent=2); f.write("\n")
PY
  c_g "✓ Removed Apigator config from $SETTINGS (backed up)."
  echo
  echo "To use your personal Claude subscription again:"
  echo "  claude /login        # sign back into your Anthropic account"
  echo "(If you used --bare anywhere, drop it too.)"
  exit 0
fi

# 1. Get the key
KEY="${APIGATOR_KEY:-}"
if [ -z "$KEY" ]; then
  printf "Paste your Apigator API key (sk-...), then press Enter: "
  read -r KEY < /dev/tty
fi
case "$KEY" in
  sk-*) : ;;
  *) c_r "That doesn't look like an Apigator key (should start with 'sk-'). Aborting."; exit 1 ;;
esac

# 2. Back up any existing settings
mkdir -p "$HOME/.claude"
if [ -f "$SETTINGS" ]; then
  cp "$SETTINGS" "$SETTINGS.bak.$(date +%s 2>/dev/null || echo backup)"
  c_y "Backed up existing settings to $SETTINGS.bak.*"
fi

# 3. Merge the Apigator env block into settings.json (preserve everything else)
KEY="$KEY" BASE_URL="$BASE_URL" OPUS="$OPUS" HAIKU="$HAIKU" SETTINGS="$SETTINGS" python3 - <<'PY'
import json, os
p = os.environ["SETTINGS"]
try:
    with open(p) as f: cfg = json.load(f)
    if not isinstance(cfg, dict): cfg = {}
except Exception:
    cfg = {}
env = cfg.get("env")
if not isinstance(env, dict): env = {}
env.update({
    "ANTHROPIC_BASE_URL": os.environ["BASE_URL"],
    "ANTHROPIC_API_KEY": os.environ["KEY"],
    "ANTHROPIC_MODEL": os.environ["OPUS"],
    "ANTHROPIC_SMALL_FAST_MODEL": os.environ["HAIKU"],
})
cfg["env"] = env
with open(p, "w") as f:
    json.dump(cfg, f, indent=2)
    f.write("\n")
PY
chmod 600 "$SETTINGS" 2>/dev/null || true

c_g "✓ Wrote $SETTINGS — Claude Code now runs on Apigator."
echo
echo "Next:"
echo "  1. If you have a personal Claude login:  claude /logout   (once, so it doesn't ask)"
echo "  2. Start it:                             claude"
echo "  3. Verify:                               claude -p \"Reply with exactly: apigator ok\""
echo
c_y "Claude is allowlist-gated. If you get 403 key_model_access_denied, ask MixerBox to enable Claude for your account."
