#!/usr/bin/env python3.12
"""配图修复阶梯①：爬源站原图变体 + 转真 JPEG
用法: python3.12 fetch_variants.py
"""
import io, os, subprocess, sys
from PIL import Image

IMG = '/data/news/images/0926/'
UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126 Safari/537.36'

TARGETS = {
    'vehicle_hotspots_4.jpg': [
        'https://image.bitautoimg.com/appimage-1024-w0/news/2026/09/25/365b7088-7093-4d06-8ffc-a9f61978313c.jpg',
        'https://image.bitautoimg.com/appimage-800-w0/news/2026/09/25/365b7088-7093-4d06-8ffc-a9f61978313c.jpg',
    ],
    'social_hotspots_3.jpg': [
        'https://img.ithome.com/newsuploadfiles/2026/9/7c1c3580-b961-4599-8111-1eff06038dbb.jpg?x-bce-process=image/format,f_auto/resize,m_lfit,w_1200',
        'https://img.ithome.com/newsuploadfiles/2026/9/7c1c3580-b961-4599-8111-1eff06038dbb.jpg?x-bce-process=image/resize,w_1080',
    ],
}
    'vehicle_hotspots_0.jpg': [
        'https://image.bitautoimg.com/appimage-1024-w0/news/2026/09/25/80e6af34-234a-4b08-9e96-00744087000e.jpg',
    ],
    'vehicle_hotspots_1.jpg': [
        'http://img3.autoimg.cn/chejiahaodfs/g33/M07/C3/23/1600x0_1_autohomecar__ChxpVWq14RaAW1VFAAsL2_nKgKk420.png',
        'http://www2.autoimg.cn/chejiahaodfs/g33/M07/C3/23/1600x0_1_autohomecar__ChxpVWq14RaAW1VFAAsL2_nKgKk420.png',
    ],
    'vehicle_hotspots_2.jpg': [
        'http://www2.autoimg.cn/chejiahaodfs/g34/M08/C3/69/1600x0_1_autohomecar__ChtpWGq2Kj6AcEmLAABCbJIyF5M023.jpg',
        'http://img3.autoimg.cn/chejiahaodfs/g34/M08/C3/69/1600x0_1_autohomecar__ChtpWGq2Kj6AcEmLAABCbJIyF5M023.jpg',
    ],
    'vehicle_hotspots_3.jpg': [
        'http://img3.autoimg.cn/chejiahaodfs/g33/M04/C4/58/1600x0_1_autohomecar__Chto52q1_ImAHIO3AAq5govcKLw794.png',
        'http://www2.autoimg.cn/chejiahaodfs/g33/M04/C4/58/1600x0_1_autohomecar__Chto52q1_ImAHIO3AAq5govcKLw794.png',
    ],
    'vehicle_hotspots_4.jpg': [
        'https://image.bitautoimg.com/appimage-1024-w0/news/2026/09/25/365b7088-7093-4d06-8ffc-a9f61978313c.jpg',
    ],
    'social_hotspots_3.jpg': [
        'https://img.ithome.com/newsuploadfiles/2026/9/7c1c3580-b961-4599-8111-1eff06038dbb.jpg',
        'https://img.ithome.com/newsuploadfiles/2026/9/7c1c3580-b961-4599-8111-1eff06038dbb.jpg?x-bce-process=image/format,f_auto',
    ],
    'social_hotspots_4.jpg': [
        'https://inews.gtimg.com/om_ls/O1tvUp4KPPx9seU1A5j408-WPb2jPEpXcG-hFYat9jcZsAA_640330/0',
    ],
}


def fetch(url):
    r = subprocess.run(
        ['curl', '-sSL', '--max-time', '12', '-A', UA, '-e', 'https://www.baidu.com/', url],
        capture_output=True)
    return r.stdout if r.returncode == 0 else None


def save_jpeg(data, out):
    im = Image.open(io.BytesIO(data))
    src = f'{im.format} {im.size[0]}x{im.size[1]}'
    if im.mode in ('RGBA', 'LA', 'P'):
        im = im.convert('RGBA')
        bg = Image.new('RGB', im.size, (255, 255, 255))
        bg.paste(im, mask=im.split()[-1])
        im = bg
    else:
        im = im.convert('RGB')
    if im.width < 600:
        return None, f'{src} → 宽度不足({im.width})'
    if im.width > 750:
        im = im.resize((750, round(im.height * 750 / im.width)), Image.LANCZOS)
    im.save(out, 'JPEG', quality=90)
    return f'{src} → JPEG {im.width}x{im.height} {os.path.getsize(out)//1024}KB', None


for fn, urls in TARGETS.items():
    out = os.path.join(IMG, fn)
    done = False
    for u in urls:
        data = fetch(u)
        if not data or len(data) < 2000:
            print(f'  ⚠️ {fn}: 取回 {len(data) if data else 0}B ← {u[:80]}')
            continue
        try:
            msg, err = save_jpeg(data, out)
        except Exception as e:
            print(f'  ⚠️ {fn}: 解码失败({e}) ← {u[:80]}')
            continue
        if err:
            print(f'  ⚠️ {fn}: {err} ← {u[:80]}')
            continue
        print(f'  ✅ {fn}: {msg}')
        done = True
        break
    if not done:
        print(f'  ❌ {fn}: 所有变体失败 → 需豆包生成')
