#!/usr/bin/env bash
# apiprice.app one-line installer (v0.1.0)
# Published at https://apiprice.app/install.sh. See the Claude Code / Codex guides for what was tested and what is uncovered.
# Installs Claude Code and/or Codex CLI and points them at a third-party API provider (v1: DeepSeek).
#
#   curl -fsSL https://apiprice.app/install.sh | bash                     # interactive
#   curl -fsSL https://apiprice.app/install.sh | bash -s -- --tool codex  # one tool
#   bash install.sh --uninstall [--tool claude-code|codex|all] [--remove-tool]
#
# The API key is NEVER accepted as a command-line argument (it would land in shell history / ps).
# It is read with hidden input from the terminal, or from env APIPRICE_API_KEY for unattended runs.
set -uo pipefail

VERSION="0.1.0"
TOOL="ask"            # claude-code | codex | all | ask
PROVIDER="deepseek"
MODEL=""
ACTION="install"      # install | uninstall
MIRROR="auto"         # auto | cn | official
METHOD="auto"         # auto | npm | binary | skip
DEEP_TEST=0
NO_TEST=0
REMOVE_TOOL=0
ASSUME_YES=0
ASSET_BASE="${APIPRICE_ASSET_BASE:-https://apiprice.app/installer/assets}"
STATE_DIR="${APIPRICE_HOME:-$HOME/.apiprice}"
BIN_DIR="$HOME/.local/bin"
MARK_BEGIN="# >>> apiprice.app installer >>>"
MARK_END="# <<< apiprice.app installer <<<"

# ---------- output helpers ----------
if [ -t 1 ]; then C_G=$'\033[32m'; C_R=$'\033[31m'; C_Y=$'\033[33m'; C_B=$'\033[1m'; C_0=$'\033[0m'; else C_G=; C_R=; C_Y=; C_B=; C_0=; fi
say()  { printf '%s\n' "$*"; }
step() { printf '%s==>%s %s\n' "$C_B" "$C_0" "$*"; }
ok()   { printf '%s[OK]%s %s\n' "$C_G" "$C_0" "$*"; }
warn() { printf '%s[!]%s %s\n' "$C_Y" "$C_0" "$*" >&2; }
fail() { printf '%s[FAIL]%s %s\n' "$C_R" "$C_0" "$*" >&2; }
die()  { fail "$*"; exit 1; }

usage() { cat <<U
apiprice.app installer $VERSION
Options:
  --tool claude-code|codex|all   which tool to set up (default: ask)
  --provider deepseek            API provider (v1: deepseek only)
  --model <id>                   override model (deepseek: deepseek-flash | deepseek-v4-pro)
  --mirror auto|cn|official      npm registry: npmmirror.com (cn) or registry.npmjs.org (default auto = fastest)
  --method auto|npm|binary|skip  how to install the CLI (auto: keep existing, else npm, else standalone binary)
  --deep-test                    also run a tool-call test (model writes + reads a file in a temp dir)
  --no-test                      skip the live verification call
  --uninstall                    restore the original config (and with --remove-tool, remove CLIs we installed)
  -y, --yes                      do not ask for confirmations
Key input: hidden prompt, or env APIPRICE_API_KEY. Never pass the key as an argument.
U
}

while [ $# -gt 0 ]; do
  case "$1" in
    --tool) TOOL="${2:-}"; shift ;;
    --provider) PROVIDER="${2:-}"; shift ;;
    --model) MODEL="${2:-}"; shift ;;
    --mirror) MIRROR="${2:-}"; shift ;;
    --method) METHOD="${2:-}"; shift ;;
    --deep-test) DEEP_TEST=1 ;;
    --no-test) NO_TEST=1 ;;
    --uninstall|--restore) ACTION="uninstall" ;;
    --remove-tool) REMOVE_TOOL=1 ;;
    -y|--yes) ASSUME_YES=1 ;;
    --key|--api-key) die "For safety the key cannot be passed as an argument. Run without it and paste it at the hidden prompt (or set APIPRICE_API_KEY)." ;;
    -h|--help) usage; exit 0 ;;
    *) die "Unknown option: $1 (see --help)" ;;
  esac
  shift
done

