#!/usr/bin/env python3
"""
gen_sources.py — 把原版 BTSOU_Plus 的源清单（ResPool.txt / ApiMapping.txt）
转成本网页版可审计的 sources.json。

原版的做法：源清单由作者服务器下发（ResPool.txt 定『资源名/启用/代理/搜索页模板/
分割符/下一页/编码方式/是否 API/导航页』，ApiMapping.txt 定 API 型源的 JSON 字段映射）。
本脚本把它**原样**搬进本机文件，字段名一一对应，不增不减：

  ResPool 列        sources.json 字段        说明
  ────────────────  ───────────────────────  ────────────────────────────────
  Name              id / name                资源名（id 规范化）
  REnable           enabled                  是否启用
  Acting            proxy                    TRUE→auto-vpn（先走 VPN）·FALSE→auto（先直连）
  Page              list_url                 搜索页模板（{keyword}/{page} → {kw}/{page}）
  Division          split                    列表页分割符（literal split，与原版一致）
  NextPage          next_page                下一页关键词（仅记录，本版按页号请求）
  Web2              web2                     原版会拉起 WebView2 导航（本版无法用 JS 渲染，仅记录）
  EncodeType        encoding                 关键词编码：UrlEncode/Base64UrlSafe/Hex
  IsApi             type                     TRUE→json，FALSE→html
  NavigationPage    navigation_page          导航页（域名轮换时的入口）
  ApiMapping.txt    json_fields 等           API 型源的字段映射

用法：
  python3 tools/gen_sources.py                 # 用本目录 tools/ResPool.txt + ApiMapping.txt
  python3 tools/gen_sources.py --fetch         # 先从作者服务器拉最新清单（自动 直连/VPN 回退）
  python3 tools/gen_sources.py --respool /tmp/ResPool.txt --out ../sources.json
"""
from __future__ import annotations

import argparse
import json
import os
import re
import shutil
import sys
import time
import urllib.error
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
APP_DIR = os.path.dirname(HERE)
DEFAULT_OUT = os.path.join(APP_DIR, "sources.json")

BASE = "https://www.pc936.com/u/UpData/BTSOU_Plus"
RESPOOL_URL = f"{BASE}/ResPool.txt"
APIMAPPING_URL = f"{BASE}/ApiMapping.txt"

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
VPN_PROXY = os.environ.get("BTSOU_WEB_PROXY", "http://127.0.0.1:10809").strip()

# 本机实测后的逐源覆盖（原版 ResPool 之外的必要修正；重跑生成仍会保留）
#   btss : Cloudflare 按 TLS 指纹放行 —— 只有 curl 能过，urllib 固定 403 → 换 curl 通道
#   u9a9 : 域名解析正常但直连/VPN 均连接失败（站点已下线）→ 本机默认关掉
LOCAL_OVERRIDES: dict[str, dict] = {
    "btss": {"transport": "curl",
             "note_extra": "本机实测：Cloudflare 认 TLS 指纹，Python 直取 403，改走系统 curl 通道"},
    "u9a9": {"enabled": False,
             "note_extra": "本机实测：站点已下线（直连与 VPN 均连接失败），保留定义但默认关闭"},
}


def _open(url: str, proxy_url: str | None):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    handlers = [urllib.request.ProxyHandler(
        {"http": proxy_url, "https": proxy_url} if proxy_url else {})]
    return urllib.request.build_opener(*handlers).open(req, timeout=20)


def fetch(url: str) -> bytes:
    """先直连，失败再走本机代理（与网页版 `auto` 策略一致）。"""
    last: Exception | None = None
    for proxy in (None, VPN_PROXY):
        try:
            with _open(url, proxy) as r:
                return r.read()
        except Exception as e:  # noqa: PERF203
            last = e
    raise RuntimeError(f"下载失败 {url}: {last}")


# ──────────────────────────────────────────────────────────── 解析

