#!/usr/bin/env python3
"""
rt_to_session —— 用 GPT 的 RT 批量刷出 AuthSession（单文件，右键即可运行）

流程:
    1. 用 RT 调 https://auth.openai.com/oauth/token 刷新 -> 拿到 新AT / id_token / 新RT
    2. 解码 AT + id_token，拼出 auth session（压缩成一行 JSON）
       token 里解不出 chatgpt_account_id 时，再用新 AT 调 accounts/check 兜底补齐 account.id / planType
    3. 输出一行:  邮箱----新RT----压缩session

输入文件 input.txt，每行:   账号----GPT密码----GPT的RT----邮箱密码   （四段用 ---- 分隔）
    只用到 账号(第1段) 和 RT(第3段)，另外两段仅携带、本流程不使用。

输出:
    output.txt     成功的账号，每行:  邮箱----新RT----压缩session
    processed.json 每个账号的完整处理记录（含原始接口 response），实时落盘，支持断点重跑
    failed.txt     失败的账号，每行:  账号----失败原因

所有可调参数都在 main() 里用 a = ... 的方式定义，无命令行解析、无全局参数。
"""

import base64
import json
import os
import threading
from datetime import datetime, timezone

from curl_cffi.requests import Session

# ──────────────────────────── 纯工具函数（无配置、无全局状态） ────────────────────────────


def decode_jwt_payload(token: str) -> dict:
    """解码 JWT 的 payload（不验签，仅取声明）。"""
    payload_b64 = token.split(".")[1]
    payload_b64 += "=" * (-len(payload_b64) % 4)
    return json.loads(base64.urlsafe_b64decode(payload_b64).decode("utf-8"))


def normalize_proxy(raw):
    """
    归一化代理字符串，返回 curl_cffi 可用的形式；空 -> None。
    支持缺省协议 / 缺省 user:pass 的多种写法：
        ip:port
        user:pass@ip:port
        http://ip:port
        http://user:pass@ip:port
    无协议时默认补 http://。
    """
    if not raw:
        return None
    raw = raw.strip()
    if not raw:
        return None
    if "://" not in raw:
        raw = "http://" + raw
    return raw


def find_rt(fields):
    """
    从一行拆出的字段里找 RT：RT 一定以小写 "rt" 两个字母开头（如 rt.1.AAD...）。
    支持 RT 在任意位置（第1/2/3/4 段轮询），也支持整行只有一个 RT 的情况。
    """
    for f in fields:
        f = (f or "").strip()
        if f.startswith("rt"):
            return f
    return ""


def find_email(fields):
    """从字段里找邮箱（含 @ 的那一段）；找不到返回空串。"""
    for f in fields:
        f = (f or "").strip()
        if "@" in f:
            return f
    return ""


