#!/usr/bin/env python3.12
"""单张补图：摩比斯条目换用盖世汽车原创报道页（m.gasgoo.com/news/70478918.html）"""
import urllib.request, re, io, os
from PIL import Image

UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"
OUT = "/data/news/images/1126/hyundai_buzz_topics_international_1.jpg"
PAGES = [
    "https://m.gasgoo.com/news/70478918.html",
    "https://auto.gasgoo.com/news/202611/25/70478918C501.shtml",
    "https://chejiahao.m.autohome.com.cn/info/26950204",
]
BAN = re.compile(r'(logo|icon|avatar|qrcode|share|weixin|placeholder|loading|blank|ad_|/ad/|banner|emoji|erweima)', 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(), r.geturl()


for page in PAGES:
    try:
        raw, final = get(page)
    except Exception as e:
        print(f"· {page[-45:]} 失败 {type(e).__name__}")
        continue
    html = raw.decode('utf-8', 'ignore')
    urls = []
    for m in re.finditer(r'(?:data-original|data-src|src|data-lazy-src|data-imgurl)\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?://[^/]+)', final)
            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 '20261125032519146542' in u:  # 与 domestic_2 同一张，排除
            continue
        if u not in urls:
            urls.append(u)
    print(f"· {page[-45:]} 候选{len(urls)}")
    for u in urls[: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"✅ intl_1: {im.size} {os.path.getsize(OUT)//1024}KB {u[-55:]}")
        raise SystemExit(0)
print("❌ 未取得")
