#!/usr/bin/env bash
# ============================================================
#  Router One · Codex CLI 一键接入 / one-click setup
#  Docs: https://router.one/docs/guides/cli-setup
#
#  用法 / Usage:
#    curl -fsSL https://router.one/install/codex.sh | bash -s -- sk-your-api-key
#
#  做四件事 / What it does:
#    1. 安装 Codex CLI（npm 或官方安装器，如未安装）
#    2. 写入 ~/.codex/config.toml（Router One provider，env_key 认证）
#    3. 把 ROUTER_ONE_API_KEY 写入 shell 配置文件
#    4. 发送 1 token 测试请求验证连通
# ============================================================

if [ -t 1 ] && [ -z "$NO_COLOR" ]; then
  C_OK="$(printf '\033[32m')"
  C_WARN="$(printf '\033[33m')"
  C_ERR="$(printf '\033[31m')"
  C_DIM="$(printf '\033[2m')"
  C_OFF="$(printf '\033[0m')"
else
  C_OK=""; C_WARN=""; C_ERR=""; C_DIM=""; C_OFF=""
fi
ok()   { printf '%s[OK]%s %s\n' "$C_OK" "$C_OFF" "$1"; }
warn() { printf '%s[!]%s %s\n' "$C_WARN" "$C_OFF" "$1"; }
err()  { printf '%s[X]%s %s\n' "$C_ERR" "$C_OFF" "$1" >&2; }
info() { printf '%s>%s %s\n' "$C_DIM" "$C_OFF" "$1"; }

printf '\n%s\n\n' "Router One · Codex CLI 一键接入"

API_KEY="$1"
if [ -z "$API_KEY" ]; then API_KEY="$ROUTER_ONE_API_KEY"; fi
if [ -z "$API_KEY" ] && [ -e /dev/tty ]; then
  printf '请输入你的 Router One API Key / Enter your API key (sk-...): ' > /dev/tty
  IFS= read -r API_KEY < /dev/tty || API_KEY=""
fi
if [ -z "$API_KEY" ]; then
  err "缺少 API Key / missing API key"
  info "用法 / usage: curl -fsSL https://router.one/install/codex.sh | bash -s -- sk-your-api-key"
  info "先在 https://router.one/dashboard/api-keys 创建 API Key"
  exit 1
fi
if [ "$API_KEY" = "sk-your-api-key" ]; then
  err "请把 sk-your-api-key 替换成你的真实 API Key / replace the placeholder with your real key"
  info "在 https://router.one/dashboard/api-keys 创建后复制完整的 sk- 开头密钥"
  exit 1
fi
case "$API_KEY" in
  sk-*) : ;;
  *) warn "API Key 一般以 sk- 开头，请确认复制完整 / keys usually start with sk-" ;;
esac

# ---- 1. Codex CLI ------------------------------------------
if command -v codex >/dev/null 2>&1; then
  ok "检测到 Codex CLI / found Codex CLI: $(command -v codex)"
else
  if command -v npm >/dev/null 2>&1; then
    info "未检测到 Codex CLI，通过 npm 安装 / installing @openai/codex via npm..."
    npm install -g @openai/codex
  fi
  if ! command -v codex >/dev/null 2>&1; then
    info "通过官方安装器安装（无需 Node.js）/ installing via the official installer..."
    if curl -fsSL https://chatgpt.com/codex/install.sh | sh; then
      export PATH="$HOME/.local/bin:$PATH"
    else
      warn "官方安装器执行失败 / official installer failed"
    fi
  fi
  if command -v codex >/dev/null 2>&1; then
    ok "Codex CLI 安装完成 / installed"
  else
    warn "未能确认 codex 命令可用：安装可能未完成，或需重开终端后生效 / could not confirm codex on PATH — reopen your terminal if needed"
  fi
fi

# ---- 2. ~/.codex/config.toml -------------------------------
CODEX_DIR="$HOME/.codex"
CONFIG_FILE="$CODEX_DIR/config.toml"
mkdir -p "$CODEX_DIR"

