#!/usr/bin/env python3.12
"""intl_1 单图：亚洲今日 / 车家号 26950206 取图"""
import urllib.request, re, io, os
from PIL import Image

UAS = [
    "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",
    "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/hyundai_buzz_topics_international_1.jpg"
PAGES = [
    "https://cn.asiatoday.co.kr/view.php?key=20261125001102432",
    "https://chejiahao.autohome.com.cn/info/26950206",
    "https://www.mk.co.kr/cn/business/11950100",
]
BAN = re.compile(r'(logo|icon|avatar|qrcode|share|weixin|placeholder|loading|blank|ad_|/ad/|banner|emoji|erweima|favicon)', re.I)
SKIP = ('20261125032519146542',)


def get(url, referer=None, binary=False, ua=None, timeout=20):
    h = {"User-Agent": ua or UAS[0], "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:
    for ua in UAS:
        try:
            raw, final = get(page, ua=ua)
        except Exception as e:
            print(f"· {page[-42:]} 失败 {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) or any(s in u for s in SKIP):
                continue
            if u not in urls:
                urls.append(u)
        print(f"· {page[-42:]} 候选{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("❌ 未取得")
