#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""用改进提取器补抓剩余条目（低并发，避免再次触发限流）。"""
import json, subprocess, threading, time
from concurrent.futures import ThreadPoolExecutor
from extract2 import extract2

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"]
_lock = threading.Lock()


def curl(u, t=35):
    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"))
    done = set()
    for line in open("catdesc.jsonl", 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("catdesc.jsonl", "a", encoding="utf-8")
    stats = {}

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

    with ThreadPoolExecutor(max_workers=3) 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()