if [ -f "$CONFIG_FILE" ]; then
  CONFIG_BACKUP="$CONFIG_FILE.bak.$(date +%Y%m%d%H%M%S)"
  cp "$CONFIG_FILE" "$CONFIG_BACKUP"
  warn "已有 config.toml，原文件备份到 / existing config backed up: $CONFIG_BACKUP"
fi
cat > "$CONFIG_FILE" <<'EOF'
model = "gpt-5.6-sol"
model_provider = "router"
model_reasoning_effort = "high"
model_verbosity = "high"
web_search = "live"

[model_providers.router]
base_url = "https://api.router.one/v1"
env_key = "ROUTER_ONE_API_KEY"
env_key_instructions = "Create an API key at https://router.one/dashboard/api-keys and set the ROUTER_ONE_API_KEY environment variable."
name = "Router One"
wire_api = "responses"
EOF
ok "已写入 $CONFIG_FILE (provider=router, env_key=ROUTER_ONE_API_KEY)"

# ---- 3. 持久化 API Key / persist the key -------------------
case "$SHELL" in
  */zsh) PROFILE_FILE="$HOME/.zshrc" ;;
  */bash) PROFILE_FILE="$HOME/.bashrc" ;;
  *) PROFILE_FILE="$HOME/.profile" ;;
esac
EXPORT_LINE="export ROUTER_ONE_API_KEY=\"$API_KEY\""
if [ -f "$PROFILE_FILE" ] && grep -qF "$EXPORT_LINE" "$PROFILE_FILE" 2>/dev/null; then
  info "$PROFILE_FILE 已包含相同的 ROUTER_ONE_API_KEY，跳过 / already configured"
else
  printf '\n# Router One API key (added by the Codex install script)\n%s\n' "$EXPORT_LINE" >> "$PROFILE_FILE"
  ok "已把 ROUTER_ONE_API_KEY 写入 $PROFILE_FILE"
  OLD_LINES="$(grep -c 'export ROUTER_ONE_API_KEY=' "$PROFILE_FILE" 2>/dev/null)"
  if [ -n "$OLD_LINES" ] && [ "$OLD_LINES" -gt 1 ] 2>/dev/null; then
    warn "检测到 $PROFILE_FILE 里有多条 ROUTER_ONE_API_KEY，以最后一条为准 / multiple entries found, the last one wins"
  fi
fi

# ---- 4. Verify ---------------------------------------------
info "发送一次 1 token 测试请求验证网关连通 / verifying gateway with a 1-token request..."
HTTP_STATUS="$(curl -s -o /dev/null -w '%{http_code}' --max-time 60 \
  -X POST "https://api.router.one/v1/chat/completions" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"auto","max_tokens":1,"messages":[{"role":"user","content":"ping"}]}')" || HTTP_STATUS="000"
FAILED=0
case "$HTTP_STATUS" in
  200) ok "网关连通，API Key 有效 / gateway reachable, key valid" ;;
  401)
    err "API Key 无效 (401)。配置已写入，但请到 https://router.one/dashboard/api-keys 检查或重新生成 Key。"
    FAILED=1
    ;;
  402) warn "API Key 有效但余额不足 (402)。请先充值 / top up first: https://router.one/dashboard" ;;
  000) warn "网络请求失败，跳过验证（配置已写入）/ network error, skipped verification" ;;
  *) warn "验证请求返回 HTTP $HTTP_STATUS (配置已写入)。排查见 / troubleshooting: https://router.one/docs/guides/cli-setup" ;;
esac

printf '\n'
if [ "$FAILED" = "1" ]; then
  err "配置完成，但 API Key 验证未通过 / setup finished but key verification failed"
  exit 1
fi
ok "全部完成！新开的终端可直接运行 codex / all set — new terminals can run codex directly"
info "当前终端需先执行 / in this terminal, first run:  source $PROFILE_FILE"
info "文档 / docs: https://router.one/docs/guides/cli-setup"
