#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""智谱 CogView-4 重出 5 张案例插画（v2）：
· 强化「绝对无文字」与「纯抽象几何、无人物」
· 要求四周宽留白、主体居中于画面中间 70%
  —— 为后续统一裁掉服务端强制水印（右下角「AI生成」）预留安全边距
原始 PNG 存 _img_price_deck/ai_<name>.png
"""
import io
import json
import os
import re
import time
import urllib.request

CFG = os.path.expanduser('~/.hermes/profiles/zone-a/config.yaml')
BASE = 'https://open.bigmodel.cn/api/paas/v4/images/generations'
OUT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/培训与上手/培训/_img_price_deck'
os.makedirs(OUT, exist_ok=True)


def zhipu_key():
    lines = io.open(CFG, encoding='utf-8').read().splitlines()
    for i, l in enumerate(lines):
        if re.match(r'^\s*zhipu\s*:\s*$', l):
            for j in range(i, min(i + 8, len(lines))):
                m = re.match(r'^\s*api_key\s*:\s*[\'"]?([^\'"\s]+)', lines[j])
                if m:
                    return m.group(1)
    raise SystemExit('未找到 zhipu api_key')


KEY = zhipu_key()

PAL = ('Strict limited color palette: deep corporate blue #1F4E9C dominant, '
       'electric ultramarine #002FA7 as small accents, off-white #FAFAF8 background, '
       'thin crisp flat 2D vector linework, no gradients, no 3D gloss')
TXT = ('The image must contain absolutely no text of any kind: no letters, no words, '
       'no digits, no numbers, no hashtags, no captions, no labels, no annotations, '
       'no signature, no scribbles, no written characters anywhere')
ABS = ('pure abstract geometric shapes only: no human beings, no people, no men, '
       'no figures, no faces, no bodies, no hands, no animals')
MRG = ('Centered symmetric composition with wide clean empty margins on all four '
       'sides; keep every important element well inside the middle 70 percent of '
       'the frame')

PROMPTS = [
    ('scene_tug',
     'Flat vector business concept illustration, Swiss international minimalist poster. '
     'An abstract negotiation scene: a long horizontal rectangular table in the middle, '
     'and on the left and right two opposing abstract geometric clusters made only of '
     'plain rectangles and squares pulling a taut rope in a tug of war across the table, '
     'with bold clean tension lines. ' + ABS + '. ' + PAL + ', flat 2D. ' + MRG + '. '
     + TXT + '.'),

    ('scene_weigh',
     'Flat vector business concept illustration, Swiss international minimalist poster. '
     'An abstract weighing-one-option-against-another scene: a simple balance scale with '
     'two pans, the left pan holding a stack of plain geometric blocks and the right pan '
     'holding a different smaller stack, the beam tipping slightly to one side; below, a '
     'dashed branching arrow splitting left and right. ' + ABS + '. ' + PAL + ', flat 2D, '
     'thin clean lines. ' + MRG + '. ' + TXT + '.'),

    ('scene_deal',
     'Flat vector business concept illustration, Swiss international minimalist poster. '
     'At the exact center of the frame, two very simple flat geometric hand silhouettes '
     'clasped in a handshake, clean minimal shapes with exactly five simple fingers each, '
     'no facial features and no people anywhere else in the image, surrounded by a few '
     'clean converging lines and a small upward arrow. ' + PAL + ', flat 2D vector, thin '
     'clean lines. ' + MRG + '. ' + TXT + '.'),

    ('scene_price',
     'Flat vector business concept illustration, Swiss international minimalist poster. '
     'An abstract too-expensive concept: one oversized completely blank paper price tag '
     'shape with a diagonal rejection slash, beside neat stacks of plain geometric coin '
     'discs, and a simple seesaw beam tipping between a coin and a product cube with a '
     'bold downward arrow. The tag is completely blank and empty. ' + ABS + '. ' + PAL +
     ', flat 2D vector, thin clean lines. ' + MRG + '. ' + TXT + '.'),

    ('jobs_cart',
     'Flat vector business concept illustration, Swiss international minimalist poster. '
     'An abstract metaphor of progress: on the left a simple flat geometric wheeled '
     'carriage made of circles and rectangles with no animal and no horse, in the middle '
     'a bold horizontal arrow, on the right a sleek simple flat geometric motor car '
     'silhouette; expressing the shift from a faster horse to the motor car. ' + ABS +
     '. ' + PAL + ', flat 2D vector, thin clean lines. ' + MRG + '. ' + TXT + '.'),
]

MODEL = 'cogview-4-250304'
SIZE = '1536x1024'


def gen(name, prompt):
    png = os.path.join(OUT, 'ai_' + name + '.png')
    for attempt in (1, 2, 3):
        try:
            body = json.dumps({'model': MODEL, 'prompt': prompt, 'size': SIZE,
                               'watermark_enabled': False}).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:
                d = json.loads(r.read())
            url = (d.get('data') or [{}])[0].get('url')
            if not url:
                print('    %s 第%d次 空URL %s' % (name, attempt,
                                                 json.dumps(d, ensure_ascii=False)[:200]))
                time.sleep(3)
                continue
            urllib.request.urlretrieve(url, png)
            print('  %-12s ✅ %s @ %s  %dKB' % (name, MODEL, SIZE,
                                                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)[:160]))
        time.sleep(3)
    print('  %-12s ❌ 失败' % name)
    return False


if __name__ == '__main__':
    print('CogView-4 重出 →', OUT)
    ok = sum(1 for n, p in PROMPTS if gen(n, p))
    print('完成 %d/%d' % (ok, len(PROMPTS)))
