#!/usr/bin/env python3.12
"""补 2 张：gasgoo 82061 + qq 20261126A06LO100"""
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/1127"

T = [
    ("hyundai_buzz_topics_domestic_2", [
        "https://auto.gasgoo.com/qcxl/article/82061.html",
        "https://www.gasgoo.com/qcxl/article/82061.html",
        "https://m.gasgoo.com/qcxl/article/82061.html",
    ]),
    ("hyundai_buzz_topics_international_0", [
        "https://news.qq.com/rain/a/20261126A06LO100",
        "https://view.inews.qq.com/a/20261126A06LO100",
    ]),
]


def get(u, ref=None, binary=False):
    h = {"User-Agent": UA, "Accept-Language": "zh-CN,zh;q=0.9"}
    if ref:
        h["Referer"] = ref
    with urllib.request.urlopen(urllib.request.Request(u, headers=h), timeout=25) as r:
        d = r.read()
    return d if binary else d.decode("utf-8", "ignore")


for name, pages in T:
    path = os.path.join(OUT, name + ".jpg")
    done = False
    for page in pages:
        try:
            html = get(page)
        except Exception as e:
            print(f"  页失败 {page[:50]} {str(e)[:40]}")
            continue
        us = []
        for m in re.finditer(r'<meta[^>]+?(?:property|name)=["\']og:image["\'][^>]*?content=["\']([^"\']+)', html, re.I):
            us.append(m.group(1))
        for m in re.finditer(r'<img[^>]+?(?:data-src|data-original|src)=["\']([^"\']+\.(?:jpg|jpeg|png|webp)[^"\']*)', html, re.I):
            us.append(m.group(1))
        for u in us[:15]:
            u = u.strip()
            if u.startswith("//"):
                u = "https:" + u
            elif u.startswith("/"):
                u = re.match(r'(https?://[^/]+)', page).group(1) + u
            if not u.startswith("http"):
                continue
            if re.search(r'(logo|icon|avatar|qrcode|share|weixin|nav|gif$|default|banner)', u, re.I):
                continue
            # 腾讯转原图
            u = re.sub(r'(inews\.gtimg\.com/om_bt/[^/]+?)/\d+$', r'\1/1000', u)
            try:
                raw = get(u, ref=page, binary=True)
                if len(raw) < 12000:
                    continue
                im = Image.open(io.BytesIO(raw)); im.load()
                w, h = im.size
                if w < 500 or w / h < 1.1:
                    continue
                im = im.convert("RGB")
                if w > 750:
                    im = im.resize((750, int(h * 750 / w)), Image.LANCZOS)
                im.save(path, "JPEG", quality=88)
                print(f"✅ {name}: {w}x{h} <- {u[:80]}")
                done = True
                break
            except Exception:
                continue
        if done:
            break
    if not done:
        print(f"❌ {name}: 全失败")