def parse_respool(text: str) -> tuple[dict, list[dict]]:
    """返回 (全局段, 源列表)。全局段=二维码/种子/订阅/热搜 等。"""
    lines = [l.rstrip("\r\n") for l in text.splitlines()]
    glob: dict[str, str] = {}
    sources: list[dict] = []
    in_lib = False
    for ln in lines:
        if not ln.strip():
            continue
        if ln.startswith("库=") or ln.replace("\t", "").strip() == "库=":
            in_lib = True
            continue
        if not in_lib:
            if "=" in ln and "\t" in ln:
                k, _, v = ln.partition("=")
                glob[k.strip()] = v.strip("\t ")
            continue
        cells = [c.strip() for c in ln.split("\t")]
        if len(cells) < 3 or not cells[0]:
            continue
        cells += [""] * (11 - len(cells))
        (name, renable, acting, page, division, nextpage,
         web2, enc, isapi, navpage, fixed) = cells[:11]
        if not page and isapi.upper() != "TRUE":
            continue
        sources.append({
            "name": name, "renable": renable, "acting": acting, "page": page,
            "division": division, "nextpage": nextpage, "web2": web2,
            "encoding": enc, "isapi": isapi, "navpage": navpage, "fixed": fixed,
        })
    return glob, sources


def parse_apimapping(text: str) -> dict[str, dict]:
    """ApiMapping.txt → {资源名: 字段映射}"""
    out: dict[str, dict] = {}
    rows = [[c.strip() for c in l.split("\t")]
            for l in text.splitlines() if l.strip()]
    if len(rows) < 3:
        return out
    head = rows[0]
    for r in rows[2:]:
        if len(r) < 2 or not r[0]:
            continue
        rec = dict(zip(head, r + [""] * (len(head) - len(r))))
        out[r[0]] = rec
    return out


def _truthy(v: str) -> bool:
    return (v or "").strip().upper() in ("TRUE", "1", "YES", "T")


def slug(name: str) -> str:
    s = re.sub(r"[^0-9a-zA-Z]+", "-", name).strip("-").lower()
    return s or "src"