def build_session(access_token: str, id_token: str, old_rt: str = "", new_rt: str = "") -> dict:
    """
    用 新AT + id_token 解码后拼 auth session。
    token 里没有的字段（sessionToken / structure / 各 is* / mfa 等）按约定不拼装。
    额外回写 oldRt / newRt 两个 key。
    """
    at = decode_jwt_payload(access_token)
    idt = decode_jwt_payload(id_token)

    at_auth = at.get("https://api.openai.com/auth", {})
    idt_auth = idt.get("https://api.openai.com/auth", {})

    # user.id 优先取 id_token 里的 user_id，兜底 AT
    user_id = idt_auth.get("user_id") or at_auth.get("user_id") or ""
    # idp 从 sub 前缀取（"auth0|xxx" -> "auth0"）
    sub = idt.get("sub") or at.get("sub") or ""
    idp = sub.split("|")[0] if "|" in sub else sub

    # expires 用 AT 的过期时间点
    exp = at.get("exp")
    if exp:
        expires = datetime.fromtimestamp(exp, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
    else:
        expires = ""

    session = {
        "user": {
            "id": user_id,
            "name": idt.get("name"),
            "email": idt.get("email") or at.get("https://api.openai.com/profile", {}).get("email"),
            "idp": idp,
            "iat": idt.get("iat") or at.get("iat"),
            "amr": idt.get("amr") or at_auth.get("amr"),
        },
        "expires": expires,
        "account": {
            "id": at_auth.get("chatgpt_account_id") or idt_auth.get("chatgpt_account_id"),
            "planType": at_auth.get("chatgpt_plan_type"),
            "computeResidency": at_auth.get("chatgpt_compute_residency"),
        },
        "accessToken": access_token,
        "authProvider": "openai",
        "oldRt": old_rt,
        "newRt": new_rt,
    }
    return session


# ──────────────────────────── 单账号处理器（每个 task 走自己固定的 proxy） ────────────────────────────

class RtToSession:
    def __init__(self, client_id, oauth_token_url, oauth_redirect_uri, accounts_check_url, impersonate, sep):
        self.client_id = client_id
        self.oauth_token_url = oauth_token_url
        self.oauth_redirect_uri = oauth_redirect_uri
        self.accounts_check_url = accounts_check_url
        self.impersonate = impersonate
        self.sep = sep

    def refresh(self, refresh_token: str, proxy):
        """调刷新接口。返回 (ok, data_or_none, raw_response)。raw_response 一定回传用于落盘。"""
        payload = {
            "client_id": self.client_id,
            "grant_type": "refresh_token",
            "redirect_uri": self.oauth_redirect_uri,
            "refresh_token": refresh_token,
        }
        with Session(impersonate=self.impersonate, proxy=proxy, timeout=60) as s:
            resp = s.post(self.oauth_token_url, json=payload, headers={"Content-Type": "application/json"})
        try:
            raw = resp.json()
        except Exception:
            raw = {"_non_json_body": resp.text}
        if resp.status_code == 200 and isinstance(raw, dict) and raw.get("access_token"):
            return True, raw, raw
        return False, None, {"_status_code": resp.status_code, "_body": raw}

    def account_check(self, access_token, proxy):
        """
        token 里解不出 chatgpt_account_id 时兜底：调 accounts/check 取 account_id + plan_type
        （team > plus > free 选最优）。返回 (info_or_none, raw_response)。
        """
        headers = {
            "Authorization": f"Bearer {access_token}",
            "Content-Type": "application/json",
            "accept": "*/*",
            "referer": "https://chatgpt.com/",
        }
        try:
            with Session(impersonate=self.impersonate, proxy=proxy, timeout=55) as s:
                resp = s.get(self.accounts_check_url, headers=headers)
            raw = resp.json() if resp.status_code == 200 else {"_status_code": resp.status_code, "_body": resp.text[:500]}
            if resp.status_code != 200:
                return None, raw
            accounts = raw.get("accounts", {})
            ordering = raw.get("account_ordering", [])
            priority = {"team": 0, "plus": 1, "free": 2}
            best_id, best_plan, best_p = None, None, 999
            for acc_id in ordering:
                acc = accounts.get(acc_id, {}).get("account", {})
                plan = acc.get("plan_type", "free")
                p = priority.get(plan, 999)
                if p < best_p:
                    best_p, best_id, best_plan = p, acc.get("account_id", acc_id), plan
            if not best_id:
                for k, v in accounts.items():
                    if k != "default":
                        acc = v.get("account", {})
                        best_id, best_plan = acc.get("account_id", k), acc.get("plan_type")
                        break
            if best_id:
                return {"account_id": best_id, "plan_type": best_plan}, raw
            return None, raw
        except Exception as e:
            return None, {"_exception": f"{type(e).__name__}: {e}"}

    def process(self, account: str, email_hint: str, refresh_token: str, proxy):
        """
        处理单个账号。
        返回 dict: {success, output, error, refresh_response}
        输出的邮箱段优先用输入里的邮箱，输入没有则用 token 里解出来的邮箱兜底。
        """
        try:
            ok, data, raw = self.refresh(refresh_token, proxy)
        except Exception as e:
            return {"success": False, "output": "", "error": f"刷新请求异常: {type(e).__name__}: {e}",
                    "refresh_response": {"_exception": f"{type(e).__name__}: {e}"}}

        if not ok:
            return {"success": False, "output": "", "error": f"刷新失败: {json.dumps(raw, ensure_ascii=False)[:500]}",
                    "refresh_response": raw}

        new_at = data.get("access_token") or ""
        new_rt = data.get("refresh_token") or refresh_token
        id_token = data.get("id_token") or ""
        if not new_at or not id_token:
            return {"success": False, "output": "", "error": "刷新返回缺少 access_token 或 id_token",
                    "refresh_response": raw}

        accounts_check_response = None
        try:
            session = build_session(new_at, id_token, refresh_token, new_rt)
            # token 里解不出 chatgpt_account_id 时，调 accounts/check 兜底补齐 id / planType
            if not session["account"].get("id"):
                info, accounts_check_response = self.account_check(new_at, proxy)
                if info:
                    session["account"]["id"] = info.get("account_id") or session["account"]["id"]
                    session["account"]["planType"] = info.get("plan_type") or session["account"]["planType"]
            session_compact = json.dumps(session, separators=(",", ":"), ensure_ascii=False)
        except Exception as e:
            return {"success": False, "output": "", "error": f"拼 session 异常: {type(e).__name__}: {e}",
                    "refresh_response": raw, "accounts_check_response": accounts_check_response}

        out_email = email_hint or session.get("user", {}).get("email") or account
        output = self.sep.join([out_email, new_rt, session_compact])
        return {"success": True, "output": output, "error": "", "refresh_response": raw,
                "accounts_check_response": accounts_check_response}


# ──────────────────────────── 结果落盘（线程安全，实时写 processed.json + 重建 output/failed） ────────────────────────────

class ResultStore:
    def __init__(self, processed_file, output_file, failed_file, sep):
        self.processed_file = processed_file
        self.output_file = output_file
        self.failed_file = failed_file
        self.sep = sep
        self.lock = threading.Lock()
        self.processed = {}  # account -> record

    def load(self):
        if os.path.exists(self.processed_file):
            try:
                with open(self.processed_file, "r", encoding="utf-8") as f:
                    for rec in json.load(f):
                        acc = rec.get("account")
                        if acc:
                            self.processed[acc] = rec
            except Exception as e:
                print(f"[WARN] 读取 processed.json 失败，当作空重头跑: {e}")

    def is_done(self, account: str) -> bool:
        """已成功处理过的跳过；失败的允许重跑。"""
        rec = self.processed.get(account)
        return bool(rec and rec.get("success"))

    def record(self, record: dict):
        """写入一条记录并实时重刷三个文件。"""
        with self.lock:
            self.processed[record["account"]] = record
            self._flush_locked()

    def _flush_locked(self):
        records = list(self.processed.values())
        # processed.json（全量记录）
        tmp = self.processed_file + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(records, f, ensure_ascii=False, indent=2)
        os.replace(tmp, self.processed_file)
        # output.txt（仅成功）
        with open(self.output_file, "w", encoding="utf-8") as f:
            for r in records:
                if r.get("success") and r.get("output"):
                    f.write(r["output"] + "\n")
        # failed.txt（仅失败，账号----失败原因）
        with open(self.failed_file, "w", encoding="utf-8") as f:
            for r in records:
                if not r.get("success"):
                    reason = (r.get("error") or "").replace("\n", " ")
                    f.write(f"{r['account']}{self.sep}{reason}\n")


# ──────────────────────────── 初始化 ────────────────────────────

def init_files(base_dir, input_file, output_file, failed_file, processed_file):
    """初始化：目录 + 四个文件都不存在就各建一个默认空文件（缺哪个补哪个，绝不报错）。"""
    os.makedirs(base_dir, exist_ok=True)
    if not os.path.exists(input_file):
        with open(input_file, "w", encoding="utf-8") as f:
            f.write("# 每行一个账号，字段用 ---- 分隔，例如：\n")
            f.write("# 账号----GPT密码----GPT的RT----邮箱密码\n")
            f.write("# RT 以小写 rt 开头，位置不限；整行只有一个 RT 也支持。\n")
    for path, default in ((output_file, ""), (failed_file, "")):
        if not os.path.exists(path):
            with open(path, "w", encoding="utf-8") as f:
                f.write(default)
    if not os.path.exists(processed_file):
        with open(processed_file, "w", encoding="utf-8") as f:
            f.write("[]")


# ──────────────────────────── 主流程 ────────────────────────────

def main():
    # ============================ 参数区（全部在这里改） ============================
    oauth_token_url = "https://auth.openai.com/oauth/token"
    oauth_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 = "chrome120"
    sep = "----"  # 输入 / 输出 / failed 统一分隔符（token 里含 - 和 _，单个 - 会切碎，必须用四横杠）

    client_id = "app_WXrF1LSkiTtfYqiL6XtjygvX"   # 刷新 RT 用的 OAuth client_id

    concurrency = 1                             # 并发线程数（任务预先均分给这么多线程，无抢占）

    # 代理：优先单代理；单代理没有就用代理池提取链接；都没有就走本地不代理（任何情况都不报错）
    single_proxy = ""                            # 单个代理，如 http://user:pass@ip:port（留空=没有）
    proxy_pool_url = ""                          # 代理池提取链接（GET 回来按行解析）；单代理为空时才用
    proxy_pool_list = []                         # 也可直接写死一批代理（非空时优先于提取链接）

    # 文件路径：数据目录固定在“本脚本文件所在目录 / data/rt_to_session/”（相对 __file__，不是
    # 当前工作目录）。所以把这个 .py 拷到任何地方都能单独运行，数据会自动建在它旁边的
    # data/rt_to_session/ 下。（放在本仓库 test/ 下时，test/data 已进 .gitignore，不会入库。）
    #
    # 各文件格式：
    #   input.txt      【输入】每行一个账号，字段用 ---- 分隔，例如：
    #                       账号----GPT密码----GPT的RT----邮箱密码
    #                  实际只用两段：邮箱（含 @ 的段）+ RT（以小写 rt 开头的段）。
    #                  RT 位置不限（1/2/3/4 段轮询识别），整行只有一个 RT 也支持；
    #                  # 开头的行和空行忽略。
    #   output.txt     【成功输出】每行： 邮箱----新RT----压缩session
    #                  session 是单行压缩 JSON；新RT 是刷新接口返回的轮换 refresh_token。
    #   failed.txt     【失败清单】每行： 账号----失败原因
    #   processed.json 【全量记录】数组，每个账号一个对象，字段：
    #                       account        账号标识（邮箱优先，没有则用 RT / 原始行）
    #                       input          原始输入行
    #                       output         该账号的 output 行（失败为空串）
    #                       success        是否成功
    #                       error          失败原因（成功为空串）
    #                       time           处理时间
    #                       proxy          该账号实际使用的代理（None=本地直连）
    #                       refresh_response        刷新接口原始返回（成功失败都存）
    #                       accounts_check_response  仅 token 缺 account_id 时兜底调 accounts/check 的原始返回，否则 null
    #                  实时逐条落盘；重跑时已成功的自动跳过、失败的自动重试。
    base_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "rt_to_session")
    input_file = os.path.join(base_dir, "input.txt")
    output_file = os.path.join(base_dir, "output.txt")
    processed_file = os.path.join(base_dir, "processed.json")
    failed_file = os.path.join(base_dir, "failed.txt")
    # ==============================================================================

    # 初始化：目录 + 四个文件缺哪个补哪个
    init_files(base_dir, input_file, output_file, failed_file, processed_file)

    # 读输入行 -> 解析出 (账号, 邮箱, RT)。RT 按“以 rt 开头”在任意位置识别，支持单 RT。
    tasks = []          # [(account, email, refresh_token, raw_line)]
    with open(input_file, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            parts = [p.strip() for p in line.split(sep)]
            email = find_email(parts)
            refresh_token = find_rt(parts)
            account = email or refresh_token or line   # 记录/去重用的标识
            tasks.append((account, email, refresh_token, line))

    if not tasks:
        print("[INFO] 输入文件里还没有账号，请把数据填进 input.txt 后再运行：")
        print(f"       {input_file}")
        return

    # 代理三级兜底（绝不报错）：单代理 > 代理池 > 本地
    single = normalize_proxy(single_proxy)
    pool = []
    if not single:
        raw_pool = list(proxy_pool_list)
        if not raw_pool and proxy_pool_url:
            print(f"[INFO] 从提取链接拉取代理池: {proxy_pool_url}")
            try:
                with Session(impersonate=impersonate, timeout=30) as s:
                    body = s.get(proxy_pool_url).text
                raw_pool = [ln.strip() for ln in body.splitlines() if ln.strip()]
            except Exception as e:
                print(f"[WARN] 拉取代理池失败，改走本地不代理: {e}")
                raw_pool = []
        pool = [normalize_proxy(p) for p in raw_pool if normalize_proxy(p)]

    if single:
        print(f"[INFO] 使用单代理: {single}")
    elif pool:
        print(f"[INFO] 使用代理池，共 {len(pool)} 个，每个账号全程绑定固定代理")
    else:
        print("[INFO] 未配置代理，走本地直连")

    # 给每个 task 绑定固定代理（单代理全用它；代理池按序取模 -> 该账号全程走这一个；都没有=None）
    bound = []          # [(account, email, refresh_token, raw_line, proxy)]
    for idx, (account, email, refresh_token, raw_line) in enumerate(tasks):
        if single:
            proxy = single
        elif pool:
            proxy = pool[idx % len(pool)]
        else:
            proxy = None
        bound.append((account, email, refresh_token, raw_line, proxy))

    # 载入已处理记录，跳过已成功的
    store = ResultStore(processed_file, output_file, failed_file, sep)
    store.load()
    pending = [t for t in bound if not store.is_done(t[0])]
    skipped = len(bound) - len(pending)
    print(f"[INFO] 共 {len(bound)} 个账号，跳过已成功 {skipped} 个，本次处理 {len(pending)} 个")
    if not pending:
        print("[INFO] 没有需要处理的账号，结束")
        return

    converter = RtToSession(client_id, oauth_token_url, oauth_redirect_uri, accounts_check_url, impersonate, sep)
    counter = {"done": 0, "ok": 0, "fail": 0}
    counter_lock = threading.Lock()
    total = len(pending)

    # 把任务预先均分给 concurrency 个线程，各线程只跑自己那份（无共享队列、无抢占）
    n_threads = max(1, min(concurrency, total))
    shards = [[] for _ in range(n_threads)]
    for i, t in enumerate(pending):
        shards[i % n_threads].append(t)

    def worker(shard):
        for account, email, refresh_token, raw_line, proxy in shard:
            if not refresh_token:
                result = {"success": False, "output": "", "error": "输入行里没找到 RT（以 rt 开头的字段）",
                          "refresh_response": None}
            else:
                result = converter.process(account, email, refresh_token, proxy)

            record = {
                "account": account,
                "input": raw_line,
                "output": result.get("output", ""),
                "success": result.get("success", False),
                "error": result.get("error", ""),
                "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "proxy": proxy,
                "refresh_response": result.get("refresh_response"),
                "accounts_check_response": result.get("accounts_check_response"),  # 仅 token 缺 account_id 时兜底调用
            }
            store.record(record)

            with counter_lock:
                counter["done"] += 1
                if record["success"]:
                    counter["ok"] += 1
                else:
                    counter["fail"] += 1
                tag = "OK " if record["success"] else "FAIL"
                print(f"[{counter['done']}/{total}] {tag} {account}"
                      + ("" if record["success"] else f"  -> {record['error'][:120]}"))

    threads = [threading.Thread(target=worker, args=(shard,)) for shard in shards if shard]
    for th in threads:
        th.start()
    for th in threads:
        th.join()

    print(f"\n===== 完成 =====  成功 {counter['ok']}，失败 {counter['fail']}")
    print(f"output   : {output_file}")
    print(f"processed: {processed_file}")
    print(f"failed   : {failed_file}")


if __name__ == "__main__":
    main()
