#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""智谱 CogView 文生图探针：验证 zone-a 的 zhipu key 与端点是否可用（最小成本档）。
key 只在本脚本内读取使用，不打印、不落盘。
"""
import io
import json
import os
import re
import sys
import urllib.request

CFG = os.path.expanduser('~/.hermes/profiles/zone-a/config.yaml')
BASE = 'https://open.bigmodel.cn/api/paas/v4/images/generations'


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) or re.match(r'^\s*provider\s*:\s*zhipu\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 and m.group(1) not in ('', "''", '""'):
                    return m.group(1)
    return None


KEY = zhipu_key()
if not KEY:
    print('❌ 未能在 zone-a config 中找到 zhipu api_key')
    sys.exit(1)
print('key 已读取：len=%d，形如 %s…（不打印全文）' % (len(KEY), KEY[:6]))


def call(model, size, prompt):
    body = json.dumps({'model': model, 'prompt': prompt, 'size': size}).encode()
    req = urllib.request.Request(BASE, data=body, method='POST', headers={
        'Authorization': 'Bearer ' + KEY, 'Content-Type': 'application/json'})
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            return r.status, json.loads(r.read())
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode('utf-8', 'replace')[:500]
    except Exception as e:
        return -1, str(e)[:300]


for model, size in (('cogview-3-flash', '1024x1024'),
                    ('cogview-4-250304', '1024x1024'),
                    ('glm-image', '1280x1280')):
    st, resp = call(model, size, 'a flat vector blue circle on a plain white background, '
                                 'minimal geometric, no text, no letters')
    ok = isinstance(resp, dict) and resp.get('data') and resp['data'][0].get('url')
    print('\n— %s @ %s → HTTP %s  %s' % (model, size, st, '✅ 出图' if ok else '❌'))
    if ok:
        print('   url 前缀:', resp['data'][0]['url'][:70])
        print('   task_status:', resp.get('task_status'), '| created:', resp.get('created'))
    else:
        print('   ', json.dumps(resp, ensure_ascii=False)[:400] if isinstance(resp, dict)
              else resp)
    if ok:
        print('\n可用模型 =', model)
        break