def build(glob: dict, raw_sources: list[dict], apimap: dict[str, dict]) -> dict:
    sources: list[dict] = []
    used_ids: dict[str, int] = {}

    # 保留离线演示源（默认关闭；用于验证整条链路而不联网）
    sources.append({
        "id": "demo", "name": "演示源（离线合成，不联网）", "type": "demo",
        "origin": "builtin",
        "enabled": False, "demo_rows": 24, "group": "内置",
        "note": "不联网的合成数据源；勾选它可验证 抓取→归一化→去重→筛选→排序→导出 整条链路。",
    })

    for s in raw_sources:
        sid = slug(s["name"])
        if sid in used_ids:
            used_ids[sid] += 1
            sid = f"{sid}-{used_ids[sid]}"
        else:
            used_ids[sid] = 1

        is_api = _truthy(s["isapi"])
        note_bits = [f"原版 ResPool 条目：{s['name']}"]
        if s["division"]:
            note_bits.append(f"分割符 {s['division']}")
        if s["nextpage"]:
            note_bits.append(f"下一页标记 {s['nextpage']}")
        if s["navpage"]:
            note_bits.append(f"导航页 {s['navpage']}")
        if _truthy(s["web2"]):
            note_bits.append("原版需 WebView2 渲染（本版可能抓不到）")
        if not _truthy(s["renable"]):
            note_bits.append("原版该条为停用")

        item: dict = {
            "id": sid,
            "name": s["name"],
            "origin": "respool",
            "type": "json" if is_api else "html",
            "enabled": _truthy(s["renable"]),
            "encoding": s["encoding"] or "UrlEncode",
            # 出站策略对齐原版『代理』列：TRUE 先走 VPN，FALSE 先直连（失败自动换另一条）
            "proxy": "auto-vpn" if _truthy(s["acting"]) else "auto",
            "list_url": (s["page"] or "").replace("{keyword}", "{kw}"),
            "group": "原版源池（ResPool）",
            "detail_fetch": not is_api,
            "note": " · ".join(note_bits),
            "respool": {
                "enable": s["renable"], "acting": s["acting"], "division": s["division"],
                "next_page": s["nextpage"], "web2": s["web2"], "encode": s["encoding"],
                "is_api": s["isapi"], "navigation_page": s["navpage"], "fixed_rules": s["fixed"],
            },
        }
        if s["division"]:
            item["split"] = s["division"]
        if is_api:
            am = apimap.get(s["name"]) or {}
            item["json_list_path"] = am.get("ListPath") or "data.list"
            item["json_fields"] = {
                "title": am.get("TitleField") or "title",
                "size": am.get("SizeField") or "size",
                "infohash": am.get("HashField") or "hash",
                "date": am.get("DateField") or "date",
                **({"popularity": am["HotField"]} if am.get("HotField") else {}),
                **({"id": am["IdField"]} if am.get("IdField") else {}),
            }
            if am.get("DetailUrlTemplate"):
                item["detail_url_template"] = am["DetailUrlTemplate"]
            item["api_status_field"] = am.get("CodeField") or "code"
            item["api_status_ok"] = am.get("SuccessValue") or "200"

        ov = LOCAL_OVERRIDES.get(sid) or LOCAL_OVERRIDES.get(s["name"]) or {}
        for k, v in ov.items():
            if k == "note_extra":
                item["note"] = f"{item['note']} · {v}"
            else:
                item[k] = v
        sources.append(item)

    return {
        "_README": [
            "磁链聚合搜索 · 数据源配置（原版 BTSOU_Plus 源池全量）",
            "==================================================",
            "本文件由 tools/gen_sources.py 从原版作者下发的 ResPool.txt / ApiMapping.txt 生成；",
            "字段与原版一一对应（源名/启用/代理/搜索页模板/分割符/编码方式/是否 API）。",
            "重跑：python3 tools/gen_sources.py --fetch   （源域名轮换时用）",
            "",
            "settings 字段：",
            "  vpn_proxy     本机代理出口（v2ray HTTP 10809 / SOCKS5 10808 均可）",
            "  default_proxy 默认出站策略：auto=先直连失败走 VPN · direct=只直连 · vpn=只走 VPN",
            "  detail_fetch_limit  列表页无磁链时，最多抓多少条详情页补磁链（0=关闭）",
            "",
            "每个源的字段：",
            "  id/name/type(html|json|demo)/enabled/group/note",
            "  list_url  搜索页模板：{kw}=编码后的关键词，{page}=页码",
            "  encoding  关键词编码：UrlEncode | Base64UrlSafe | Hex（对齐原版『编码方式』）",
            "  proxy     出站：auto=直连优先·auto-vpn=VPN 优先·direct·vpn（对齐原版『代理』）",
            "  split     列表页分割符（对齐原版『分割符』，literal 切块）",
            "  detail_fetch  是否允许抓详情页补磁链",
            "  mirrors   可选。上一次的域名（回退链）：主域名被墙/失效时自动改用它们",
            "  可选覆盖：row/title/size/magnet/date/popularity/detail/referer（正则）",
            "  不写这些字段时，使用 server.py 里与原版一致的『通用正则组』。",
        ],
        "settings": {
            "vpn_proxy": VPN_PROXY,
            "default_proxy": "auto",
            # 与 server.py DEFAULT_SETTINGS 对齐；同步时会保留本机已有的 settings 值
            "timeout": 20,
            "workers": 10,
            "detail_fetch_limit": 24,
            "detail_workers": 6,
            "detail_cache_ttl": 21600,
        },
        "globals_from_respool": glob,
        "sources": sources,
    }


# ──────────────────────────────────────────────────────────── 与作者同步（供网页版 /api/sync 调用）

