#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GPT-image2 额度查询（单账号，固定代理）

接口：POST https://chatgpt.com/backend-api/conversation/init（只需 access_token，无需 rt）
  - 200 → 从 limits_progress 里取 feature_name=="image_gen" 的 remaining(剩余额度) 和 reset_after(下次刷新时间)
  - 401 → token 失效（死号）
  - 403 / 429 / 5xx / 网络异常 → 未知（多半是代理/风控，不下死结论）

只用 access_token（Bearer）；curl_cffi impersonate 模拟浏览器指纹过 Cloudflare。

每次执行都会把本次结果写进同目录 processed.json（相当于日志）。

依赖：curl_cffi（pip install curl_cffi）
运行：右键直接运行，或 python3 GPT-image2额度查询.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 _fmt_reset(iso_str: str) -> str:
    """把 reset_after 的 ISO8601(UTC) 转成本地时间字符串；解析失败原样返回"""
    if not iso_str:
        return ""
    try:
        dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))
        return dt.astimezone().strftime("%Y-%m-%d %H:%M:%S")
    except Exception:
        return iso_str


def query_image_quota(access_token: str, proxy: Optional[str], cfg: dict) -> dict:
    """查 image_gen 额度：返回 {ok, status, reason, remaining, reset_after, reset_local}"""
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json",
        "accept": "*/*",
        "origin": "https://chatgpt.com",
        "referer": "https://chatgpt.com/",
        "oai-device-id": str(uuid.uuid4()),   # 每次请求随机一个 device id
        "user-agent": cfg["ua"],
    }
    body = {
        "conversation_mode_kind": "primary_assistant",
        "requested_default_model": None,
        "conversation_id": None,
        "conversation_origin": None,
    }
    try:
        with cffi_requests.Session(impersonate=cfg["impersonate"], proxy=proxy, timeout=TIMEOUT) as s:
            resp = s.post(cfg["init_url"], headers=headers, json=body, timeout=TIMEOUT)
        code = resp.status_code
        if code == 200:
            try:
                data = resp.json()
            except Exception:
                return {"ok": None, "status": 200, "reason": "200 但非 JSON（未知）",
                        "remaining": None, "reset_after": "", "reset_local": ""}
            item = None
            for lp in (data.get("limits_progress") or []):
                if lp.get("feature_name") == "image_gen":
                    item = lp
                    break
            if item is None:
                return {"ok": True, "status": 200, "reason": "无 image_gen 额度项（可能无限制或不适用）",
                        "remaining": None, "reset_after": "", "reset_local": ""}
            reset = item.get("reset_after") or ""
            return {"ok": True, "status": 200, "reason": "ok",
                    "remaining": item.get("remaining"), "reset_after": reset,
                    "reset_local": _fmt_reset(reset)}
        if code == 401:
            return {"ok": False, "status": 401, "reason": "401 token 失效",
                    "remaining": None, "reset_after": "", "reset_local": ""}
        # 403/429/5xx 都可能是代理或风控，不判死
        return {"ok": None, "status": code, "reason": f"HTTP {code}（未知）",
                "remaining": None, "reset_after": "", "reset_local": ""}
    except Exception as e:
        return {"ok": None, "status": 0, "reason": f"网络异常（未知）: {type(e).__name__}",
                "remaining": None, "reset_after": "", "reset_local": ""}


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（Bearer），必填
    proxy = ""                      # 固定代理 "ip:port" 或 "user:pass@ip:port"，留空 = 直连

    # —— 以下配置 ——
    output_dir = os.path.dirname(os.path.abspath(__file__))
    processed = "processed.json"    # 执行日志：每次跑都写
    # ========================================================================

    cfg = {
        "init_url": "https://chatgpt.com/backend-api/conversation/init",
        "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

    if not at.strip():
        log("❌ 没有 at，请在参数区填入 access_token（Bearer）")
        return

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

    r = query_image_quota(at, proxy, cfg)
    if r["ok"] is True:
        if r["remaining"] is not None:
            tail = f"，下次刷新 {r['reset_local'] or r['reset_after']}" if (r["reset_local"] or r["reset_after"]) else ""
            log(f"✅ {who} 图片(image_gen)剩余额度：{r['remaining']}{tail}")
        else:
            log(f"✅ {who} {r['reason']}")
    elif r["ok"] is False:
        log(f"❌ 死号 {who} | {r['reason']}")
    else:
        log(f"❓ 未知 {who} | {r['reason']}")

    write_processed(processed_path, key, {
        "account": account,
        "email": email,
        "ok": r["ok"],
        "remaining": r["remaining"],
        "reset_after": r["reset_after"],
        "reset_local": r["reset_local"],
        "status": r["status"],
        "reason": r["reason"],
        "ts": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    })
    log(f"已记录 → {processed_path}")


if __name__ == "__main__":
    main()
