#!/usr/bin/env python3.12
"""从 6 条现代条目的原文页抓取配图并落盘 images/1126/
规则：取文章正文首张横向真图（宽度>=500），转真 JPEG，750 宽。
"""
import urllib.request, urllib.error, re, io, os, sys
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/1126"

TARGETS = [
    ("hyundai_buzz_topics_domestic_0", "https://www.cet.com.cn/cms/show-10677390.html"),
    ("hyundai_buzz_topics_domestic_1", "https://finance.sina.com.cn/tjhz/2026-11-25/doc-inizwfqx2109774.shtml"),
    ("hyundai_buzz_topics_domestic_2", "https://m.gasgoo.com/qcxl/article/82061.html"),
    ("hyundai_buzz_topics_international_0", "https://news.qq.com/rain/a/20261125A09NT500"),
    ("hyundai_buzz_topics_international_1", "https://news.qq.com/rain/a/20261125A0745500"),
    ("hyundai_buzz_topics_international_2", "https://finance.sina.com.cn/tech/digi/2026-11-25/doc-inizxiai9604129.shtml"),
]

BAN = re.compile(r'(logo|icon|avatar|qrcode|share|weixin|placeholder|loading|blank|ad_|/ad/|banner)', re.I)


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
    if binary:
        h["Accept"] = "image/avif,image/webp,image/apng,image/*,*/*;q=0.8"
    req = urllib.request.Request(url, headers=h)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return r.read()


def find_images(html, base):
    urls = []
    for m in re.finditer(r'(?:data-original|data-src|src)\s*=\s*["\']([^"\']+)["\']', html, re.I):
        u = m.group(1).strip()
        if not u or u.startswith('data:'):
            continue
        if u.startswith('//'):
            u = 'https:' + u
        elif u.startswith('/'):
            mm = re.match(r'(https?://[^/]+)', base)
            if not mm:
                continue
            u = mm.group(1) + u
        if not re.match(r'https?://', u):
            continue
        if not re.search(r'\.(jpg|jpeg|png|webp)(\?|$)', u, re.I):
            continue
        if BAN.search(u):
            continue
        if u not in urls:
            urls.append(u)
    return urls


def try_image(u, page):
    try:
        raw = get(u, referer=page, binary=True, timeout=20)
    except Exception:
        return None
    if len(raw) < 12000:
        return None
    try:
        im = Image.open(io.BytesIO(raw))
        im.load()
    except Exception:
        return None
    w, h = im.size
    if w < 500:
        return None
    if h >= w * 1.15:  # 竖向不要
        return None
    return im.convert('RGB')


def main():
    for name, page in TARGETS:
        out = os.path.join(OUT, name + '.jpg')
        try:
            html = get(page).decode('utf-8', 'ignore')
        except Exception as e:
            print(f"  ❌ {name}: 页面抓取失败 {type(e).__name__}")
            continue
        cands = find_images(html, page)
        got = None
        used = ''
        for u in cands[:12]:
            im = try_image(u, page)
            if im:
                got, used = im, u
                break
        if not got:
            print(f"  ⚠️ {name}: 无可用横向图（候选 {len(cands)}）")
            continue
        w, h = got.size
        if w != 750:
            got = got.resize((750, round(h * 750 / w)), Image.LANCZOS)
        got.save(out, 'JPEG', quality=88)
        print(f"  ✅ {name}: {w}x{h} -> {got.size} {os.path.getsize(out)//1024}KB  {used[-60:]}")


if __name__ == '__main__':
    main()
