#!/usr/bin/env python3.12
# -*- coding: utf-8 -*-
"""批量豆包重生成不合格配图（Phase 3.5）"""
import json, urllib.request, os, re, time

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/0822'
JSON_PATH = '/data/news/json/yes_data/0821data.json'

d = json.load(open(JSON_PATH))

def find_item(section, idx):
    for s in d:
        if s.get('name') == section:
            return s['list'][idx]
    return None

# (板块, idx, 文件名)
targets = [
    ('brand_hotspots', 0, 'brand_hotspots_0.jpg'),
    ('brand_hotspots', 1, 'brand_hotspots_1.jpg'),
    ('brand_hotspots', 2, 'brand_hotspots_2.jpg'),
    ('vehicle_hotspots', 0, 'vehicle_hotspots_0.jpg'),
    ('vehicle_hotspots', 1, 'vehicle_hotspots_1.jpg'),
    ('vehicle_hotspots', 2, 'vehicle_hotspots_2.jpg'),
    ('social_hotspots', 2, 'social_hotspots_2.jpg'),
    ('social_hotspots', 4, 'social_hotspots_4.jpg'),
]

def gen_img(prompt, fname):
    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('豆包未返回图片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())
    return local_path

for section, idx, fname in targets:
    item = find_item(section, idx)
    title = item.get('title', '')
    summary = item.get('summary', '')
    clean_title = re.sub(r'\s*\d[\d,.]*\s*万(?:热度)?\s*$', '', title)
    clean_summary = re.sub(r'(环境异常|验证码|页面加载异常|加载失败)', '', summary)[:60]
    prompt = f'配图：{clean_title}，{clean_summary}，新闻配图风格，写实，横向构图，16:9，高清'
    try:
        local = gen_img(prompt, fname)
        # 验证
        from PIL import Image
        im = Image.open(local)
        sz = os.path.getsize(local)
        print(f'  ✅ {section}[{idx}] {fname} {im.size} {sz//1024}KB')
        # 更新 thumb（确保是本地路径）
        item['thumb'] = f'/images/0822/{fname}'
        json.dump(d, open(JSON_PATH, 'w'), ensure_ascii=False, indent=2)
    except Exception as e:
        print(f'  ❌ {section}[{idx}] {fname} 失败: {e}')
    time.sleep(1)

print('\n✅ 批量重生成完成')
