#!/usr/bin/env python3.12
"""1127 刊：从原文页抓配图落盘 images/1127/，取正文首张横向真图(宽>=500)，转真JPEG，750宽"""
import urllib.request, urllib.error, re, io, os, sys, json
from PIL import Image

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
OUT = "/data/news/images/1127"
BAN = re.compile(r'(logo|icon|avatar|qrcode|qr_|share|weixin|placeholder|loading|blank|ad_|/ad/|banner|/5g|sprite|default)', re.I)

TARGETS = [
    ("hyundai_buzz_topics_domestic_0", "https://finance.eastmoney.com/a/202611263940467932.html"),
    ("hyundai_buzz_topics_domestic_1", "https://news.qq.com/rain/a/20261126A0703I00"),
    ("hyundai_buzz_topics_domestic_2", "https://m.gasgoo.com/qcxl/article/82061.html"),
    ("hyundai_buzz_topics_international_0", "https://news.qq.com/rain/a/20261126A06LO100"),
    ("hyundai_buzz_topics_international_1", "https://news.qq.com/rain/a/20261125A0745500"),
    ("hyundai_buzz_topics_international_2", "https://news.qq.com/rain/a/20261125A09NT500"),
    ("social_hotspots_0", "https://www.chinanews.com.cn/cj/2026/11-26/10738085.shtml"),
    ("social_hotspots_1", "https://www.chinanews.com.cn/ty/2026/11-26/10738082.shtml"),
    ("social_hotspots_2", "https://www.chinanews.com.cn/cj/2026/11-26/10738080.shtml"),
]


def get(url, referer=None, binary=False, timeout=20):
    h = {"User-Agent": UA, "Accept-Language": "zh-CN,zh;q=0.9"}
    if referer:
        h["Referer"] = referer
    req = urllib.request.Request(url, headers=h)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        data = r.read()
    if binary:
        return data
    for enc in ("utf-8", "gbk", "gb18030"):
        try:
            return data.decode(enc, "ignore")
        except Exception:
            continue
    return data.decode("utf-8", "ignore")


def cands(html, page):
    out = []
    for m in re.finditer(r'<meta[^>]+property=["\']og:image["\'][^>]+content=["\']([^"\']+)', html, re.I):
        out.append(m.group(1))
    for m in re.finditer(r'<meta[^>]+content=["\']([^"\']+)["\'][^>]+property=["\']og:image', html, re.I):
        out.append(m.group(1))
    for m in re.finditer(r'<img[^>]+(?:data-src|data-original|src)=["\']([^"\']+\.(?:jpg|jpeg|png|webp)[^"\']*)', html, re.I):
        out.append(m.group(1))
    res = []
    for u in out:
        u = u.strip()
        if u.startswith("//"):
            u = "https:" + u
        elif u.startswith("/"):
            m = re.match(r'(https?://[^/]+)', page)
            u = (m.group(1) if m else "") + u
        if not u.startswith("http"):
            continue
        if BAN.search(u):
            continue
        if u not in res:
            res.append(u)
    return res


def save(url, page, path):
    try:
        raw = get(url, referer=page, binary=True, timeout=25)
    except Exception as e:
        return None, f"dl fail {e}"
    if len(raw) < 12000:
        return None, f"too small {len(raw)}"
    try:
        im = Image.open(io.BytesIO(raw))
        im.load()
    except Exception as e:
        return None, f"not image {e}"
    w, h = im.size
    if w < 500 or w <= h * 1.05:
        return None, f"not landscape {w}x{h}"
    im = im.convert("RGB")
    if im.width > 750:
        im = im.resize((750, int(im.height * 750 / im.width)), Image.LANCZOS)
    im.save(path, "JPEG", quality=88)
    return path, f"ok {w}x{h}"


def main():
    os.makedirs(OUT, exist_ok=True)
    result = {}
    for name, page in TARGETS:
        path = os.path.join(OUT, name + ".jpg")
        try:
            html = get(page)
        except Exception as e:
            print(f"❌ {name}: page fail {e}")
            result[name] = None
            continue
        ok = False
        for u in cands(html, page)[:8]:
            p, msg = save(u, page, path)
            if p:
                print(f"✅ {name}: {msg} <- {u[:70]}")
                result[name] = path
                ok = True
                break
            else:
                print(f"   skip {msg}")
        if not ok:
            print(f"❌ {name}: no usable img")
            result[name] = None
    json.dump(result, open("/tmp/thumb_1127.json", "w"), ensure_ascii=False, indent=1)
    print("\n成功:", sum(1 for v in result.values() if v), "/", len(TARGETS))


if __name__ == "__main__":
    main()
