#!/usr/bin/python3.12
"""批量豆包重生成不合格配图（2026-08-18）：vehicle 5张 PNG伪装/小尺寸 + brand 3张小尺寸"""
import json, urllib.request, os, re, sys

API_KEY = "ark-563a4210-d804-47fa-a37a-40962192119b-ce6db"
API_URL = "https://ark.cn-beijing.volces.com/api/v3/images/generations"
MODEL = "doubao-seedream-4-0-250828"
IMG_DIR = "/data/news/images/0819/"
YES_DATA = "/data/news/json/yes_data/0818data.json"

# (板块, idx, 标题, 摘要)
targets = [
    ("brand_hotspots", 2, "作为广告公司，我们做产品是认真的", ""),
    ("brand_hotspots", 3, "天猫绿动生活公益短片：垃圾堆不是它们的家", ""),
    ("brand_hotspots", 4, "逛盒马，成了这代年轻人的新生活方式", ""),
    ("vehicle_hotspots", 0, "比亚迪王朝网8系唐将于成都车展亮相 最大纯电续航850km", ""),
    ("vehicle_hotspots", 1, "方程豹成都车展阵容公布 钛9/方程S系列等将亮相", ""),
    ("vehicle_hotspots", 2, "零跑B10/C10正式登陆阿根廷市场 深化品牌南美市场布局", ""),
    ("vehicle_hotspots", 3, "成都车展亮相/或主打20万区间 极狐阿尔法T7将于8月26日开启预售", ""),
    ("vehicle_hotspots", 4, "搭载1.5T插电混动系统！捷途山海L7 PLUS激光雷达版8月19日上市", ""),
]

# 从 yes_data 读取 summary 用于 prompt
d = json.load(open(YES_DATA))
sec_map = {}
for s in d:
    sec_map[s.get('name')] = s.get('list', [])

def clean_title(t):
    t = re.sub(r'\s*\d[\d,.]*\s*万(?:热度)?\s*$', '', t)
    return t.strip()

def gen_and_save(sec, idx, title, summary, fname):
    ct = clean_title(title)
    prompt = f"配图：{ct}，{summary[:60]}，新闻配图风格，写实，横向构图，16:9，高清"
    payload = json.dumps({
        "model": MODEL, "prompt": prompt, "size": "1280x720",
        "n": 1, "response_format": "url"
    }).encode()
    req = urllib.request.Request(API_URL, data=payload,
        headers={'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json'})
    resp = urllib.request.urlopen(req, timeout=120)
    result = json.loads(resp.read().decode('utf-8'))
    img_url = result.get('data', [{}])[0].get('url', '')
    if not img_url:
        raise Exception(f"{sec}[{idx}] 豆包未返回图片URL")
    local_path = os.path.join(IMG_DIR, fname)
    img_req = urllib.request.Request(img_url, headers={'User-Agent': 'Mozilla/5.0'})
    img_resp = urllib.request.urlopen(img_req, timeout=60)
    with open(local_path, 'wb') as f:
        f.write(img_resp.read())
    # 更新 thumb
    for it in sec_map.get(sec, []):
        if it.get('title','').strip() == title:
            it['thumb'] = f'/images/0819/{fname}'
    print(f"✅ {sec}[{idx}] -> {fname} ({os.path.getsize(local_path)//1024}KB)")
    return local_path

for sec, idx, title, summary in targets:
    fname = f"{sec}_{idx}.jpg"
    try:
        gen_and_save(sec, idx, title, summary, fname)
    except Exception as e:
        print(f"❌ {sec}[{idx}] 失败: {e}")

json.dump(d, open(YES_DATA, 'w'), ensure_ascii=False, indent=2)
print("✅ 已保存 yes_data")
