# -*- coding: utf-8 -*-
"""修正：① 左侧被手机按键遮挡的26px用镜像法补回，重出高清图
        ② 重绘版强调"白色圆形徽"，重出"""
import base64, io, json, os, time, requests
import numpy as np
from PIL import Image, ImageEnhance, ImageFilter
from concurrent.futures import ThreadPoolExecutor

CFG = json.load(open('/data/www/files/LhyjdesignPro/config.json'))
KEY, BASE, MODEL = CFG['api_key'], CFG['base_url'], CFG['models']['image_gen']
D = '/data/www/files/pandaReadArt/convert'

crop = Image.open(os.path.join(D, '00_海报本体_裁切.jpg')).convert('RGB')
W, H = crop.size
PAD = 26
strip = crop.crop((0, 0, PAD, H)).transpose(Image.FLIP_LEFT_RIGHT)
canvas = Image.new('RGB', (W + PAD, H))
canvas.paste(strip, (0, 0))
canvas.paste(crop, (PAD, 0))
# 柔和接缝：接缝两侧 ±8px 线性过渡
a = np.asarray(canvas).astype(float)
x0, x1 = PAD - 8, PAD + 8
left = a[:, x0 - 1, :][:, None, :]
right = a[:, x1, :][:, None, :]
for i, x in enumerate(range(x0, x1 + 1)):
    t = i / (x1 - x0)
    a[:, x, :] = left[:, 0, :] * (1 - t) + right[:, 0, :] * t
canvas = Image.fromarray(a.astype('uint8'))
full_path = os.path.join(D, '00_海报本体_补边.jpg')
canvas.save(full_path, quality=97)
print(f'PAD  {canvas.size}  aspect={canvas.size[0]/canvas.size[1]:.4f}')

w, h = canvas.size
TH = 2480
TW = int(round(w * TH / h))
hd = canvas.resize((TW, TH), Image.LANCZOS)
hd = hd.filter(ImageFilter.UnsharpMask(radius=2.2, percent=105, threshold=3))
hd = ImageEnhance.Color(hd).enhance(1.06)
hd = ImageEnhance.Contrast(hd).enhance(1.05)
hd = ImageEnhance.Sharpness(hd).enhance(1.18)
hd_path = os.path.join(D, '01_高清图_A4_300dpi.jpg')
hd.save(hd_path, quality=95, subsampling=0)
print(f'HD   {hd.size}  {os.path.getsize(hd_path)/1024/1024:.2f}MB')

NOTEXT = (" Absolutely NO TEXT anywhere: no letters, no Chinese characters, no numbers, no calligraphy, no "
          "captions, no titles, no labels, no writing on any plaque, sign, banner, monument or flag, no logos, no "
          "watermarks, no signature, no seals. Every plaque, sign and banner must be blank. ")

KEEP = (" Keep exactly: the thick wavy red ribbon border; the yellow five-pointed star with a red outline in the "
        "bottom-left corner; the red and white swirling clouds along the bottom; the light blue sky with white "
        "clouds and small red stars; the two white doves; the four cartoon child soldiers in blue uniforms with "
        "red collar tabs and caps with red stars marching along a yellow path, the leading boy carrying a large "
        "red flag; the girl with pigtails and the other two boys; the three-arch grey stone bridge over the blue "
        "river; the winding yellow path up the green hill with small red flags planted along it; and the tall "
        "white monument on the hilltop. CRITICAL: on the big red flag the emblem must be a small plain WHITE "
        "ROUND CIRCLE DISC — perfectly round like a circle, NOT a star, not a square — and inside that white "
        "circle draw one small neat yellow hammer and sickle with a straight handle and a clearly curved crescent "
        "blade crossing each other; nothing else inside the circle. The tall white monument must be completely "
        "PLAIN and SMOOTH with no marks, no lines and no writing on it. The thick wavy red ribbon border must be "
        "one clean smooth continuous wave. Leave the upper sky empty. ")

REDRAW = (" Faithfully reproduce this exact children's poster as a clean high-quality version, preserving the same "
          "composition, layout, number of objects and positions. Bold uniform black outlines with flat bright "
          "marker colouring, no shading, no gradients. ") + KEEP + NOTEXT


def call(prompt, size, strength, name, retries=3):
    b64 = base64.b64encode(open(full_path, 'rb').read()).decode()
    for a2 in range(retries):
        try:
            r = requests.post(f"{BASE}/images/generations",
                headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"},
                json={"model": MODEL, "prompt": prompt, "size": size, "n": 1, "watermark": False,
                      "image": f"data:image/jpeg;base64,{b64}", "strength": strength}, timeout=300)
            d = r.json()
            if d.get('data'):
                img = Image.open(io.BytesIO(requests.get(d['data'][0]['url'], timeout=200).content)).convert('RGB')
                p = os.path.join(D, name)
                img.save(p, quality=95, subsampling=0)
                print(f'OK  {name}  s={strength}  {os.path.getsize(p)/1024/1024:.2f}MB', flush=True)
                return p
            print(f'ERR {name} #{a2}: {json.dumps(d, ensure_ascii=False)[:200]}', flush=True)
        except Exception as e:
            print(f'EXC {name} #{a2}: {e}', flush=True)
        time.sleep(6)
    return None


with ThreadPoolExecutor(max_workers=1) as ex:
    print(list(ex.map(lambda j: call(REDRAW, '2400x1700', 0.30, '02_AI重绘高清版.jpg'), [0])))
