#!/usr/bin/env bash
# Codex login toggle - download from pool.yulitongxing.com/switch
# Run again any time to flip between OFFICIAL login and the team GATEWAY.
# Only touches ~/.codex/config.toml and ~/.codex/auth.json, with backups each run.
set -u
DIR="${CODEX_TOGGLE_HOME:-$HOME/.codex}"
GW='https://api.yulitongxing.com/v1'
CFG="$DIR/config.toml"; AUTH="$DIR/auth.json"
OFF="$DIR/auth.official.json"; KEYF="$DIR/.gateway_key"
PY="$(command -v python3 || true)"
[ -n "$PY" ] || { echo "[X] python3 not found (needed for safe JSON/TOML edit)"; exit 1; }
[ -f "$CFG" ] || { echo "[X] config.toml not found in $DIR - install and run Codex once first."; exit 1; }
[ -f "$AUTH" ] || { echo "[X] auth.json not found in $DIR"; exit 1; }
TS=$(date +%Y%m%d-%H%M%S)
cp "$CFG" "$CFG.bak-$TS"; cp "$AUTH" "$AUTH.bak-$TS"
# 先判断方向；若要切到网关且本机没有缓存 key，在 bash 层读入（heredoc 会占用 python 的 stdin）
IS_GW=0
if grep -q '^openai_base_url[[:space:]]*=' "$CFG" && grep '^openai_base_url[[:space:]]*=' "$CFG" | grep -q yulitongxing; then
  IS_GW=1
fi
if [ "$IS_GW" -eq 0 ] && [ ! -f "$KEYF" ]; then
  printf 'Paste your gateway key (sk-...): '
  read -r KEYIN
  [ -n "$KEYIN" ] || { echo "[X] empty key - aborted, nothing changed."; exit 1; }
  printf '%s' "$KEYIN" > "$KEYF"
fi
"$PY" - "$DIR" "$GW" "$TS" <<'PYEOF'
import json, re, sys
from pathlib import Path
d, gw, ts = Path(sys.argv[1]), sys.argv[2], sys.argv[3]
cfg, auth = d / "config.toml", d / "auth.json"
off, keyf = d / "auth.official.json", d / ".gateway_key"
POOL = r"gpt-6-astra|gpt-5\.5|gpt-5\.6-[A-Za-z0-9_.-]+|gpt-5\.3-codex-spark|codex-auto-review|gpt-oss-[A-Za-z0-9_.-]+|gemini-[A-Za-z0-9_.-]+|grok-[A-Za-z0-9_.-]+|deepseek-[A-Za-z0-9_.-]+|claude-[A-Za-z0-9_.-]+"
c = cfg.read_text(encoding="utf-8")
on_gw = re.search(r'(?m)^openai_base_url\s*=\s*"[^"]*yulitongxing', c) is not None
if on_gw:
    c = re.sub(r'(?m)^#?\s*openai_base_url[^\r\n]*\r?\n?', '', c)
    if not off.exists():
        j = json.loads(auth.read_text(encoding="utf-8"))
        j.pop("OPENAI_API_KEY", None)
        j["auth_mode"] = "chatgpt"
        off.write_text(json.dumps(j, indent=2, ensure_ascii=False), encoding="utf-8")
    auth.write_text(off.read_text(encoding="utf-8"), encoding="utf-8")
    c = re.sub(r'(?m)^(model\s*=\s*"(?:%s)"\s*)$' % POOL, r'# \1  # toggled-to-official ' + ts, c)
    cfg.write_text(c, encoding="utf-8")
    print("[OK] switched to OFFICIAL OpenAI login.")
else:
    if not off.exists():
        off.write_text(auth.read_text(encoding="utf-8"), encoding="utf-8")
    key = keyf.read_text(encoding="utf-8").strip() if keyf.exists() else ""
    if not key:
        print("[X] empty key - aborted, nothing changed."); sys.exit(1)
    auth.write_text(json.dumps({"OPENAI_API_KEY": key}, indent=2), encoding="utf-8")
    c = re.sub(r'(?m)^#?\s*openai_base_url[^\r\n]*\r?\n?', '', c)
    c = 'openai_base_url = "%s"\n' % gw + c
    c = re.sub(r'(?m)^# (model\s*=\s*"(?:%s)"\s*)(#.*)?$' % POOL, r'\1', c)
    if re.search(r'(?m)^model\s*=', c) is None:
        c = re.sub(r'(?m)^(openai_base_url\s*=\s*"[^"]*"\s*)$', r'\1\nmodel = "gpt-6-astra"', c)
    cfg.write_text(c, encoding="utf-8")
    print("[OK] switched to GATEWAY api.yulitongxing.com.")
print("Backups created: *.bak-%s (config.toml / auth.json)" % ts)
print("Now FULLY quit Codex and reopen it.")
PYEOF
