#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""批量抓取全部目录条目官方页（增量落盘 + 断点续跑）。"""
import re, json, subprocess, os, sys
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")
OUT = "catdesc.jsonl"
import threading
_lock = threading.Lock()


def curl(u, t=15):
    r = subprocess.run(["curl", "-s", "-L", "--compressed", "-A", UA,
                        "--max-time", str(t), u], capture_output=True)
    return r.stdout.decode("utf-8", "ignore")


def clean(s):
    s = re.sub(r"\s+", " ", s).strip()
    return (s.replace("&nbsp;", " ").replace("&amp;", "&").replace("&#8217;", "'")
            .replace("&#039;", "'").replace("&quot;", '"').replace("&#39;", "'")
            .replace("&rsquo;", "'").replace("&#8203;", "").replace("&ndash;", "–")
            .replace("&mdash;", "—").replace("&hellip;", "…"))


def extract(h):
    m = re.search(r'<meta[^>]+(?:property|name)="(?:og:description|description)"[^>]+content="([^"]{60,1500})"', h, re.I)
    if not m:
        m = re.search(r'content="([^"]{60,1500})"[^>]+(?:property|name)="(?:og:description|description)"', h, re.I)
    if m:
        return clean(re.sub(r"<[^>]+>", " ", m.group(1))), "meta"
    body = re.sub(r"(?is)<(script|style|nav|header|footer|form|svg|noscript)[^>]*>.*?</\1>", " ", h)
    cands = []
    for p in re.findall(r"<p\b[^>]*>(.*?)</p>", body, re.S | re.I)[:40]:
        t = clean(re.sub(r"<[^>]+>", " ", p))
        if len(t) > 100 and "cookie" not in t.lower() and "javascript" not in t.lower():
            cands.append(t)
        if len(cands) >= 2:
            break
    if cands:
        return " ".join(cands)[:1500], "body"
    return "", "none"


def load_done():
    done = {}
    if os.path.exists(OUT):
        for line in open(OUT, encoding="utf-8"):
            try:
                d = json.loads(line)
                if d.get("desc"):
                    done[d["key"]] = d
            except Exception:
                pass
    return done


def main():
    workers = int(sys.argv[1]) if len(sys.argv)>1 else 12
    tmo = int(sys.argv[2]) if len(sys.argv)>2 else 15
    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])
    done = load_done()
    print("已有缓存:", len(done), "/", len(rows))
    todo = [(i, r) for i, r in enumerate(rows) if f"{r[0]}|{r[2]}|{r[4]}" not in done]
    print("待抓取:", len(todo))

    f = open(OUT, "a", encoding="utf-8")

    def work(item):
        i, r = item
        sid, col, en, cn, deg, url, disc = r
        key = f"{sid}|{en}|{deg}"
        try:
            h2 = curl(url, tmo)
            desc, src = extract(h2) if h2 else ("", "empty")
        except Exception as e:
            desc, src = "", type(e).__name__
        rec = {"key": key, "i": i, "sid": sid, "col": col, "en": en, "cn": cn,
               "deg": deg, "url": url, "disc": disc, "desc": desc, "src": src}
        if desc:
            with _lock:
                f.write(json.dumps(rec, ensure_ascii=False) + "\n")
                f.flush()
        return len(desc)

    with ThreadPoolExecutor(max_workers=workers) as ex:
        for n, _ in enumerate(ex.map(work, todo)):
            if (n + 1) % 150 == 0:
                print("progress", n + 1, "/", len(todo), flush=True)
    f.close()
    print("完成")


if __name__ == "__main__":
    main()
