# -*- coding: utf-8 -*-
"""_fetch.py —— 批量并发抓取 + 本地缓存（供核验/回填共用，避免逐条串行重抓）。
用法：
    python _fetch.py https://a https://b --workers 12
    python _fetch.py --file urls.txt --workers 12
    python _fetch.py --status            # 看缓存里各站点的可达性汇总
输出：cache/<sha1>.html + cache/<sha1>.json（url/状态/日期/是否 CF 挑战）
口径：只做正常 HTTP 抓取；遇 403 人机验证只记录，不破解、不换代理。
"""
import sys, json, hashlib, pathlib, argparse, urllib.request, urllib.error
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime

BASE = pathlib.Path(r"D:\work buddy\2026-11-05-14-15-52")
CACHE = BASE / "cache"
CACHE.mkdir(exist_ok=True)

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"


def key(url):
    return hashlib.sha1(url.encode("utf-8")).hexdigest()[:16]


def fetch(url, timeout=20, retries=2):
    k = key(url)
    meta_p, html_p = CACHE / f"{k}.json", CACHE / f"{k}.html"
    if meta_p.exists() and html_p.exists():
        meta = json.loads(meta_p.read_text(encoding="utf-8"))
        if meta.get("status") == 200:
            return meta
    last = ""
    for i in range(retries + 1):
        try:
            req = urllib.request.Request(url, headers={
                "User-Agent": UA,
                "Accept": "text/html,application/xhtml+xml,application/pdf;q=0.9,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.9",
            })
            with urllib.request.urlopen(req, timeout=timeout) as r:
                body = r.read()
                status = r.getcode()
            html_p.write_bytes(body)
            meta = {"url": url, "status": status, "date": datetime.now().strftime("%Y-%m-%d %H:%M"),
                    "bytes": len(body), "flag": "ok"}
            meta_p.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
            return meta
        except urllib.error.HTTPError as e:
            code = e.code
            body = b""
            try:
                body = e.read()
            except Exception:
                pass
            head = body[:4000].decode("utf-8", "ignore").lower()
            flag = "cf-challenge" if (code == 403 and ("just a moment" in head or "challenge" in head or "cf-" in head)) else f"http-{code}"
            if i == retries:
                meta = {"url": url, "status": code, "date": datetime.now().strftime("%Y-%m-%d %H:%M"),
                        "bytes": len(body), "flag": flag}
                meta_p.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
                return meta
        except Exception as e:
            last = type(e).__name__ + ": " + str(e)[:80]
    meta = {"url": url, "status": 0, "date": datetime.now().strftime("%Y-%m-%d %H:%M"),
            "bytes": 0, "flag": "error", "err": last}
    meta_p.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
    return meta


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("urls", nargs="*")
    ap.add_argument("--file")
    ap.add_argument("--workers", type=int, default=12)
    ap.add_argument("--status", action="store_true")
    a = ap.parse_args()

    if a.status:
        from collections import Counter
        metas = [json.loads(p.read_text(encoding="utf-8")) for p in CACHE.glob("*.json")]
        print("缓存条目:", len(metas), " 状态分布:", dict(Counter(m["flag"] for m in metas)))
        return

    urls = list(a.urls)
    if a.file:
        urls += [l.strip() for l in pathlib.Path(a.file).read_text(encoding="utf-8").splitlines() if l.strip()]
    if not urls:
        print("no urls"); return

    from collections import Counter
    res = []
    with ThreadPoolExecutor(max_workers=a.workers) as ex:
        futs = {ex.submit(fetch, u): u for u in urls}
        for f in as_completed(futs):
            res.append(f.result())
    print("抓取", len(res), "条  状态:", dict(Counter(r["flag"] for r in res)))
    for r in res:
        if r["flag"] != "ok":
            print(f'  [{r["flag"]}] {r["url"]}')


if __name__ == "__main__":
    main()
