#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""生成竖版底图（铺满整张海报正文）—— MiniMax image-01"""
import json
import os
import time
import urllib.request

API_KEY = open(os.path.expanduser('~/.config/minimax/music_api_key')).read().strip()
OUT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/对外物料/科研朋友圈_20261009/bg'
os.makedirs(OUT, exist_ok=True)

NEG = ('no animals, no birds, no insects, no people, no hands, no text, no letters, '
       'no words, no watermark, no logo, no signature, not busy')

JOBS = [
    ('bg_热带植物_竖版', '1024x1536',
     'vertical tropical botanical background, lush green monstera and palm leaves framing the edges, '
     'pink orchid and orange bromeliad flowers, soft dreamy bokeh, bright airy high-key light, '
     'painterly watercolor texture, large soft empty space in the center, vertical portrait composition, ' + NEG),
    ('bg_叶影光斑_竖版', '1024x1536',
     'vertical soft botanical background, blurred green leaves and warm sunlight bokeh with subtle pink and '
     'amber petals drifting, dreamy pastel gradient, very soft and airy, large clean empty center, '
     'vertical portrait composition, ' + NEG),
]


def gen(name, size, prompt):
    for attempt in range(1, 4):
        try:
            payload = json.dumps({'model': 'image-01', 'prompt': prompt,
                                  'image_size': size, 'num_images': 1}).encode()
            req = urllib.request.Request(
                'https://api.minimaxi.com/v1/image_generation', data=payload,
                headers={'Authorization': 'Bearer ' + API_KEY, 'Content-Type': 'application/json'},
                method='POST')
            with urllib.request.urlopen(req, timeout=150) as resp:
                d = json.loads(resp.read())
            data = d.get('data')
            url = ''
            if isinstance(data, dict):
                urls = data.get('image_urls') or []
                url = urls[0] if urls else ''
            elif isinstance(data, list) and data:
                url = data[0].get('url') or data[0].get('image_url') or ''
            if not url:
                print('  %s 第%d次空URL base_resp=%s' % (name, attempt, d.get('base_resp')))
                time.sleep(2)
                continue
            p = os.path.join(OUT, name + '.png')
            urllib.request.urlretrieve(url, p)
            print('  ✅ %s  %d KB' % (name, os.path.getsize(p) // 1024))
            return True
        except Exception as e:
            print('  %s 第%d次失败: %s' % (name, attempt, e))
            time.sleep(3)
    print('  ❌ %s 失败' % name)
    return False


if __name__ == '__main__':
    ok = 0
    for n, s, p in JOBS:
        if os.path.exists(os.path.join(OUT, n + '.png')):
            print('  ⏭ %s 已存在' % n); ok += 1; continue
        ok += 1 if gen(n, s, p) else 0
        time.sleep(1)
    print('成功 %d/%d' % (ok, len(JOBS)))
