#!/usr/bin/env python3.12
"""chinanews 三条补图：优先 smimg_ 大图，长宽比严格 1.15-2.6"""
import urllib.request, re, io, os, json
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"

TARGETS = [
    ("social_hotspots_0", "https://www.chinanews.com.cn/cj/2026/11-26/10738085.shtml"),
    ("social_hotspots_1", "https://www.chinanews.com.cn/ty/2026/11-26/10738082.shtml"),
    ("social_hotspots_2", "https://www.chinanews.com.cn/cj/2026/11-26/10738080.shtml"),
]


def get(url, referer=None, binary=False, timeout=25):
    h = {"User-Agent": UA, "Referer": referer or "https://www.chinanews.com.cn/"}
    with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=timeout) as r:
        d = r.read()
    return d if binary else d.decode("utf-8", "ignore")


def try_save(url, page, path):
    try:
        raw = get(url, referer=page, binary=True)
    except Exception as e:
        return None, f"dl {str(e)[:30]}"
    if len(raw) < 15000:
        return None, f"small {len(raw)}"
    try:
        im = Image.open(io.BytesIO(raw)); im.load()
    except Exception as e:
        return None, f"bad {str(e)[:20]}"
    w, h = im.size
    ar = w / h
    if w < 550 or not (1.15 <= ar <= 2.6):
        return None, f"形状 {w}x{h} ar={ar:.2f}"
    im = im.convert("RGB")
    if im.width > 750:
        im = im.resize((750, int(im.height * 750 / im.width)), Image.LANCZOS)
    im.save(path, "JPEG", quality=88)
    return path, f"ok {w}x{h} ar={ar:.2f}"


for name, page in TARGETS:
    path = os.path.join(OUT, name + ".jpg")
    html = get(page)
    urls = []
    # 1. 优先同日期 smimg_ 大图
    for m in re.finditer(r'(//i2\.chinanews\.com\.cn/simg/(?:hd|cmshd)/[^"\'\s]+)', html):
        u = "https:" + m.group(1)
        if u not in urls:
            urls.append(u)
    # 2. 再补其他
    for m in re.finditer(r'(//i2\.chinanews\.com\.cn/simg/[^"\'\s]+?\.(?:jpg|jpeg|png))', html):
        u = "https:" + m.group(1)
        if u not in urls:
            urls.append(u)
    ok = False
    for u in urls[:20]:
        p, msg = try_save(u, page, path)
        if p:
            print(f"✅ {name}: {msg} <- {u[:85]}")
            ok = True
            break
    if not ok:
        print(f"❌ {name}: 无合适图（共 {len(urls)} 候选）")