# Reading from the terminal works even under `curl ... | bash` (stdin is the script there).
TTY=""; if [ -r /dev/tty ] && { : </dev/tty; } 2>/dev/null; then TTY=/dev/tty; fi
ask() { # ask "prompt" default -> echoes answer
  local a=""; if [ -n "$TTY" ] && [ $ASSUME_YES = 0 ]; then printf '%s' "$1" >/dev/tty; IFS= read -r a </dev/tty || a=""; fi
  [ -z "$a" ] && a="$2"; printf '%s' "$a"
}

# ---------- provider registry (extend here) ----------
provider_load() {
  case "$1" in
    deepseek)
      P_NAME="DeepSeek"
      P_KEY_URL="https://platform.deepseek.com/api_keys"
      P_KEY_RE='^sk-[A-Za-z0-9]{16,128}$'
      P_MODELS_URL="https://api.deepseek.com/models"
      P_BALANCE_URL="https://api.deepseek.com/user/balance"
      P_ANTHROPIC_BASE="https://api.deepseek.com/anthropic"     # Claude Code (Anthropic Messages API)
      P_RESPONSES_BASE="https://api.deepseek.com"               # Codex (Responses API)
      P_CLAUDE_MODEL="${MODEL:-deepseek-flash}"
      P_CLAUDE_MODEL_1M="${P_CLAUDE_MODEL}[1m]"                  # per DeepSeek docs: [1m] tells Claude Code the 1M window
      P_CLAUDE_SMALL="deepseek-flash"
      P_CODEX_MODEL="${MODEL:-deepseek-flash}"
      P_CODEX_CATALOG="deepseek/codex-models.json"
      ;;
    *) die "Unsupported provider: $1 (v1 supports: deepseek)";;
  esac
}

# ---------- platform ----------
OS="$(uname -s)"; ARCH="$(uname -m)"
case "$OS" in Linux) PLAT_OS=linux;; Darwin) PLAT_OS=darwin;; MINGW*|MSYS*|CYGWIN*) die "On Windows please use PowerShell: irm https://apiprice.app/install.ps1 | iex";; *) die "Unsupported OS: $OS";; esac
case "$ARCH" in x86_64|amd64) PLAT_ARCH=x64;; arm64|aarch64) PLAT_ARCH=arm64;; *) die "Unsupported CPU: $ARCH";; esac
IS_MUSL=0; if [ "$PLAT_OS" = linux ] && { ls /lib/ld-musl-* >/dev/null 2>&1 || ldd --version 2>&1 | grep -qi musl; }; then IS_MUSL=1; fi

# portable timeout (macOS has no `timeout`)
run_to() { local secs="$1"; shift; "$@" & local pid=$!; ( sleep "$secs"; kill -TERM "$pid" 2>/dev/null ) & local w=$!; wait "$pid"; local rc=$?; kill "$w" 2>/dev/null; wait "$w" 2>/dev/null; return $rc; }

# curl with the key in a header, key passed via stdin config (never in argv)
curl_key() { # curl_key URL -> body on stdout, http code in $HTTP_CODE
  local out; out="$(printf 'header = "Authorization: Bearer %s"\n' "$API_KEY" | curl -sS -m 20 -K - -w '\n%{http_code}' "$1" 2>/dev/null)" || true
  HTTP_CODE="${out##*$'\n'}"; printf '%s' "${out%$'\n'*}"
}

mask() { local k="$1"; printf '%s****%s' "${k:0:3}" "${k: -4}"; }

sha512_b64() { if command -v openssl >/dev/null; then openssl dgst -sha512 -binary "$1" | openssl base64 -A; else python3 -c 'import sys,hashlib,base64;print(base64.b64encode(hashlib.sha512(open(sys.argv[1],"rb").read()).digest()).decode())' "$1"; fi; }
file_hash() { if command -v sha256sum >/dev/null; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi; }

# ---------- JSON helper (settings.json merge) : node -> python3 -> osascript(JXA) ----------
json_tool() {
  if command -v node >/dev/null 2>&1; then echo node; return; fi
  if command -v python3 >/dev/null 2>&1 && python3 -c 'import json' >/dev/null 2>&1; then echo python3; return; fi
  if [ "$PLAT_OS" = darwin ] && command -v osascript >/dev/null 2>&1; then echo jxa; return; fi
  echo none
}
# json_env_edit FILE MODE  (MODE=set: merge KEY=VALUE lines from stdin into .env ; MODE=unset: delete keys listed on stdin)
json_env_edit() {
  local file="$1" mode="$2" tool; tool="$(json_tool)"
  local input; input="$(cat)"
  case "$tool" in
    node) APP_FILE="$file" APP_MODE="$mode" APP_IN="$input" node -e '
