#!/usr/bin/env python3.12
"""补齐剩余 3 张现代配图：仅走 web（豆包 API 当前 ClosedEndpoint 不可用）"""
import urllib.request, re, io, os
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"
BAN = re.compile(r'(logo|icon|avatar|qrcode|share|weixin|placeholder|loading|blank|ad_|/ad/|banner|5g)', re.I)

CASES = [
    ("hyundai_buzz_topics_domestic_2", [
        "https://m.gasgoo.com/qcxl/article/82061.html",
        "https://auto.gasgoo.com/qcxl/article/82061.html",
        "https://www.gasgoo.com/qcxl/article/82061.html",
        "https://www.gasgoo.com/news/202611/25/2323.html",
    ]),
    ("hyundai_buzz_topics_international_0", [
        "https://news.qq.com/rain/a/20261125A09NT500",
        "https://view.inews.qq.com/a/20261125A09NT500",
    ]),
    ("hyundai_buzz_topics_international_1", [
        "https://news.qq.com/rain/a/20261125A0745500",
        "https://view.inews.qq.com/a/20261125A0745500",
    ]),
]


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(), r.geturl()


def find_images(html, base, loose=False):
    urls = []
    for m in re.finditer(r'(?:data-original|data-src|src|data-lazy-src|data-imgurl|content)\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 not loose and BAN.search(u):
            continue
        if u not in urls:
            urls.append(u)
    return urls


for name, pages in CASES:
    out = os.path.join(OUT, name + '.jpg')
    done = False
    for page in pages:
        try:
            raw, final = get(page)
        except Exception as e:
            print(f"  · {name}: {page[-40:]} 抓取失败 {type(e).__name__}")
            continue
        html = raw.decode('utf-8', 'ignore')
        cands = find_images(html, final)
        print(f"  · {name}: {page[-40:]} 候选{len(cands)}")
        for u in cands[:15]:
            try:
                raw2, _ = get(u, referer=final, binary=True, timeout=18)
            except Exception:
                continue
            if len(raw2) < 12000:
                continue
            try:
                im = Image.open(io.BytesIO(raw2)); im.load()
            except Exception:
                continue
            w, h = im.size
            if w < 500 or h >= w * 1.15 or h < 250 or h / w < 0.4:
                continue
            im = im.convert('RGB')
            if w != 750:
                im = im.resize((750, round(h * 750 / w)), Image.LANCZOS)
            im.save(out, 'JPEG', quality=88)
            print(f"  ✅ {name}: {im.size} {os.path.getsize(out)//1024}KB  {u[-55:]}")
            done = True
            break
        if done:
            break
    if not done:
        print(f"  ❌ {name}: 无可用图")
