#!/bin/bash
# Codex Key Tool (Mac) — double-click là chạy, không cần cài gì thêm.
set -euo pipefail
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

CODEX_DIR="$HOME/.codex"
AUTH="$CODEX_DIR/auth.json"
CFG="$CODEX_DIR/config.toml"
MARKER="$CODEX_DIR/.codex-key-tool-applied"
BACKUP="$CODEX_DIR/.codex-key-tool-backup/config.toml"

alert() {
  osascript -e "display alert \"Codex Key Tool\" message \"$1\" as ${2:-informational}" >/dev/null 2>&1 || true
}

confirm() {
  osascript -e "display dialog \"$1\" buttons {\"Huỷ\", \"OK\"} default button \"OK\" with icon caution" 2>/dev/null | grep -q "OK"
}

json_escape() {
  python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))' <<<"$1" 2>/dev/null | sed 's/^"//;s/"$//'
}

write_auth() {
  local key="$1"
  mkdir -p "$CODEX_DIR"
  if command -v python3 >/dev/null 2>&1; then
    AUTH_PATH="$AUTH" KEY="$key" python3 <<'PY'
import json, os
from pathlib import Path
p = Path(os.environ["AUTH_PATH"])
data = {"auth_mode": "apikey", "OPENAI_API_KEY": os.environ["KEY"]}
p.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
PY
  else
    local esc
    esc=$(printf '%s' "$key" | sed 's/\\/\\\\/g; s/"/\\"/g')
    printf '{\n  "auth_mode": "apikey",\n  "OPENAI_API_KEY": "%s"\n}\n' "$esc" >"$AUTH"
  fi
}

write_config_cli() {
  cat >"$CFG" <<'EOF'
# Codex API-only — Nghimmo (macOS)
model = "gpt-5.6-sol"
model_provider = "Nghimmo"
model_reasoning_effort = "medium"
sandbox_mode = "danger-full-access"
approval_policy = "never"

[model_providers.Nghimmo]
name = "Nghimmo"
base_url = "https://api.nghimmo.com/v1"
env_key = "OPENAI_API_KEY"
wire_api = "responses"
request_max_retries = 2
stream_max_retries = 4
stream_idle_timeout_ms = 120000

[agents.subagent]
model = "nghi/gpt-5.4-mini"
EOF
}

write_config_app() {
  cat >"$CFG" <<'EOF'
# API-only FAST (macOS)
model = "gpt-5.6-sol"
model_provider = "Nghimmo"
model_reasoning_effort = "low"
sandbox_mode = "danger-full-access"
approval_policy = "never"

[model_providers.Nghimmo]
name = "Nghimmo"
base_url = "https://api.nghimmo.com/v1"
env_key = "OPENAI_API_KEY"
wire_api = "responses"
request_max_retries = 2
stream_max_retries = 3
stream_idle_timeout_ms = 90000

[desktop]
followUpQueueMode = "queue"

[agents.subagent]
model = "nghi/gpt-5.4-mini"

[features]
js_repl = false
EOF
}

clear_proxies() {
  for v in HTTP_PROXY HTTPS_PROXY ALL_PROXY http_proxy https_proxy all_proxy NO_PROXY no_proxy; do
    launchctl unsetenv "$v" 2>/dev/null || true
  done
}

apply_mode() {
  local mode="$1" key="$2"
  mkdir -p "$CODEX_DIR"
  clear_proxies
  if [ "$mode" = "app" ] && [ -f "$CFG" ] && [ ! -f "$BACKUP" ]; then
    mkdir -p "$(dirname "$BACKUP")"
    cp "$CFG" "$BACKUP"
  fi
  write_auth "$key"
  if [ "$mode" = "app" ]; then write_config_app; else write_config_cli; fi
  printf '{\n  "mode": "%s",\n  "version": "2.2.8",\n  "api_only": true\n}\n' "$mode" >"$MARKER"
  if [ "$mode" = "app" ]; then
    launchctl setenv OPENAI_API_KEY "$key" 2>/dev/null || true
  else
    launchctl unsetenv OPENAI_API_KEY 2>/dev/null || true
  fi
}

reset_all() {
  clear_proxies
  rm -f "$AUTH"
  if [ -f "$BACKUP" ]; then cp "$BACKUP" "$CFG"; elif [ -f "$MARKER" ]; then rm -f "$CFG"; fi
  rm -f "$MARKER"
  launchctl unsetenv OPENAI_API_KEY 2>/dev/null || true
}

pick_action() {
  osascript <<'APPLE' 2>/dev/null || echo "login"
set choices to {"Đăng nhập / đổi key", "Reset cấu hình", "Thoát"}
set picked to choose from list choices with prompt "Codex Key Tool — chọn thao tác:" default items {"Đăng nhập / đổi key"}
if picked is false then return "exit"
if item 1 of picked is "Reset cấu hình" then return "reset"
if item 1 of picked is "Thoát" then return "exit"
return "login"
APPLE
}

pick_mode() {
  osascript <<'APPLE' 2>/dev/null || echo "app"
set choices to {"Desktop (app ChatGPT)", "CLI (terminal codex)"}
set picked to choose from list choices with prompt "Dùng Codex ở đâu?" default items {"Desktop (app ChatGPT)"}
if picked is false then return "app"
if item 1 of picked contains "CLI" then return "cli"
return "app"
APPLE
}

ask_key() {
  osascript <<'APPLE' 2>/dev/null || true
set dlg to display dialog "Dán License key Codex (sk-...):" default answer "" with hidden answer buttons {"Huỷ", "OK"} default button "OK" with title "Codex Key Tool"
return text returned of dlg
APPLE
}

# --- main ---
action="$(pick_action)"
case "$action" in
  exit|"") exit 0 ;;
  reset)
    if confirm "Reset cấu hình Codex trên máy này?"; then
      reset_all
      alert "Đã reset xong. Mở lại app ChatGPT nếu đang dùng Desktop." "informational"
    fi
    exit 0
    ;;
esac

mode="$(pick_mode)"
key="$(ask_key)"
key="$(printf '%s' "$key" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"

if [ -z "$key" ]; then
  alert "Chưa nhập key." "warning"
  exit 1
fi
if [ "${#key}" -lt 8 ] || [[ "$key" == *YOUR_API_KEY* ]]; then
  alert "Key không hợp lệ. Kiểm tra lại." "warning"
  exit 1
fi

apply_mode "$mode" "$key"

if [ "$mode" = "app" ]; then
  msg="Xong! Thoát hẳn app ChatGPT rồi mở lại để dùng Codex Desktop."
  if [ -d "/Applications/ChatGPT.app" ]; then
    open -a "ChatGPT" 2>/dev/null || true
  fi
else
  msg="Xong! Mở Terminal và gõ: codex"
fi
alert "$msg" "informational"
