#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GPT 刷 RT（单账号，固定代理）

刷新接口：POST https://auth.openai.com/oauth/token
  body: {client_id, grant_type=refresh_token, redirect_uri, refresh_token}
  200               → 新的 access_token / refresh_token（OpenAI 的 rt 滚动，旧 rt 作废）
  400 invalid_grant → RT 已失效
  其他 / 网络异常    → 失败

每次执行都会把本次结果写进同目录 processed.json（相当于日志，含新 rt / at，防止丢失）。
换出新 rt 时会醒目提示并立即落盘 —— 旧 rt 一旦刷过就作废，新 rt 千万别丢。

依赖：curl_cffi（pip install curl_cffi）
运行：右键直接运行，或 python3 2_GPT刷RT.py
"""
import base64
import json
import os
from datetime import datetime
from typing import Optional

from curl_cffi import requests as cffi_requests

TIMEOUT = 30   # 请求超时（秒）


def log(msg: str) -> None:
    print(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}", flush=True)


def _proxies(proxy: Optional[str]):
    if not proxy:
        return None
    return {"http": proxy, "https": proxy}


def jwt_field(token: str, namespace: Optional[str], field: str) -> str:
    """从 JWT payload 取字段（不验签）。namespace 为空则取顶层"""
    try:
        payload_b64 = token.split(".")[1]
        payload_b64 += "=" * (4 - len(payload_b64) % 4)
        payload = json.loads(base64.b64decode(payload_b64).decode("utf-8"))
        target = payload.get(namespace) if namespace else payload
        return str((target or {}).get(field) or "")
    except Exception:
        return ""


def refresh_rt(refresh_token: str, client_id: str, proxy: Optional[str], cfg: dict) -> dict:
    """rt → {ok, access_token, refresh_token, email, expires_in, status, note}"""
    payload = {
        "client_id": client_id,
        "grant_type": "refresh_token",
        "redirect_uri": cfg["redirect_uri"],
        "refresh_token": refresh_token,
    }
    try:
        resp = cffi_requests.post(
            cfg["oauth_token_url"], json=payload, impersonate=cfg["impersonate"],
            proxies=_proxies(proxy), headers={"Content-Type": "application/json"},
            timeout=TIMEOUT,
        )
        code = resp.status_code
        if code == 200:
            d = resp.json()
            new_at = d.get("access_token") or ""
            new_rt = d.get("refresh_token") or ""
            email = (jwt_field(d.get("id_token") or "", None, "email")
                     or jwt_field(new_at, "https://api.openai.com/profile", "email"))
            return {"ok": True, "access_token": new_at, "refresh_token": new_rt,
                    "email": email, "expires_in": d.get("expires_in", 0), "status": 200, "note": ""}
        text = resp.text or ""
        if code == 400 and "invalid_grant" in text:
            return {"ok": False, "access_token": "", "refresh_token": "", "email": "",
                    "expires_in": 0, "status": 400, "note": "invalid_grant（RT 已失效）"}
        return {"ok": False, "access_token": "", "refresh_token": "", "email": "",
                "expires_in": 0, "status": code, "note": f"HTTP {code}: {text[:120]}"}
    except Exception as e:
        return {"ok": False, "access_token": "", "refresh_token": "", "email": "",
                "expires_in": 0, "status": 0, "note": f"网络异常: {type(e).__name__}: {str(e)[:60]}"}


def write_processed(processed_path: str, key: str, record: dict) -> None:
    """把本次结果写进 processed.json（原子写，多次执行累积成日志）"""
    done = {}
    if os.path.exists(processed_path):
        try:
            with open(processed_path, "r", encoding="utf-8") as f:
                done = json.load(f)
        except Exception:
            done = {}
        if not isinstance(done, dict):
            done = {}
    done[key] = record
    tmp = processed_path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(done, f, ensure_ascii=False, indent=2)
    os.replace(tmp, processed_path)


def main() -> None:
    # ==================== 参数区（改这里，不用命令行传参）====================
    # —— 核心参数（两个）——
    email = ""                      # 账号邮箱（标识用，写进日志 / processed.json）
    rt = ""                         # 要刷新的 refresh_token
    # —— 以下都是 output / 配置 ——
    proxy = "http://xxx:xxx"                      # 固定代理 "ip:port" 或 "user:pass@ip:port"，留空 = 直连
    client_id = "app_WXrF1LSkiTtfYqiL6XtjygvX"   # codex 默认；ChatGPT iOS 用 app_EMoamEEZ73f0CkXaXp7hrann
    output_dir = os.path.dirname(os.path.abspath(__file__))
    processed = "processed.json"    # 执行日志：每次跑都写，记录结果 + 换出的新 rt/at
    # ========================================================================

    cfg = {
        "oauth_token_url": "https://auth.openai.com/oauth/token",
        "redirect_uri": "com.openai.chat://auth0.openai.com/ios/com.openai.chat/callback",
        "impersonate": "chrome",
    }

    # 归一化固定代理
    proxy = (proxy or "").strip()
    if proxy and "://" not in proxy:
        proxy = "http://" + proxy
    proxy = proxy or None

    label = email.strip() or "(未标注账号)"
    processed_path = os.path.join(output_dir, processed)

    if not rt.strip():
        log("❌ 没有 rt，请在参数区填入要刷新的 refresh_token")
        return

    log(f"{label} 用 refresh_token 刷新")
    r = refresh_rt(rt.strip(), client_id, proxy, cfg)
    acct_email = email.strip() or r["email"]
    who = acct_email or "(无邮箱)"
    key = (acct_email or rt.strip() or "unknown").lower()

    if r["ok"]:
        log(f"✅ {who} 刷新成功")
        if r["refresh_token"] and r["refresh_token"] != rt.strip():
            log("⚠️ 发生了 RT 刷新！旧 RT 已作废，新的 rt 是：")
            log(f"    {r['refresh_token']}")
            log("    请立即保存！全部信息见 processed.json")
    else:
        log(f"❌ {who} 刷新失败：{r['note']}")

    write_processed(processed_path, key, {
        "ok": r["ok"],
        "email": acct_email,
        "client_id": client_id,
        "old_rt": rt.strip(),
        "new_rt": r["refresh_token"] if r["ok"] else "",
        "access_token": r["access_token"] if r["ok"] else "",
        "expires_in": r["expires_in"] if r["ok"] else 0,
        "status": r["status"],
        "note": r["note"],
        "ts": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    })
    log(f"已记录 → {processed_path}")


if __name__ == "__main__":
    main()