const fs=require("fs");const f=process.env.APP_FILE;let o={};
if(fs.existsSync(f)){const t=fs.readFileSync(f,"utf8").trim(); if(t) o=JSON.parse(t);}
if(typeof o!=="object"||Array.isArray(o)) throw new Error("settings.json is not an object");
o.env=o.env||{};
for(const line of process.env.APP_IN.split("\n")){ if(!line) continue;
  if(process.env.APP_MODE==="set"){const i=line.indexOf("="); o.env[line.slice(0,i)]=line.slice(i+1);} else delete o.env[line]; }
if(Object.keys(o.env).length===0) delete o.env;
fs.writeFileSync(f, JSON.stringify(o,null,2)+"\n",{mode:0o600});' ;;
    python3) APP_FILE="$file" APP_MODE="$mode" APP_IN="$input" python3 -c '
import json,os
f=os.environ["APP_FILE"];o={}
if os.path.exists(f):
    t=open(f,encoding="utf-8").read().strip()
    if t: o=json.loads(t)
if not isinstance(o,dict): raise SystemExit("settings.json is not an object")
env=o.setdefault("env",{})
for line in os.environ["APP_IN"].split("\n"):
    if not line: continue
    if os.environ["APP_MODE"]=="set":
        k,v=line.split("=",1); env[k]=v
    else: env.pop(line,None)
if not env: o.pop("env",None)
fd=os.open(f,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,0o600)
with os.fdopen(fd,"w",encoding="utf-8") as h: h.write(json.dumps(o,indent=2,ensure_ascii=False)+"\n")' ;;
    jxa) APP_FILE="$file" APP_MODE="$mode" APP_IN="$input" osascript -l JavaScript -e '
ObjC.import("Foundation");
function env(k){return ObjC.unwrap($.NSProcessInfo.processInfo.environment.objectForKey(k));}
const f=env("APP_FILE");const fm=$.NSFileManager.defaultManager;let o={};
if(fm.fileExistsAtPath(f)){const t=ObjC.unwrap($.NSString.stringWithContentsOfFileEncodingError(f,$.NSUTF8StringEncoding,null)).trim(); if(t) o=JSON.parse(t);}
o.env=o.env||{};
env("APP_IN").split("\n").forEach(function(line){ if(!line) return;
  if(env("APP_MODE")==="set"){const i=line.indexOf("="); o.env[line.slice(0,i)]=line.slice(i+1);} else delete o.env[line]; });
if(Object.keys(o.env).length===0) delete o.env;
$(JSON.stringify(o,null,2)+"\n").writeToFileAtomicallyEncodingError(f,true,$.NSUTF8StringEncoding,null);' >/dev/null ;;
    *) return 3 ;;
  esac
  local rc=$?; [ -f "$file" ] && chmod 600 "$file"; return $rc
}

# ---------- backup / state ----------
# First install of a tool saves the original file once (or a marker that it did not exist).
backup_original() { # backup_original TOOL FILE
  local d="$STATE_DIR/backup/$1"; mkdir -p "$d"; chmod 700 "$STATE_DIR"
  local b="$d/$(basename "$2").orig"
  if [ -e "$b" ] || [ -e "$b.absent" ]; then return 0; fi   # keep the very first original (idempotent re-runs)
  if [ -f "$2" ]; then cp -p "$2" "$b"; chmod 600 "$b"; else : > "$b.absent"; fi
}
record_written() { local d="$STATE_DIR/backup/$1"; file_hash "$2" > "$d/$(basename "$2").written"; }
state_set() { mkdir -p "$STATE_DIR"; local f="$STATE_DIR/state"; touch "$f"; grep -v "^$1=" "$f" > "$f.tmp" 2>/dev/null; echo "$1=$2" >> "$f.tmp"; mv "$f.tmp" "$f"; }
state_get() { [ -f "$STATE_DIR/state" ] && grep "^$1=" "$STATE_DIR/state" | tail -1 | cut -d= -f2-; }

