#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""用 urllib 通道补抓 curl 失败的条目（NYU / Penn / USC 等）。"""
import re, json, os, ssl, sys, threading
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from fetch_all import extract, clean

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
CTX = ssl.create_default_context()
CTX.check_hostname = False
CTX.verify_mode = ssl.CERT_NONE
OUT = "catdesc.jsonl"
_lock = threading.Lock()


def get(u, t=20):
    req = urllib.request.Request(u, headers={"User-Agent": UA, "Accept": "text/html,*/*;q=0.8",
                                             "Accept-Language": "en-US,en;q=0.9"})
    with urllib.request.urlopen(req, timeout=t, context=CTX) as r:
        return r.read().decode("utf-8", "ignore")


def main():
    h = open("index_main.html", encoding="utf-8").read()
    a = h.find("const CATD=[")
    b = h.find("const DOCDEG")
    rows = re.findall(r'\["([a-z0-9\-]+)", "([^"]*)", "([^"]*)", "([^"]*)", "([^"]*)", "([^"]*)", "([^"]*)"\]', h[a:b])
    have = set()
    if os.path.exists(OUT):
        for line in open(OUT, encoding="utf-8"):
            try:
                d = json.loads(line)
                if d.get("desc"):
                    have.add(d["key"])
            except Exception:
                pass
    todo = [r for r in rows if f"{r[0]}|{r[2]}|{r[4]}" not in have]
    print("缓存", len(have), "待补", len(todo))

    f = open(OUT, "a", encoding="utf-8")

    def work(r):
        sid, col, en, cn, deg, url, disc = r
        url = url.replace("&amp;", "&")
        try:
            hh = get(url)
            desc, src = extract(hh) if hh else ("", "empty")
        except Exception as e:
            desc, src = "", type(e).__name__
        if desc:
            rec = {"key": f"{sid}|{en}|{deg}", "i": 0, "sid": sid, "col": col, "en": en,
                   "cn": cn, "deg": deg, "url": url, "disc": disc, "desc": desc, "src": src}
            with _lock:
                f.write(json.dumps(rec, ensure_ascii=False) + "\n")
                f.flush()
        return bool(desc)

    with ThreadPoolExecutor(max_workers=6) as ex:
        res = list(ex.map(work, todo))
    f.close()
    print("补抓成功", sum(res), "/", len(todo))


if __name__ == "__main__":
    main()
