#!/usr/bin/env python3.12
"""重生成 brand_hotspots_2 / vehicle_hotspots_3 配图"""
import urllib.request, re, io, os
from PIL import Image

UAS = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "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",
]
BAN = re.compile(r'(logo|icon|avatar|qrcode|share|weixin|placeholder|loading|blank|ad_|/ad/|banner|emoji|erweima|favicon)', re.I)

CASES = {
    "brand_hotspots_2": [
        "https://socialbeta.com/campaign/29069",
        "https://www.digitaling.com/projects/281365.html",
    ],
    "vehicle_hotspots_3": [
        "https://news.yiche.com/xinchexiaoxi/20261125/15114927075.html",
        "https://www.autohome.com.cn/news/202611/1308501.html",
    ],
}


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()


def grab(name, pages, minw=600):
    for page in pages:
        for ua in UAS:
            try:
                raw, final = get(page, ua=ua)
            except Exception as e:
                print(f"  · {name} {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 u not in urls:
                    urls.append(u)
            print(f"  · {name} {page[-45:]} 候选{len(urls)}")
            for u in urls[:25]:
                try:
                    raw2, _ = get(u, referer=final, binary=True, timeout=18)
                except Exception:
                    continue
                if len(raw2) < 25000:
                    continue
                try:
                    im = Image.open(io.BytesIO(raw2)); im.load()
                except Exception:
                    continue
                w, h = im.size
                if w < minw or h >= w * 0.95 or h < 300 or h / w < 0.45:
                    continue
                im = im.convert('RGB')
                if w != 750:
                    im = im.resize((750, round(h * 750 / w)), Image.LANCZOS)
                out = f"/data/news/images/1126/{name}.jpg"
                im.save(out, 'JPEG', quality=90)
                print(f"  ✅ {name}: {im.size} {os.path.getsize(out)//1024}KB  {u[-60:]}")
                return True
    print(f"  ❌ {name} 未取得")
    return False


if __name__ == '__main__':
    for n, pgs in CASES.items():
        grab(n, pgs)