# 参与差异比较的字段（源池相关内容；设置项不参与）
DIFF_FIELDS = ["name", "type", "enabled", "encoding", "proxy", "list_url",
               "split", "transport", "referer", "detail_fetch"]


def url_shape(u: str | None) -> str:
    """把 URL 的主机名抹掉，只留路径形状：用来区分『真改版』与『镜像域名轮换』。"""
    return re.sub(r"//[^/]+", "//*", u or "")


def _respool_sources(cfg: dict | None) -> dict[str, dict]:
    out: dict[str, dict] = {}
    for s in (cfg or {}).get("sources", []):
        if s.get("origin") == "respool" or (s.get("origin") is None and s.get("type") != "demo"):
            out[s["id"]] = s
    return out


def diff_configs(old_cfg: dict | None, new_cfg: dict) -> dict:
    """给出『新增 / 移除 / 字段变化』三类差异（只比源池条目）。"""
    old, new = _respool_sources(old_cfg), _respool_sources(new_cfg)
    added = sorted(set(new) - set(old))
    removed = sorted(set(old) - set(new))
    changed = []
    rotations = []
    for sid in sorted(set(old) & set(new)):
        fields, host_only = {}, True
        for f in DIFF_FIELDS:
            a, b = old[sid].get(f), new[sid].get(f)
            if a != b:
                fields[f] = {"old": a, "new": b}
                if f != "list_url" or url_shape(a) != url_shape(b):
                    host_only = False
        if not fields:
            continue
        if host_only:
            rotations.append({"id": sid, "name": new[sid].get("name"),
                              "old": old[sid].get("list_url"),
                              "new": new[sid].get("list_url")})
        else:
            changed.append({"id": sid, "name": new[sid].get("name"), "fields": fields})
    return {
        "added": [{"id": i, "name": new[i].get("name"), "list_url": new[i].get("list_url")}
                  for i in added],
        "removed": [{"id": i, "name": old[i].get("name"), "list_url": old[i].get("list_url")}
                    for i in removed],
        "changed": changed,
        "mirror_rotation": rotations,
        "counts": {
            "old": len(old), "new": len(new),
            "enabled_new": sum(1 for s in new.values() if s.get("enabled")),
            "added": len(added), "removed": len(removed), "changed": len(changed),
            "mirror_rotation": len(rotations),
            "unchanged": len(set(old) & set(new)) - len(changed) - len(rotations),
        },
    }


def _probe_status(url: str, timeout: float = 10.0) -> int:
    """只探 HTTP 状态（直连优先，失败走本机代理）；0 = 连接层失败。"""
    for proxy in (None, VPN_PROXY):
        try:
            with _open(url, proxy) as r:
                return int(getattr(r, "status", 0) or 0)
        except urllib.error.HTTPError as e:
            return int(e.code or 0)
        except Exception:
            continue
    return 0


def _verify_new_domains(cfg: dict, old_cfg: dict, max_workers: int = 6,
                        limit: int = 12) -> list[dict]:
    """同步时验一下换了域名的那几个源：新域名 200 → 做主域名；否则旧域名留主。"""
    from concurrent.futures import ThreadPoolExecutor
    prev = {x.get("id"): x for x in (old_cfg or {}).get("sources", [])}
    jobs = []
    for s in cfg["sources"]:
        if s.get("origin") != "respool" or not s.get("mirrors"):
            continue
        o = prev.get(s["id"]) or {}
        old_url, new_url = o.get("list_url"), s.get("list_url")
        if old_url and new_url and old_url != new_url:
            jobs.append((s, old_url, new_url))
    jobs = jobs[:limit]
    if not jobs:
        return []

    def check(item):
        s, old_url, new_url = item
        u = new_url.replace("{keyword}", "test").replace("{kw}", "test").replace("{page}", "1")
        return s, old_url, new_url, _probe_status(u)

    out = []
    with ThreadPoolExecutor(max_workers=max_workers) as ex:
        for s, old_url, new_url, status in ex.map(check, jobs):
            ok = 200 <= status < 400
            if ok:
                s["list_url"], s["mirrors"] = new_url, [old_url]
            else:  # 新域名不通 → 旧域名留主，新域名降级进回退链（下次同步再试）
                extra = [m for m in (s.get("mirrors") or []) if m not in (old_url, new_url)]
                s["list_url"], s["mirrors"] = old_url, [new_url] + extra
            out.append({"id": s["id"], "new": new_url, "old": old_url,
                        "status": status, "kept": "new" if ok else "old"})
    return out


