#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""补抓剩余缺失条目：带完整浏览器请求头（可突破部分 WAF）。"""
import json, subprocess, threading, sys, os
from concurrent.futures import ThreadPoolExecutor

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
HDR = ["-H", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
       "-H", "Accept-Language: en-US,en;q=0.9",
       "-H", 'sec-ch-ua: "Chromium";v="131", "Not_A Brand";v="24"',
       "-H", "sec-ch-ua-mobile: ?0",
       "-H", 'sec-ch-ua-platform: "Windows"',
       "-H", "Sec-Fetch-Dest: document",
       "-H", "Sec-Fetch-Mode: navigate",
       "-H", "Sec-Fetch-Site: none",
       "-H", "Sec-Fetch-User: ?1",
       "-H", "Upgrade-Insecure-Requests: 1"]

from fetch_all import extract  # 复用提取逻辑

_lock = threading.Lock()


def curl(u, t=30):
    r = subprocess.run(["curl", "-sS", "-L", "--compressed", "-A", UA, "--max-time", str(t)] + HDR + [u],
                       capture_output=True)
    return r.stdout.decode("utf-8", "ignore")


def main():
    items = json.load(open("miss_list.json", encoding="utf-8"))
    out = "catdesc.jsonl"
    done = set()
    for line in open(out, encoding="utf-8"):
        try:
            d = json.loads(line)
            if d.get("desc"):
                done.add(d["key"])
        except Exception:
            pass
    todo = [r for r in items if f"{r['sid']}|{r['en']}|{r['deg']}" not in done]
    print("待抓", len(todo), flush=True)
    f = open(out, "a", encoding="utf-8")
    stats = {}

    def work(r):
        key = f"{r['sid']}|{r['en']}|{r['deg']}"
        try:
            h = curl(r["url"])
            desc, src = extract(h) if h else ("", "empty")
        except Exception as e:
            desc, src = "", type(e).__name__
        if desc and len(desc) >= 60:
            rec = dict(r, key=key, desc=desc, src=src)
            with _lock:
                f.write(json.dumps(rec, ensure_ascii=False) + "\n")
                f.flush()
        with _lock:
            stats[r["sid"]] = stats.get(r["sid"], [0, 0])
            stats[r["sid"]][0 if desc else 1] += 1
        return bool(desc)

    with ThreadPoolExecutor(max_workers=6) as ex:
        list(ex.map(work, todo))
    f.close()
    print("结果:", {k: f"成功{v[0]}/失败{v[1]}" for k, v in stats.items()})


if __name__ == "__main__":
    main()
