#!/usr/bin/env python3.12
"""0911 图片修复：0字节PNG恢复 + 竖向/小图豆包重生成（2026-09-10）"""
import json, re, urllib.request, os, time
from PIL import Image

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"

YES = "/data/news/json/yes_data/0910data.json"
IMG_DIR = "/data/news/images/0911"


def recover_png(fname):
    """0字节jpg → 用同名 .jpg.png 备份转 JPEG"""
    jpg = os.path.join(IMG_DIR, fname)
    png = jpg + ".png"
    if not os.path.exists(png):
        print(f"  ⚠️ 无PNG备份: {fname}")
        return False
    im = Image.open(png).convert("RGB")
    im.save(jpg, "JPEG", quality=88)
    print(f"  ✅ {fname} 从PNG恢复 {im.size} {os.path.getsize(jpg)}B")
    return True


def gen_image(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=90)
    with open(local_path, 'wb') as f:
        f.write(img_resp.read())
    return local_path


TARGETS = [
    # (板块, index, 文件名, 自定义prompt 或 None)
    ('social_hotspots', 3, 'social_hotspots_3.jpg',
     '配图：中国科技企业加大底层技术自主研发投入，研发中心与芯片设计场景，无人物，新闻配图风格，写实，横向构图，高清'),
    ('social_hotspots', 4, 'social_hotspots_4.jpg',
     '配图：AI智能眼镜新品发布，支持虹膜识别，无显示屏，科技产品展示场景，新闻配图风格，写实，横向构图，高清'),
]

d = json.load(open(YES))

# 1) 0字节恢复
print("=== 1. 0字节PNG恢复 ===", flush=True)
for name, idx, fname, _ in [('vehicle_hotspots', 0, 'vehicle_hotspots_0.jpg', None),
                            ('vehicle_hotspots', 1, 'vehicle_hotspots_1.jpg', None),
                            ('vehicle_hotspots', 2, 'vehicle_hotspots_2.jpg', None)]:
    recover_png(fname)

# 2) 豆包重生成
print("=== 2. 豆包重生成 ===", flush=True)
for name, idx, fname, custom in TARGETS:
    for s in d:
        if s.get('name') == name:
            it = s['list'][idx]
            if custom:
                prompt = custom
            else:
                t = re.sub(r'\s*\d[\d,.]*\s*万(?:热度)?\s*$', '', it.get('title', ''))
                sm = it.get('summary', '') or ''
                prompt = f"配图：{t}，{sm[:60]}，新闻配图风格，写实，横向构图，高清"
                prompt = prompt.replace('“', '').replace('”', '').replace('"', '')
            print(f"[{name}][{idx}] {fname} -> {prompt[:60]}...", flush=True)
            try:
                path = gen_image(prompt, fname)
                im = Image.open(path)
                print(f"  OK {path} ({os.path.getsize(path)}B) {im.size}", flush=True)
                it['thumb'] = f'/images/0911/{fname}'
            except Exception as e:
                print(f"  FAIL {e}", flush=True)
            time.sleep(1)

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