# ---------- npm registry / mirror ----------
REG=""
pick_registry() {
  case "$MIRROR" in
    cn) REG="https://registry.npmmirror.com";;
    official) REG="https://registry.npmjs.org";;
    *) local a b
       a=$(curl -s -o /dev/null -m 6 -w '%{http_code} %{time_total}' https://registry.npmjs.org/@openai%2fcodex 2>/dev/null || echo "000 9")
       b=$(curl -s -o /dev/null -m 6 -w '%{http_code} %{time_total}' https://registry.npmmirror.com/@openai%2fcodex 2>/dev/null || echo "000 9")
       if [ "${a%% *}" = 200 ] && { [ "${b%% *}" != 200 ] || awk -v x="${a#* }" -v y="${b#* }" 'BEGIN{exit !(x<=y)}'; }; then REG="https://registry.npmjs.org"; else REG="https://registry.npmmirror.com"; fi ;;
  esac
  say "    npm registry: $REG"
}

# ---------- tool definitions ----------
tool_cmd()  { case "$1" in claude-code) echo claude;; codex) echo codex;; esac; }
tool_pkg()  { case "$1" in claude-code) echo "@anthropic-ai/claude-code";; codex) echo "@openai/codex";; esac; }

ensure_path_line() {
  case ":$PATH:" in *":$BIN_DIR:"*) return 0;; esac
  local rc; case "${SHELL:-}" in */zsh) rc="$HOME/.zshrc";; */bash) if [ "$PLAT_OS" = darwin ]; then rc="$HOME/.bash_profile"; else rc="$HOME/.bashrc"; fi;; *) rc="$HOME/.profile";; esac
  if ! grep -qF "$MARK_BEGIN" "$rc" 2>/dev/null; then
    printf '\n%s\nexport PATH="$HOME/.local/bin:$PATH"\n%s\n' "$MARK_BEGIN" "$MARK_END" >> "$rc"
    state_set path_rc "$rc"; warn "Added ~/.local/bin to PATH in $rc — open a new terminal (or run: source $rc)."
  fi
  export PATH="$BIN_DIR:$PATH"
}

