#!/usr/bin/env python3.12
"""尝试从 autohome 原文提取大尺寸横向图，替换豆包生成图"""
import urllib.request, re, json, os, ssl

UA = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36',
      'Referer': 'https://www.autohome.com.cn/'}

# 候选图片（从上一轮抓取）
candidates = {
    0: [
        'http://img3.autoimg.cn/chejiahaodfs/g33/M04/47/B8/ChxpVWpMY06AP9GxAAjhUR98UZ803',
        'http://img3.autoimg.cn/chejiahaodfs/g33/M07/47/B9/ChxpVmpMY1qAY1N2AAZM4sYFCqU99',
        'http://www2.autoimg.cn/chejiahaodfs/g34/M03/05/62/ChxpWGp4R9WAR2hyAAIU_Wl9NbI75',
        'http://www2.autoimg.cn/chejiahaodfs/g34/M0B/02/60/ChtpWGp4R9WABJ6vAAJUCWkkAn014',
        'http://www2.autoimg.cn/chejiahaodfs/g33/M00/09/F9/Chto52p4R9WAeFKyAAHl51SIe2E53',
        'http://www2.autoimg.cn/chejiahaodfs/g34/M00/02/60/ChtpWGp4R9WAPN7yAAigMWKIHJE64',
    ],
    1: [
        'http://car3.autoimg.cn/cardfs/product/g33/M04/6A/EC/Chto52pm0eGAZ2O9AA9Phv5JLxg',
        'http://car2.autoimg.cn/cardfs/product/g34/M06/65/C0/ChtpWGpm0eGANjFDABDwtxUMl20',
        'http://car2.autoimg.cn/cardfs/product/g34/M09/68/A4/ChxpWGpm0eGAIkl6ABRnoxBUHlw',
        'http://car2.autoimg.cn/cardfs/product/g34/M07/68/A4/ChxpWGpm0eCAXCu4ABAG53pTy8c',
        'http://car2.autoimg.cn/cardfs/product/g33/M01/6A/D5/ChxpVmpm0duABHksABO2jsxEwdQ',
    ],
    3: [
        'http://www2.autoimg.cn/chejiahaodfs/g34/M0A/24/69/ChtpWGqP7maAVT26AAJ7RWiyobE81',
        'http://www2.autoimg.cn/chejiahaodfs/g34/M09/27/61/ChxpV2qP7mmAapbcABaDAXt56hs32',
        'http://www2.autoimg.cn/chejiahaodfs/g34/M07/24/69/ChtpWGqP7mmAANX_ABU3_YdsiwM42',
        'http://car3.autoimg.cn/cardfs/product/g33/M06/B8/14/ChxpVmqHq66AGqPiAFMguRCH3bU',
        'http://car3.autoimg.cn/cardfs/product/g34/M06/B4/95/ChxpWGqHq6mAPIaQAGBdRasHyo4',
    ],
}

IMG_DIR = '/data/news/images/0831'
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

def try_download(url, fname):
    """下载并检查尺寸，合格返回 True"""
    try:
        req = urllib.request.Request(url, headers=UA)
        resp = urllib.request.urlopen(req, timeout=20, context=ctx)
        data = resp.read()
        if len(data) < 20000:
            return False, 'too small'
        tmp = os.path.join(IMG_DIR, fname + '.tmp')
        with open(tmp, 'wb') as f:
            f.write(data)
        # PIL 检查尺寸
        from PIL import Image
        im = Image.open(tmp)
        w, h = im.size
        if w < 750 or h > w:
            os.remove(tmp)
            return False, f'{w}x{h}'
        os.rename(tmp, os.path.join(IMG_DIR, fname))
        return True, f'{w}x{h}'
    except Exception as e:
        return False, str(e)[:40]

for idx, urls in candidates.items():
    fname = f'vehicle_hotspots_{idx}.jpg'
    print(f"\n[{idx}] 尝试提取大图 → {fname}")
    for u in urls:
        # 620x0 → 1600x0 拿大图
        big = u.replace('620x0', '1600x0')
        ok, info = try_download(big, fname)
        if ok:
            print(f"  ✅ 成功 {info}: {big[:80]}")
            break
        else:
            print(f"  ❌ {info}: {big[:70]}")
