#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""MiniMax image-01 生成 5 张案例场景插画（生成阶段脚本，不写入成品页）。
色板：宝锐蓝为主 + 深蓝点缀；无文字、无真人肖像、纯几何抽象。
原始 PNG 存 _img_price_deck/mm_<name>.png

prompt 纪律（来自上一轮 CogView 的实测教训，同样适用于任何 T2I）：
  · 绝不写 #hex 色号 —— 会被模型当文字画出来
  · 不做否定词堆砌（no text/no logo 反而诱导涂鸦）；改用「纯色空白背景 + 大量留白」正向描述
  · 要求四周留白，便于后处理裁掉服务端水印
"""
import io
import json
import os
import re
import time
import urllib.request

ENV = os.path.expanduser('~/.hermes/.env')
BASE = 'https://api.minimaxi.com/v1/image_generation'
OUT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/培训与上手/培训/_img_price_deck'
os.makedirs(OUT, exist_ok=True)


def minimax_key():
    txt = io.open(ENV, encoding='utf-8').read()
    m = re.search(r'^MINIMAX_CN_API_KEY=(.*)$', txt, re.M)
    if m and m.group(1).strip():
        return m.group(1).strip()
    return io.open(os.path.expanduser('~/.config/minimax/music_api_key')).read().strip()


KEY = minimax_key()

BG = ('A plain uniform empty warm off-white background with wide empty margins on '
      'every side')
STYLE = ('Only flat deep blue shapes with thin dark outlines, flat 2D vector, no '
         'shading, no gradient, clean and simple')
TAIL = 'The picture is clean and simple and contains nothing else.'

PROMPTS = [
    ('scene_tug',
     'Minimalist flat vector business concept illustration. ' + BG + '. In the middle a '
     'long simple rectangular table; on the left one plain deep blue rectangular block '
     'leaning to the right, on the right one plain deep blue rectangular block leaning to '
     'the left; a thick taut rope runs horizontally across the table between them, with a '
     'few thin tension lines. ' + STYLE + '. ' + TAIL),

    ('scene_weigh',
     'Minimalist flat vector business concept illustration. ' + BG + '. A simple balance '
     'scale with a slim central post and two hanging flat pans; the left pan holds one '
     'large plain blue cube, the right pan holds two small plain blue cubes, and the beam '
     'tilts down towards the left side. ' + STYLE + '. ' + TAIL),

    ('scene_deal',
     'Minimalist flat vector business concept illustration. ' + BG + '. At the centre two '
     'very simple flat blue hands clasped together in a handshake, seen from the side, '
     'each hand with five simple fingers and a clear thumb, clean minimal shapes, no '
     'faces. ' + STYLE + '. ' + TAIL),

    ('scene_price',
     'Minimalist flat vector business concept illustration. ' + BG + '. A large plain '
     'blank paper tag shape tilted slightly with a thick diagonal line crossing it, a '
     'small neat stack of plain blue discs beside it, and below a simple seesaw beam with '
     'a blue disc on its left end and a plain cube on its right end. The tag surface is '
     'completely plain and empty. ' + STYLE + '. ' + TAIL),

    ('jobs_cart',
     'Minimalist flat vector business concept illustration. ' + BG + '. On the left a '
     'simple flat blue carriage with two round wheels, in the middle a bold horizontal '
     'arrow, on the right a simple flat blue motor car with two round wheels. '
     + STYLE + '. ' + TAIL),
]

SIZE = '1536x1024'


def call(prompt, size=SIZE):
    body = json.dumps({'model': 'image-01', 'prompt': prompt, 'image_size': size,
                       'num_images': 1}).encode()
    req = urllib.request.Request(BASE, data=body, method='POST', headers={
        'Authorization': 'Bearer ' + KEY, 'Content-Type': 'application/json'})
    with urllib.request.urlopen(req, timeout=180) as r:
        return json.loads(r.read())


def gen(name, prompt):
    png = os.path.join(OUT, 'mm_%s.png' % name)
    for attempt in (1, 2, 3):
        try:
            d = call(prompt)
            br = d.get('base_resp', {})
            if br.get('status_code') not in (0, None):
                print('    %s 接口错误 %s' % (name, br))
            url = (d.get('data') or {}).get('image_urls', [''])[0] \
                if isinstance(d.get('data'), dict) else ''
            if not url:
                time.sleep(3)
                continue
            urllib.request.urlretrieve(url, png)
            print('  %-12s ✅ %dKB' % (name, os.path.getsize(png) // 1024))
            return True
        except urllib.error.HTTPError as e:
            print('    %s HTTP %s %s' % (name, e.code, e.read().decode('utf-8', 'replace')[:200]))
        except Exception as e:
            print('    %s ERR %s' % (name, str(e)[:140]))
        time.sleep(3)
    print('  %-12s ❌ 失败' % name)
    return False


if __name__ == '__main__':
    import sys
    if '--probe' in sys.argv:
        d = call('a plain blue circle on a white background', '1024x1024')
        print('probe base_resp:', d.get('base_resp'))
        u = (d.get('data') or {}).get('image_urls', [''])
        print('probe url:', bool(u and u[0]))
        sys.exit(0)
    print('MiniMax image-01 →', OUT)
    print('完成 %d/%d' % (sum(1 for n, p in PROMPTS if gen(n, p)), len(PROMPTS)))