# standalone install from the npm platform tarball (no Node needed); integrity = registry sha512
install_binary() { # install_binary TOOL
  local t="$1" pkg ver meta url integ tmp plat
  pkg="$(tool_pkg "$t")"
  ver="$(curl -fsSL -m 20 "$REG/$pkg/latest" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p' | head -1)"
  [ -n "$ver" ] || { fail "Cannot read latest version of $pkg from $REG"; return 1; }
  plat="$PLAT_OS-$PLAT_ARCH"
  if [ "$t" = claude-code ]; then [ $IS_MUSL = 1 ] && plat="$plat-musl"; meta="$REG/$pkg-$plat/$ver"
  else meta="$REG/$pkg/$ver-$plat"; fi
  local j; j="$(curl -fsSL -m 20 "$meta")" || { fail "No $plat build for $pkg $ver"; return 1; }
  url="$(printf '%s' "$j" | sed -n 's/.*"tarball":"\([^"]*\)".*/\1/p' | head -1)"
  integ="$(printf '%s' "$j" | sed -n 's/.*"integrity":"sha512-\([^"]*\)".*/\1/p' | head -1)"
  tmp="$(mktemp -d)"; say "    downloading $pkg $ver ($plat) ..."
  curl -fSL $([ -t 2 ] && echo --progress-bar || echo -sS) -m 900 -o "$tmp/p.tgz" "$url" || { rm -rf "$tmp"; fail "Download failed: $url"; return 1; }
  [ "$(sha512_b64 "$tmp/p.tgz")" = "$integ" ] || { rm -rf "$tmp"; fail "Integrity check failed for $url"; return 1; }
  local dest="$STATE_DIR/tools/$t/$ver"; rm -rf "$dest"; mkdir -p "$dest" "$BIN_DIR"
  tar xzf "$tmp/p.tgz" -C "$dest" --strip-components=1 || { rm -rf "$tmp"; return 1; }; rm -rf "$tmp"
  local exe
  if [ "$t" = claude-code ]; then exe="$dest/claude"; else exe="$(ls "$dest"/vendor/*/bin/codex 2>/dev/null | head -1)"; fi
  [ -x "$exe" ] || { fail "Binary not found in package"; return 1; }
  # small wrapper (not a symlink) so the tool resolves its bundled resources from the real path
  printf '#!/bin/sh\n# managed by apiprice.app installer\nexec "%s" "$@"\n' "$exe" > "$BIN_DIR/$(tool_cmd "$t")"; chmod 755 "$BIN_DIR/$(tool_cmd "$t")"
  state_set "installed_$t" "binary:$ver"
  ensure_path_line
}

install_npm() {
  local t="$1" pkg prefix; pkg="$(tool_pkg "$t")"
  prefix="$(npm config get prefix 2>/dev/null)"
  local probe="$prefix"; while [ -n "$probe" ] && [ ! -e "$probe" ]; do probe="$(dirname "$probe")"; done   # prefix may not exist yet
  if [ -z "$prefix" ] || { [ ! -w "$prefix/lib" ] && [ ! -w "$probe" ]; }; then
    warn "npm global prefix $prefix is not writable (would need sudo). Using standalone binary instead."; return 2
  fi
  # Pin the exact latest version: with an old Node (e.g. 20 while claude-code needs >=22) npm silently picks
  # an OLD release whose "engines" matches (seen in testing: 2.1.197 instead of 2.1.302). The binary itself does not use Node.
  local ver; ver="$(curl -fsSL -m 20 "$REG/$pkg/latest" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p' | head -1)"
  [ -n "$ver" ] && pkg="$pkg@$ver"
  say "    npm install -g $pkg --registry=$REG"
  npm install -g "$pkg" --registry="$REG" --no-fund --no-audit --loglevel=error || return 1
  state_set "installed_$t" "npm"
  hash -r 2>/dev/null
}

ensure_tool() { # ensure_tool TOOL
  local t="$1" c; c="$(tool_cmd "$t")"
  if [ "$METHOD" != binary ] && [ "$METHOD" != npm ] && command -v "$c" >/dev/null 2>&1; then
    ok "$c already installed: $("$c" --version 2>/dev/null | head -1) ($(command -v "$c"))"; return 0
  fi
  [ "$METHOD" = skip ] && { fail "$c not installed and --method skip given"; return 1; }
  step "Installing $c"
  [ -n "$REG" ] || pick_registry
  local rc=1
  if [ "$METHOD" != binary ] && command -v npm >/dev/null 2>&1; then install_npm "$t"; rc=$?; fi
  if [ $rc -ne 0 ] && [ "$METHOD" != npm ]; then install_binary "$t"; rc=$?; fi
  [ $rc -eq 0 ] || { fail "Could not install $c"; return 1; }
  command -v "$c" >/dev/null 2>&1 || export PATH="$BIN_DIR:$PATH"
  ok "$c installed: $("$c" --version 2>/dev/null | head -1)"
}

# ---------- configure ----------
CLAUDE_KEYS="ANTHROPIC_BASE_URL ANTHROPIC_AUTH_TOKEN ANTHROPIC_MODEL ANTHROPIC_DEFAULT_OPUS_MODEL ANTHROPIC_DEFAULT_SONNET_MODEL ANTHROPIC_DEFAULT_HAIKU_MODEL CLAUDE_CODE_SUBAGENT_MODEL CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"
configure_claude() {
  local f="$HOME/.claude/settings.json"; mkdir -p "$HOME/.claude"
  backup_original claude-code "$f"
  if [ -f "$f" ] && [ "$(json_tool)" = none ]; then die "Need node, python3 (or macOS osascript) to merge existing $f"; fi
  printf '%s\n' \
    "ANTHROPIC_BASE_URL=$P_ANTHROPIC_BASE" \
    "ANTHROPIC_AUTH_TOKEN=$API_KEY" \
    "ANTHROPIC_MODEL=$P_CLAUDE_MODEL_1M" \
    "ANTHROPIC_DEFAULT_OPUS_MODEL=$P_CLAUDE_MODEL_1M" \
    "ANTHROPIC_DEFAULT_SONNET_MODEL=$P_CLAUDE_MODEL_1M" \
    "ANTHROPIC_DEFAULT_HAIKU_MODEL=$P_CLAUDE_SMALL" \
    "CLAUDE_CODE_SUBAGENT_MODEL=$P_CLAUDE_SMALL" \
    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1" | json_env_edit "$f" set || die "Failed to write $f"
  record_written claude-code "$f"
  # skip the first-run onboarding screen: only sets this one flag; it is intentionally NOT reverted on --uninstall
  # (~/.claude.json also holds Claude Code's own history/MCP state, so we never restore/delete that file)
  local cj="$HOME/.claude.json"
  if [ ! -f "$cj" ]; then printf '{\n  "hasCompletedOnboarding": true\n}\n' > "$cj"; chmod 600 "$cj"
  elif ! grep -q '"hasCompletedOnboarding": *true' "$cj"; then
    case "$(json_tool)" in node) APP_F="$cj" node -e 'const fs=require("fs");const f=process.env.APP_F;const o=JSON.parse(fs.readFileSync(f,"utf8"));o.hasCompletedOnboarding=true;fs.writeFileSync(f,JSON.stringify(o,null,2)+"\n")';;
      python3) APP_F="$cj" python3 -c 'import json,os;f=os.environ["APP_F"];o=json.load(open(f));o["hasCompletedOnboarding"]=True;open(f,"w").write(json.dumps(o,indent=2)+"\n")';; *) warn "Could not set hasCompletedOnboarding in $cj (first launch may show a setup screen)";; esac
  fi
  [ -n "${ANTHROPIC_API_KEY:-}" ] && warn "Your shell exports ANTHROPIC_API_KEY; it may override the DeepSeek token. Remove it from your shell profile."
  ok "Claude Code configured: $f (env block, chmod 600)"
}

codex_strip() { # remove our managed lines + conflicting top-level keys + [model_providers.<p>] section from stdin
  awk -v p="$1" -v top=1 -v mb="$MARK_BEGIN" -v me="$MARK_END" '
    $0==mb {skip=1; next} $0==me {skip=0; next} skip {next}
    /^[[:space:]]*\[/ { top=0; insec = ($0 ~ "^[[:space:]]*\\[model_providers\\." p "\\][[:space:]]*$") }
    insec {next}
    (top!=0) && /^[[:space:]]*(model|model_provider|model_catalog_json|model_reasoning_effort|web_search)[[:space:]]*=/ {next}
    {print}
  '
}
configure_codex() {
  local dir="${CODEX_HOME:-$HOME/.codex}" f; f="$dir/config.toml"; mkdir -p "$dir"
  backup_original codex "$f"; backup_original codex "$dir/models.json"
  # model catalog (from DeepSeek docs) — removes the "model metadata not found" warning
  local cat_src="" cat_dst="$dir/models.json"
  if [ -n "${APIPRICE_ASSET_DIR:-}" ] && [ -f "$APIPRICE_ASSET_DIR/$P_CODEX_CATALOG" ]; then cp "$APIPRICE_ASSET_DIR/$P_CODEX_CATALOG" "$cat_dst"; cat_src=local
  elif curl -fsSL -m 30 -o "$cat_dst.tmp" "$ASSET_BASE/$P_CODEX_CATALOG"; then mv "$cat_dst.tmp" "$cat_dst"; cat_src=remote
  else rm -f "$cat_dst.tmp"; warn "Could not fetch model catalog; Codex will show a metadata warning but still works."; fi
  local body=""; [ -f "$f" ] && body="$(codex_strip "$PROVIDER" < "$f")"
  local tmp; tmp="$(mktemp)"
  {
    echo "$MARK_BEGIN"
    echo "model = \"$P_CODEX_MODEL\""
    echo "model_provider = \"$PROVIDER\""
    echo "model_reasoning_effort = \"high\""
    echo "web_search = \"disabled\""
    [ -n "$cat_src" ] && echo "model_catalog_json = \"$cat_dst\""
    echo "$MARK_END"
    [ -n "$body" ] && printf '%s\n' "$body"
    echo ""
    echo "$MARK_BEGIN"
    echo "[model_providers.$PROVIDER]"
    echo "name = \"$P_NAME\""
    echo "base_url = \"$P_RESPONSES_BASE\""
    echo "wire_api = \"responses\""
    echo "experimental_bearer_token = \"$API_KEY\""
    echo "$MARK_END"
  } > "$tmp"
  # top-level keys must come before any [table]; our block is first, so the file stays valid TOML
  install -m 600 "$tmp" "$f"; rm -f "$tmp"
  record_written codex "$f"
  ok "Codex configured: $f (chmod 600)"
}

# ---------- verify ----------
verify_tool() { # verify_tool TOOL -> 0 pass
  local t="$1" c w out rc; c="$(tool_cmd "$t")"; w="$(mktemp -d)"
  step "Live test: $c → $P_NAME (one short request, costs a fraction of a cent)"
  if [ "$t" = claude-code ]; then
    out="$(cd "$w" && run_to 180 "$c" -p "Reply with exactly the two letters OK and nothing else." --output-format json </dev/null 2>"$w/err")"; rc=$?
    if [ $rc -eq 0 ] && printf '%s' "$out" | grep -q '"is_error":false' && printf '%s' "$out" | grep -q '"result":"OK'; then ok "Claude Code answered via $P_NAME (text call passed)"; else fail "Claude Code test failed (exit $rc): $(printf '%s' "$out" | head -c 300) $(head -c 300 "$w/err")"; rm -rf "$w"; return 1; fi
    if [ $DEEP_TEST = 1 ]; then local tok="apiprice-$RANDOM$RANDOM"
      (cd "$w" && run_to 300 "$c" -p "Create a file named proof.txt in the current directory containing exactly: $tok . Then read it back with the Read tool and report its contents." --allowedTools "Write,Read" --output-format json </dev/null >"$w/tool.json" 2>&1)
      if [ "$(tr -d '\n ' < "$w/proof.txt" 2>/dev/null)" = "$tok" ]; then ok "Tool call passed (Write + Read in temp dir)"; else fail "Tool-call test failed"; rm -rf "$w"; return 1; fi
    fi
  else
    run_to 180 "$c" exec --skip-git-repo-check -C "$w" -o "$w/last.txt" "Reply with exactly the two letters OK and nothing else." </dev/null >"$w/log" 2>&1; rc=$?
    if [ $rc -eq 0 ] && [ "$(tr -d '[:space:]' < "$w/last.txt" 2>/dev/null)" = OK ]; then ok "Codex answered via $P_NAME (text call passed)"; else fail "Codex test failed (exit $rc): $(grep -iE 'error|status' "$w/log" | head -3)"; rm -rf "$w"; return 1; fi
    if [ $DEEP_TEST = 1 ]; then local tok="apiprice-$RANDOM$RANDOM"
      run_to 300 "$c" exec --skip-git-repo-check -C "$w" -s workspace-write -c 'approval_policy="never"' "Create a file named proof.txt in the current directory containing exactly the text $tok (no newline needed), then run: cat proof.txt" </dev/null >"$w/tool.log" 2>&1
      if grep -q "$tok" "$w/proof.txt" 2>/dev/null; then ok "Tool call passed (file created + read via shell in temp dir)"; else fail "Tool-call test failed"; rm -rf "$w"; return 1; fi
    fi
  fi
  rm -rf "$w"; return 0
}

# ---------- uninstall ----------
restore_file() { # restore_file TOOL FILE -> 0 restored exactly; 1 no backup; 2 file changed since install (caller strips surgically)
  local d="$STATE_DIR/backup/$1" b; b="$d/$(basename "$2").orig"
  local wr; wr="$(cat "$d/$(basename "$2").written" 2>/dev/null)"
  [ -f "$b" ] || [ -f "$b.absent" ] || return 1
  if [ -f "$2" ] && [ -n "$wr" ] && [ "$(file_hash "$2")" != "$wr" ]; then
    warn "$2 was changed after install (by you or the tool): removing only our settings and keeping your other changes. Pre-install original kept at $b.kept"
    [ -f "$b" ] && mv "$b" "$b.kept"; rm -f "$b.absent" "$d/$(basename "$2").written"
    return 2
  fi
  if [ -f "$b" ]; then cp -p "$b" "$2"; ok "Restored original $2"; rm -f "$b"
  else rm -f "$2"; ok "Removed $2 (did not exist before install)"; rm -f "$b.absent"; fi
  rm -f "$d/$(basename "$2").written"; return 0
}
uninstall_tool() {
  local t="$1"
  step "Restoring $t"
  if [ "$t" = claude-code ]; then
    restore_file claude-code "$HOME/.claude/settings.json"
    if [ $? -ne 0 ] && [ -f "$HOME/.claude/settings.json" ]; then printf '%s\n' $CLAUDE_KEYS | json_env_edit "$HOME/.claude/settings.json" unset && ok "Removed our keys from ~/.claude/settings.json"; fi
  else
    local dir="${CODEX_HOME:-$HOME/.codex}"
    restore_file codex "$dir/config.toml"
    if [ $? -ne 0 ]; then
      [ -f "$dir/config.toml" ] && { codex_strip "$PROVIDER" < "$dir/config.toml" > "$dir/config.toml.tmp" && mv "$dir/config.toml.tmp" "$dir/config.toml"; ok "Removed apiprice block from $dir/config.toml"; }
    fi
    restore_file codex "$dir/models.json"; [ $? -eq 2 ] && warn "Left $dir/models.json in place (changed after install)"
  fi
  if [ $REMOVE_TOOL = 1 ]; then
    local how; how="$(state_get "installed_$t")"
    case "$how" in
      npm) if command -v npm >/dev/null 2>&1; then npm uninstall -g "$(tool_pkg "$t")" --loglevel=error && ok "Uninstalled $(tool_pkg "$t") (npm)"; else warn "npm not found; run: npm uninstall -g $(tool_pkg "$t")"; fi;;
      binary:*) rm -f "$BIN_DIR/$(tool_cmd "$t")"; rm -rf "$STATE_DIR/tools/$t"; ok "Removed standalone $(tool_cmd "$t")";;
      *) say "    $(tool_cmd "$t") was not installed by this installer; leaving it in place.";;
    esac
    [ "$how" = npm ] && ! command -v npm >/dev/null 2>&1 || state_set "installed_$t" ""
  fi
}

