#!/usr/bin/env python3
"""
probe_all.py — 逐源实测（打本机 1114 的 /api/probe），输出一张源健康表。

用法：
  python3 tools/probe_all.py --kw 流浪地球
  python3 tools/probe_all.py --kw ubuntu --only 1377x,knaben --json
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import urllib.request
from concurrent.futures import ThreadPoolExecutor

APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SOURCES = os.path.join(APP_DIR, "sources.json")
ENDPOINT = "http://127.0.0.1:1114/api/probe"


def probe(src: dict, kw: str) -> dict:
    body = json.dumps({"kw": kw, "source": src}, ensure_ascii=False).encode()
    req = urllib.request.Request(ENDPOINT, data=body,
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=180) as r:
        out = json.loads(r.read().decode("utf-8"))
    out["_id"] = src["id"]
    out["_name"] = src.get("name", src["id"])
    out["_proxy"] = src.get("proxy")
    out["_encoding"] = src.get("encoding")
    return out


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--kw", default="流浪地球")
    ap.add_argument("--only", default="", help="逗号分隔的源 id")
    ap.add_argument("--json", action="store_true", help="输出完整 JSON")
    ap.add_argument("--workers", type=int, default=6)
    args = ap.parse_args()

    cfg = json.load(open(SOURCES, encoding="utf-8"))
    want = {x for x in args.only.split(",") if x}
    srcs = [s for s in cfg["sources"]
            if s.get("enabled") and s.get("type") != "demo" and (not want or s["id"] in want)]

    with ThreadPoolExecutor(max_workers=args.workers) as ex:
        results = list(ex.map(lambda s: probe(s, args.kw), srcs))

    results.sort(key=lambda r: (-(r.get("rows") or 0), r["_id"]))
    if args.json:
        print(json.dumps(results, ensure_ascii=False, indent=1))
        return 0

    ok = 0
    print(f"关键词：{args.kw}   （{len(results)} 源）")
    print(f"{'源':<10} {'策略':<9} {'编码':<14} {'HTTP':<5} {'通道':<7} {'条数':<5} "
          f"{'磁链':<5} 首条标题 / 提示")
    print("-" * 130)
    for r in results:
        rows = r.get("rows") or 0
        withmag = r.get("with_magnet")
        sample = ""
        if r.get("sample"):
            sample = (r["sample"][0].get("title") or "")[:52]
        elif r.get("error"):
            sample = "ERR " + str(r["error"])[:60]
        elif r.get("hint"):
            sample = "HINT " + str(r["hint"])[:60]
        flag = "✓" if rows else "✗"
        if rows:
            ok += 1
        print(f"{r['_id']:<10} {str(r['_proxy']):<9} {str(r['_encoding']):<14} "
              f"{str(r.get('http_status') or '-'):<5} {str(r.get('via') or '-'):<7} "
              f"{flag}{rows:<4} {str(withmag if withmag is not None else '-'):<5} {sample}")
    print("-" * 130)
    print(f"有效源 {ok}/{len(results)}；"
          f"有磁链 {sum(1 for r in results if r.get('with_magnet'))}；"
          f"失败 {sum(1 for r in results if r.get('error') or r.get('http_status'))}"
          f"（HTTP≠200: {sum(1 for r in results if r.get('http_status') and r['http_status'] != 200)}）")
    return 0


if __name__ == "__main__":
    sys.exit(main())
