#!/usr/bin/env python3.12
"""阶段4收尾：补齐2张缺失 + social0换唯一图（豆包已不可用，走公开图源）"""
import urllib.request, re, io, os
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"


def get(u, ref=None, binary=False):
    h = {"User-Agent": UA, "Accept-Language": "zh-CN,zh;q=0.9"}
    if ref:
        h["Referer"] = ref
    with urllib.request.urlopen(urllib.request.Request(u, headers=h), timeout=25) as r:
        d = r.read()
    return d if binary else d.decode("utf-8", "ignore")


def grab(name, pages, minw=500):
    path = os.path.join(OUT, name + ".jpg")
    seen = set()
    for page in pages:
        try:
            html = get(page)
        except Exception as e:
            print(f"   页失败 {page[:60]} {str(e)[:35]}")
            continue
        us = []
        for m in re.finditer(r'<meta[^>]+?(?:property|name)=["\']og:image["\'][^>]*?content=["\']([^"\']+)', html, re.I):
            us.append(m.group(1))
        for m in re.finditer(r'<img[^>]+?(?:data-src|data-original|src)=["\']([^"\']+\.(?:jpg|jpeg|png|webp)[^"\']*)', html, re.I):
            us.append(m.group(1))
        for u in us[:18]:
            u = u.strip()
            if u.startswith("//"):
                u = "https:" + u
            elif u.startswith("/"):
                mm = re.match(r'(https?://[^/]+)', page)
                if not mm:
                    continue
                u = mm.group(1) + u
            if not u.startswith("http") or u in seen:
                continue
            seen.add(u)
            if re.search(r'(logo|icon|avatar|qrcode|share|weixin|nav|\.gif$|default|banner|sprite|/ad/)', u, re.I):
                continue
            u = re.sub(r'(inews\.gtimg\.com/om_bt/[^/]+?)/\d+$', r'\1/1000', u)
            try:
                raw = get(u, ref=page, binary=True)
                if len(raw) < 12000:
                    continue
                im = Image.open(io.BytesIO(raw))
                im.load()
                w, h = im.size
                if w < minw or w / h < 1.1 or w / h > 3.0:
                    continue
                im = im.convert("RGB")
                if w > 750:
                    im = im.resize((750, int(h * 750 / w)), Image.LANCZOS)
                im.save(path, "JPEG", quality=88)
                print(f"  ✅ {name}: {w}x{h} <- {u[:78]}")
                return True
            except Exception:
                continue
    print(f"  ❌ {name}: 全失败")
    return False


TASKS = [
    # 1. 盖世汽车销量榜 → 同站销量数据页
    ("hyundai_buzz_topics_domestic_2", [
        "https://m.gasgoo.com/qcxl",
        "https://www.gasgoo.com/qcxl",
        "https://auto.gasgoo.com/qcxl",
    ]),
    # 2. 现代集团人事 → 集团官网新闻
    ("hyundai_buzz_topics_international_0", [
        "https://www.hyundaimotorgroup.com/en/news",
        "https://www.hyundai.com.cn/news/440.html",
    ]),
    # 3. social0 算法协商 → 换劳动/平台监管类新闻源图
    ("social_hotspots_0", [
        "https://www.chinanews.com.cn/cj/2026/11-26/10738083.shtml",
        "https://www.chinanews.com.cn/cj/2026/11-26/10738084.shtml",
    ]),
]

for name, pages in TASKS:
    print(f"· {name}")
    grab(name, pages)