# ---------- main ----------
say "${C_B}apiprice.app installer $VERSION${C_0}  ($PLAT_OS-$PLAT_ARCH)"
case "$TOOL" in
  claude-code|codex|all) ;;
  ask) if [ "$ACTION" = uninstall ]; then TOOL=all; else
         c="$(ask "Which tool?  1) Claude Code  2) Codex  3) both  [3]: " 3)"
         case "$c" in 1) TOOL=claude-code;; 2) TOOL=codex;; *) TOOL=all;; esac; fi ;;
  *) die "--tool must be claude-code, codex or all";;
esac
TOOLS="$TOOL"; [ "$TOOL" = all ] && TOOLS="claude-code codex"
provider_load "$PROVIDER"

if [ "$ACTION" = uninstall ]; then
  for t in $TOOLS; do uninstall_tool "$t"; done
  if [ $REMOVE_TOOL = 1 ] && [ -n "$(state_get path_rc)" ]; then rc="$(state_get path_rc)"
    awk -v mb="$MARK_BEGIN" -v me="$MARK_END" '$0==mb{s=1;next} $0==me{s=0;next} !s' "$rc" > "$rc.tmp" && mv "$rc.tmp" "$rc"; ok "Removed PATH line from $rc"; state_set path_rc ""; fi
  ok "Done. Your previous settings are back."; exit 0