def sync(dry_run: bool = False, out: str = DEFAULT_OUT,
         respool_path: str | None = None, apimapping_path: str | None = None) -> dict:
    """从作者服务器拉最新源清单 → 重建 config → 比对差异 → （非 dry_run）落地。

    安全阀：拉到的清单解析出的源少于 5 条就中止；写入前对 sources.json 与两个快照都留时间戳备份；
    用户在 settings 里的调参、以及非原版源池的自建源会被保留。
    """
    respool_path = respool_path or os.path.join(HERE, "ResPool.txt")
    apimapping_path = apimapping_path or os.path.join(HERE, "ApiMapping.txt")

    res_bytes = fetch(RESPOOL_URL)
    api_bytes = fetch(APIMAPPING_URL)
    res_text = res_bytes.decode("utf-8-sig", errors="replace")
    api_text = api_bytes.decode("utf-8-sig", errors="replace")

    glob, raw_sources = parse_respool(res_text)
    apimap = parse_apimapping(api_text)
    if len(raw_sources) < 5:
        raise RuntimeError(f"拉到的 ResPool 只有 {len(raw_sources)} 条，疑似被劫持/出错，已中止")

    cfg = build(glob, raw_sources, apimap)
    old_cfg = None
    if os.path.isfile(out):
        try:
            with open(out, encoding="utf-8") as f:
                old_cfg = json.load(f)
        except Exception:
            old_cfg = None

    kept_mirrors = 0
    if old_cfg:  # 保留用户设置、非源池自建源，以及旧域名（降级为回退镜像）
        prev = {s.get("id"): s for s in old_cfg.get("sources", [])}
        for s in cfg["sources"]:
            if s.get("origin") != "respool":
                continue
            o = prev.get(s["id"]) or {}
            olds: list[str] = []
            if o.get("list_url") and o["list_url"] != s.get("list_url"):
                olds.append(o["list_url"])
            for m in (o.get("mirrors") or []):
                if m not in olds:
                    olds.append(m)
            olds = [m for m in olds if m and m != s.get("list_url")]
            if olds:
                s["mirrors"] = olds[:2]  # 主域名 + 最多 2 个回退镜像
                kept_mirrors += 1
        st = dict(cfg.get("settings") or {})
        st.update(old_cfg.get("settings") or {})
        cfg["settings"] = st
        known = {s["id"] for s in cfg["sources"]}
        keep = [s for s in old_cfg.get("sources", [])
                if s.get("origin") not in ("respool", "builtin") and s.get("id") not in known]
        if keep:
            cfg["sources"].extend(keep)

    diff = diff_configs(old_cfg, cfg)
    result: dict = {
        "ok": True,
        "dry_run": bool(dry_run),
        "respool_url": RESPOOL_URL,
        "respool_version": (glob.get("版本") or "").strip(),
        "respool_bytes": len(res_bytes),
        "apimapping_bytes": len(api_bytes),
        "parsed_rows": len(raw_sources),
        "mirrors_kept": kept_mirrors,
        "diff": diff,
        "backups": [],
    }
    need_verify = [s for s in cfg["sources"]
                   if s.get("origin") == "respool" and s.get("mirrors")]
    result["will_verify"] = len(need_verify)
    if dry_run:
        result["diff"] = diff_configs(old_cfg, cfg)  # 含 mirrors 的预览
        return result

    if need_verify:
        result["verified"] = _verify_new_domains(cfg, old_cfg)
        result["diff"] = diff_configs(old_cfg, cfg)

    os.makedirs(HERE, exist_ok=True)
    stamp = time.strftime("%Y%m%d-%H%M%S")
    for path, data in ((respool_path, res_bytes), (apimapping_path, api_bytes)):
        if os.path.isfile(path):
            bak = f"{path}.bak-{stamp}"
            shutil.copy2(path, bak)
            result["backups"].append(bak)
        with open(path, "wb") as f:
            f.write(data)
    if os.path.isfile(out):
        bak = f"{out}.bak-{stamp}"
        shutil.copy2(out, bak)
        result["backups"].append(bak)
    tmp = f"{out}.tmp-{os.getpid()}"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(cfg, f, ensure_ascii=False, indent=2)
        f.write("\n")
    os.replace(tmp, out)
    result["applied_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
    return result


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--respool", default=os.path.join(HERE, "ResPool.txt"))
    ap.add_argument("--apimapping", default=os.path.join(HERE, "ApiMapping.txt"))
    ap.add_argument("--out", default=DEFAULT_OUT)
    ap.add_argument("--fetch", action="store_true", help="从作者服务器拉最新清单并重建（带差异对比）")
    ap.add_argument("--dry-run", action="store_true", help="只比对差异，不写任何文件")
    args = ap.parse_args()

    if args.fetch:
        res = sync(dry_run=args.dry_run, out=args.out,
                   respool_path=args.respool, apimapping_path=args.apimapping)
        d = res["diff"]
        print(f"[sync]  作者清单版本 {res['respool_version'] or '?'} · "
              f"ResPool {res['respool_bytes']}B / ApiMapping {res['apimapping_bytes']}B · "
              f"解析 {res['parsed_rows']} 条{'（dry-run，未写入）' if res['dry_run'] else ''}")
        print(f"        源池 {d['counts']['old']} → {d['counts']['new']}"
              f"（新增 {d['counts']['added']} · 移除 {d['counts']['removed']} · "
              f"变化 {d['counts']['changed']} · 不变 {d['counts']['unchanged']}）")
        for i in d["added"]:
            print(f"        + {i['id']}  {i.get('list_url') or ''}")
        for i in d["removed"]:
            print(f"        - {i['id']}  {i.get('list_url') or ''}")
        for c in d["changed"]:
            for f, v in c["fields"].items():
                print(f"        ~ {c['id']}.{f}: {str(v['old'])[:60]} → {str(v['new'])[:60]}")
        for b in res.get("backups", []):
            print(f"[bak]   {b}")
        return 0

    for p in (args.respool, args.apimapping):
        if not os.path.isfile(p):
            print(f"[!] 缺少 {p}（可用 --fetch 下载，或 --respool/--apimapping 指定路径）",
                  file=sys.stderr)
            return 2

    glob, raw_sources = parse_respool(open(args.respool, encoding="utf-8-sig").read())
    apimap = parse_apimapping(open(args.apimapping, encoding="utf-8-sig").read())
    cfg = build(glob, raw_sources, apimap)

    if os.path.isfile(args.out):
        bak = f"{args.out}.bak-{time.strftime('%Y%m%d-%H%M%S')}"
        shutil.copy2(args.out, bak)
        print(f"[bak]   {args.out} → {bak}")
    with open(args.out, "w", encoding="utf-8") as f:
        json.dump(cfg, f, ensure_ascii=False, indent=2)
        f.write("\n")

    srcs = cfg["sources"]
    real = [s for s in srcs if s["type"] != "demo"]
    print(f"[ok]    {args.out}")
    print(f"        源总数 {len(real)}（启用 {sum(1 for s in real if s['enabled'])}）"
          f" · API 型 {sum(1 for s in real if s['type'] == 'json')}"
          f" · 走 VPN 优先 {sum(1 for s in real if s['proxy'] == 'auto-vpn')}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
