#!/usr/bin/env python3.12
"""1127 刊配图 v2：站点头部优先 + 腾讯 /1000 原图 + chinawens 正文区解析"""
import urllib.request, urllib.error, 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"
BAN = re.compile(r'(logo|icon|avatar|qrcode|qr_|share|weixin|placeholder|loading|blank|ad_|/ad/|banner|sprite|default|/nav|/toparr|\.gif$)', re.I)

TARGETS = [
    ("hyundai_buzz_topics_domestic_0", "https://finance.eastmoney.com/a/202611263940467932.html"),
    ("hyundai_buzz_topics_domestic_1", "https://news.qq.com/rain/a/20261126A0703I00"),
    ("hyundai_buzz_topics_domestic_2", "https://m.gasgoo.com/qcxl/article/82061.html"),
    ("hyundai_buzz_topics_international_0", "https://news.qq.com/rain/a/20261126A06LO100"),
    ("hyundai_buzz_topics_international_1", "https://news.qq.com/rain/a/20261125A0745500"),
    ("hyundai_buzz_topics_international_2", "https://news.qq.com/rain/a/20261125A09NT500"),
    ("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, "Accept-Language": "zh-CN,zh;q=0.9"}
    if referer:
        h["Referer"] = referer
    req = urllib.request.Request(url, headers=h)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        data = r.read()
    if binary:
        return data
    return data.decode("utf-8", "ignore")


def norm(u, page):
    u = u.strip().replace("&amp;", "&")
    if u.startswith("//"):
        u = "https:" + u
    elif u.startswith("/"):
        m = re.match(r'(https?://[^/]+)', page)
        u = (m.group(1) if m else "") + u
    # 腾讯图床：转 1000 原图
    u = re.sub(r'(inews\.gtimg\.com/om_ls/[^/]+)_\d+_\d+/0$', r'\1/0', u)
    u = re.sub(r'(inews\.gtimg\.com/om_bt/[^/]+?)/\d+$', r'\1/1000', u)
    return u


def cands(html, page):
    out = []
    for m in re.finditer(r'<meta[^>]+?(?:property|name)=["\']og:image["\'][^>]*?content=["\']([^"\']+)', html, re.I):
        out.append(m.group(1))
    for m in re.finditer(r'<meta[^>]+?content=["\']([^"\']+)["\'][^>]*?(?:property|name)=["\']og:image', html, re.I):
        out.append(m.group(1))
    # 正文区优先
    body = html
    mb = re.search(r'(<div[^>]+(?:class|id)=["\'][^"\']*(?:article|content|detail|main|TRS_Editor)[^"\']*["\'][\s\S]{0,40000})', html, re.I)
    if mb:
        body = mb.group(1)
    for m in re.finditer(r'<img[^>]+?(?:data-src|data-original|data-lazy|srcset|src)=["\']([^"\']+)', body, re.I):
        out.append(m.group(1).split()[0])
    res = []
    for u in out:
        u = norm(u, page)
        if not u.startswith("http"):
            continue
        if BAN.search(u):
            continue
        if u not in res:
            res.append(u)
    return res


def save(url, page, path):
    try:
        raw = get(url, referer=page, binary=True)
    except Exception as e:
        return None, f"dl fail {str(e)[:40]}"
    if len(raw) < 8000:
        return None, f"small {len(raw)}"
    try:
        im = Image.open(io.BytesIO(raw))
        im.load()
    except Exception as e:
        return None, f"notimage {str(e)[:25]}"
    w, h = im.size
    if w < 450 or w <= h * 1.0:
        return None, f"notlandscape {w}x{h}"
    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}"


def main():
    os.makedirs(OUT, exist_ok=True)
    result = {}
    for name, page in TARGETS:
        path = os.path.join(OUT, name + ".jpg")
        if os.path.exists(path) and os.path.getsize(path) > 10000:
            print(f"⏭  {name}: 已存在")
            result[name] = path
            continue
        try:
            html = get(page)
        except Exception as e:
            print(f"❌ {name}: page fail {str(e)[:50]}")
            result[name] = None
            continue
        ok = False
        cs = cands(html, page)
        print(f"·  {name}: 候选 {len(cs)}")
        for u in cs[:12]:
            p, msg = save(u, page, path)
            if p:
                print(f"   ✅ {msg} <- {u[:75]}")
                result[name] = path
                ok = True
                break
        if not ok:
            print(f"   ❌ 全失败")
            result[name] = None
    json.dump(result, open("/tmp/thumb_1127.json", "w"), ensure_ascii=False, indent=1)
    print("\n成功:", sum(1 for v in result.values() if v), "/", len(TARGETS))


if __name__ == "__main__":
    main()