fi

# key
API_KEY="${APIPRICE_API_KEY:-}"
if [ -z "$API_KEY" ]; then
  [ -n "$TTY" ] || die "No terminal for the hidden key prompt. Set APIPRICE_API_KEY for unattended installs."
  say "Get a $P_NAME API key at: $P_KEY_URL"
  printf 'Paste your %s API key (input hidden): ' "$P_NAME" >/dev/tty
  IFS= read -rs API_KEY </dev/tty; printf '\n' >/dev/tty
fi
API_KEY="$(printf '%s' "$API_KEY" | tr -d '[:space:]')"
printf '%s' "$API_KEY" | grep -Eq "$P_KEY_RE" || die "That does not look like a $P_NAME key (expected sk-...)."

step "Checking key with $P_NAME ($(mask "$API_KEY"))"
curl_key "$P_MODELS_URL" >/dev/null
case "$HTTP_CODE" in
  200) ok "Key accepted (GET /models → 200)";;
  401|403) die "$P_NAME rejected the key (HTTP $HTTP_CODE). Check it at $P_KEY_URL";;
  000) die "Cannot reach $P_MODELS_URL. Check your network/proxy (HTTPS_PROXY is honoured).";;
  *) die "Unexpected HTTP $HTTP_CODE from $P_MODELS_URL";;
esac
bal="$(curl_key "$P_BALANCE_URL")"
if printf '%s' "$bal" | grep -q '"is_available":false'; then warn "Your $P_NAME balance is 0 — calls will fail with 402 until you top up."; fi

RESULT=0
for t in $TOOLS; do
  ensure_tool "$t" || { RESULT=1; continue; }
  if [ "$t" = claude-code ]; then configure_claude; else configure_codex; fi
  if [ $NO_TEST = 0 ]; then verify_tool "$t" || RESULT=1; fi
done
API_KEY=""

say ""
if [ $RESULT = 0 ]; then
  ok "All set. Open a new terminal, cd into your project and run: $(for t in $TOOLS; do printf '%s ' "$(tool_cmd "$t")"; done)"
  say "    Undo anytime: curl -fsSL https://apiprice.app/install.sh | bash -s -- --uninstall"
else
  fail "Setup finished with errors (see above). Nothing else was changed; undo with --uninstall."
  exit 1
fi
