#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""生成海报底部底图候选（彩色大自然，无动物、无文字）—— MiniMax image-01

用途：海报底部扫码板块的底层背景图
要求：颜色丰富 / 无动物 / 无人物 / 无任何文字或水印 / 留白够放白字
"""
import json
import os
import sys
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')

CANDIDATES = [
    ('bg_热带植物', 'lush tropical botanical background, vivid green monstera and palm leaves, '
                 'pink orchid and orange bromeliad flowers, soft dreamy bokeh, bright airy high-key light, '
                 'painterly watercolor texture, clean uncluttered composition with open space, ' + NEG),
    ('bg_山湖晨光', 'colorful nature landscape background, misty mountains and turquoise lake at sunrise, '
                 'vivid pink and orange sky, wildflower meadow in foreground, soft gradient haze, '
                 'painterly illustration style, clean composition with open space, ' + NEG),
    ('bg_抽象叶脉', 'abstract botanical background, translucent overlapping leaves in emerald green, teal, '
                 'pink and amber, soft light rays, gentle gradient, minimal clean design, generous negative space, '
                 + NEG),
]


def gen(name, prompt, size='1536x1024'):
    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=120) as resp:
                d = json.loads(resp.read())
            url = ''
            data = d.get('data')
            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__':
    print('生成 %d 张底图候选 -> %s' % (len(CANDIDATES), OUT))
    good = 0
    for n, p in CANDIDATES:
        if os.path.exists(os.path.join(OUT, n + '.png')):
            print('  ⏭ %s 已存在，跳过' % n)
            good += 1
            continue
        good += 1 if gen(n, p) else 0
        time.sleep(1)
    print('\n成功 %d/%d' % (good, len(CANDIDATES)))
    sys.exit(0 if good else 1)
