# -*- coding: utf-8 -*-
"""最终流程：精确裁切 → A4/300dpi高清图 → AI重绘高清版 → 线条图(+空心标题)"""
import base64, io, json, os, re, time, requests
from PIL import Image, ImageEnhance, ImageFilter, ImageDraw, ImageFont
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']
SRC = '/root/.hermes/webui/attachments/d7fb35486610/screenshot-1789268930955.jpeg'
D = '/data/www/files/pandaReadArt/convert'
os.makedirs(D, exist_ok=True)
FONT = '/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc'
TITLE = '长征胜利90周年'

# ---------- ① 精确裁切：去掉左侧手机导航键(0-24)与底部桌面条(y>=815) ----------
im = Image.open(SRC).convert('RGB')
crop = im.crop((26, 0, 1148, 814))
crop_path = os.path.join(D, '00_海报本体_裁切.jpg')
crop.save(crop_path, quality=97)
print(f'CROP {crop.size} aspect={crop.size[0]/crop.size[1]:.4f}')

# ---------- ② 高清图：按 A4 高度 300dpi 放大 + 增强 ----------
w, h = crop.size
TH = 2480
TW = int(round(w * TH / h))
hd = crop.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: the flag's white circular emblem must contain a clean "
        "symmetrical hammer and sickle — a hammer with a straight handle and a sickle with a clearly curved "
        "crescent blade crossing each other, nothing else inside the circle, no extra star. 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

LINE = (" Convert this exact poster into a pure black-and-white LINE DRAWING for a children's colouring template. "
        "Keep EXACTLY the same shapes, positions, proportions, number of objects and composition — do not add, "
        "remove, move or redraw anything. Uniform bold black outlines only on a pure white background: no colour, "
        "no grey tones, no shading, no cross-hatching, no stippling, no gradients, no filled dark areas — every "
        "region left pure white with clean closed outlines. Draw the ribbon border, the bottom clouds and the "
        "corner star as simple black outlines too. ") + KEEP + NOTEXT


def call(prompt, size, strength, name, retries=3):
    b64 = base64.b64encode(open(crop_path, 'rb').read()).decode()
    for a 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} #{a}: {json.dumps(d, ensure_ascii=False)[:200]}', flush=True)
        except Exception as e:
            print(f'EXC {name} #{a}: {e}', flush=True)
        time.sleep(6)
    return None


def add_hollow_title(path, title=TITLE):
    """线稿叠加空心标题（描边字，便于孩子涂色）"""
    im = Image.open(path).convert('RGB')
    W, H = im.size
    d = ImageDraw.Draw(im)
    base = int(H * 0.082)
    segs = re.findall(r'\d+|\D+', title)
    fonts, widths = [], []
    for s in segs:
        sz = int(base * 1.45) if s.isdigit() else base
        f = ImageFont.truetype(FONT, sz)
        bb = d.textbbox((0, 0), s, font=f, anchor='ls')
        fonts.append(f); widths.append(bb[2] - bb[0])
    gap = int(base * 0.06)
    total = sum(widths) + gap * (len(segs) - 1)
    x = (W - total) / 2
    y = int(H * 0.145)
    for s, f, wd in zip(segs, fonts, widths):
        d.text((x, y), s, font=f, fill=(255, 255, 255), anchor='ls',
               stroke_width=max(3, base // 12), stroke_fill=(20, 20, 20))
        x += wd + gap
    im.save(path, quality=95, subsampling=0)
    print(f'TITLE {os.path.basename(path)}')


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=2) as ex:
        ex.map(lambda j: call(j[1], '2400x1700', j[2], j[3]),
               [('redraw', REDRAW, 0.30, '02_AI重绘高清版.jpg'),
                ('line', LINE, 0.60, '03_线条图.jpg')])
    add_hollow_title(os.path.join(D, '03_线条图.jpg'))
    print('DONE')
