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

判活接口：GET https://chatgpt.com/backend-api/accounts/check/v4-2023-04-27
  - 200                        → 存活，解析套餐(Plus/Pro/Team/Free)、accountId
  - 401                        → 死号（token 失效）
  - 403 / 429 / 5xx / 网络异常  → 未知（不下死结论，避免误杀）

凭据二选一（优先级 at > rt）：
  at  = access_token，直接用
  rt  = refresh_token，先换 at 再验活（OpenAI 的 rt 可能滚动，换出的新 rt 会写进 processed.json）

每次执行都会把本次结果写进同目录 processed.json（相当于日志，含换出的新 rt / at，防止丢失）。

依赖：curl_cffi（pip install curl_cffi）
运行：右键直接运行，或 python3 1_GPT验活.py
"""
import base64
import json
import os
import uuid
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_email(token: str) -> str:
    """从 JWT 里解出邮箱（不验签），顶层 email 优先，其次 OpenAI profile 命名空间"""
    try:
        payload_b64 = token.split(".")[1]
        payload_b64 += "=" * (4 - len(payload_b64) % 4)
        payload = json.loads(base64.b64decode(payload_b64).decode("utf-8"))
        if payload.get("email"):
            return payload["email"]
        profile = payload.get("https://api.openai.com/profile") or {}
        return profile.get("email") or ""
    except Exception:
        return ""


def refresh_access_token(refresh_token: str, proxy: Optional[str], cfg: dict) -> dict:
    """refresh_token → {access_token, refresh_token}（新 rt 可能滚动，一并带回来留证）"""
    payload = {
        "client_id": cfg["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,
        )
        if resp.status_code == 200:
            d = resp.json()
            return {"access_token": d.get("access_token") or "",
                    "refresh_token": d.get("refresh_token") or ""}
        log(f"[refresh] rt 换 at 失败 HTTP {resp.status_code}: {(resp.text or '')[:120]}")
    except Exception as e:
        log(f"[refresh] rt 换 at 异常: {e}")
    return {"access_token": "", "refresh_token": ""}


def plan_of(data: dict) -> str:
    """从 accounts/check 响应里推断套餐等级"""
    accounts = data.get("accounts") or {}
    for key in ("default", *accounts.keys()):
        acc = accounts.get(key) or {}
        entitlement = (acc.get("entitlement") or {})
        plan = entitlement.get("subscription_plan") or ""
        if plan:
            low = plan.lower()
            if "team" in low or "business" in low:
                return "Team"
            if "pro" in low:
                return "Pro"
            if "plus" in low or "chatgptplusplan" in low:
                return "Plus"
            return plan
    return "Free"


def account_id_of(data: dict) -> str:
    accounts = data.get("accounts") or {}
    acc = accounts.get("default") or (list(accounts.values())[0] if accounts else {})
    return str((acc.get("account") or {}).get("account_id") or "")


def check_alive(access_token: str, proxy: Optional[str], cfg: dict) -> dict:
    """单账号验活：返回 {alive(True/False/None), status, reason, plan, account_id}"""
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json",
        "accept": "*/*",
        "referer": "https://chatgpt.com/",
        "oai-device-id": str(uuid.uuid4()),   # 每次请求随机一个 device id
        "user-agent": cfg["ua"],
    }
    try:
        with cffi_requests.Session(impersonate=cfg["impersonate"], proxy=proxy, timeout=TIMEOUT) as s:
            resp = s.get(cfg["accounts_check_url"], headers=headers, timeout=TIMEOUT)
        code = resp.status_code
        if code == 200:
            try:
                data = resp.json()
            except Exception:
                return {"alive": None, "status": 200, "reason": "200 但非 JSON（未知）",
                        "plan": "", "account_id": ""}
            return {"alive": True, "status": 200, "reason": "200 正常",
                    "plan": plan_of(data), "account_id": account_id_of(data)}
        if code == 401:
            return {"alive": False, "status": 401, "reason": "401 token 失效",
                    "plan": "", "account_id": ""}
        # 403/429/5xx 都可能是代理或风控，不判死
        return {"alive": None, "status": code, "reason": f"HTTP {code}（未知）",
                "plan": "", "account_id": ""}
    except Exception as e:
        return {"alive": None, "status": 0, "reason": f"网络异常（未知）: {type(e).__name__}",
                "plan": "", "account_id": ""}


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:
    # ==================== 参数区（改这里，不用命令行传参）====================
    account = "xxx@example.com"     # 可选，仅用于日志显示，不影响验活
    at = ""                         # access_token，有就直接用
    rt = ""                         # refresh_token，没 at 时用它换
    proxy = ""                      # 固定代理 "ip:port" 或 "user:pass@ip:port"，留空 = 直连

    default_client_id = "app_WXrF1LSkiTtfYqiL6XtjygvX"   # ChatGPT iOS，rt 换 at 用
    # codex 默认 client_id 是 app_EMoamEEZ73f0CkXaXp7hrann（Codex 独立于 ChatGPT，需要时换成它）

    output_dir = os.path.dirname(os.path.abspath(__file__))
    processed = "processed.json"    # 执行日志：每次跑都写，记录结果 + 换出的新 rt/at

    cfg = {
        "client_id": default_client_id,
        "oauth_token_url": "https://auth.openai.com/oauth/token",
        "redirect_uri": "com.openai.chat://auth0.openai.com/ios/com.openai.chat/callback",
        "accounts_check_url": "https://chatgpt.com/backend-api/accounts/check/v4-2023-04-27",
        "impersonate": "chrome",
        "ua": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
               "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"),
    }

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

    label = account.strip() or "(未标注账号)"

    # 按优先级取 access_token：at > rt
    source, token, new_rt = "", at.strip(), ""
    if token:
        source = "at"
    elif rt.strip():
        source = "rt"
        log(f"{label} 用 refresh_token 换 access_token")
        got = refresh_access_token(rt.strip(), proxy, cfg)
        token, new_rt = got["access_token"], got["refresh_token"]
        if new_rt and new_rt != rt.strip():
            log("⚠️ 发生了 RT 刷新！旧 RT 已作废，新的 rt 是：")
            log(f"    {new_rt}")
            log("    请立即保存！全部信息见 processed.json")

    processed_path = os.path.join(output_dir, processed)
    email = jwt_email(token) if token else ""
    who = email or account.strip() or "(无邮箱)"
    key = (email or account.strip() or at.strip() or rt.strip() or "unknown").lower()

    if not token:
        log(f"❓ {label} 未知：没有可用的 access_token（at / rt 都换不出）")
        write_processed(processed_path, key, {
            "account": account, "email": email, "source": source or "(无)",
            "alive": None, "plan": "", "account_id": "",
            "access_token": "", "new_rt": new_rt, "status": 0,
            "reason": "没有可用的 access_token", "ts": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        })
        log(f"已记录 → {processed_path}")
        return

    r = check_alive(token, proxy, cfg)
    if r["alive"] is True:
        extra = f" | accountId={r['account_id']}" if r.get("account_id") else ""
        log(f"✅ 存活 [{r.get('plan') or '?'}] {who} | {r['reason']}{extra}")
    elif r["alive"] is False:
        log(f"❌ 死号 {who} | {r['reason']}")
    else:
        log(f"❓ 未知 {who} | {r['reason']}")

    write_processed(processed_path, key, {
        "account": account, "email": email, "source": source,
        "alive": r["alive"], "plan": r.get("plan") or "", "account_id": r.get("account_id") or "",
        "access_token": token, "new_rt": new_rt, "status": r.get("status"),
        "reason": r.get("reason"), "ts": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    })
    log(f"已记录 → {processed_path}")


if __name__ == "__main__":
    main()
