# -*- coding: utf-8 -*-
"""校园 5 份：由插画反推线条图 + 合成 A4 横版（无标题带，仅右下角一行作品名）"""
import base64, glob, json, os, time, requests
from concurrent.futures import ThreadPoolExecutor
from PIL import Image, ImageDraw, ImageFont

CFG = json.load(open('/data/www/files/LhyjdesignPro/config.json'))
API_KEY, BASE, MODEL = CFG['api_key'], CFG['base_url'], CFG['models']['image_gen']
ROOT = '/data/www/files/waterHealthArt/campus'
SRC = os.path.join(ROOT, 'illustration')
LIN = os.path.join(ROOT, 'lineart')
os.makedirs(LIN, exist_ok=True)

LINE_INSTR = ("Convert this watercolour illustration into a PURE BLACK-AND-WHITE LINE DRAWING for children to trace "
              "and colour. Keep EXACTLY the same shapes, positions, proportions, element count and composition — do "
              "not add, remove, move or redraw anything. Keep the outlines confident and hand-drawn with clearly "
              "VARIED stroke thickness and some broken, dry-brush line ends. Remove ALL colour, ALL shading, ALL grey "
              "tones, ALL watercolour texture, ALL paper grain and ALL soft gradients — uniform clean black outlines "
              "on a pure white background, every enclosed area pure white. NO cross-hatching, NO stippling, NO tonal "
              "patches, NO grey fill. Keep the drawn finger lines on the hands. NO text anywhere: no letters, no "
              "numbers, no characters, no labels, no signature, no watermark. ")


def reline(path, strength=0.6):
    name = os.path.basename(path)
    b64 = base64.b64encode(open(path, 'rb').read()).decode()
    for a in range(3):
        try:
            r = requests.post(f"{BASE}/images/generations",
                headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
                json={"model": MODEL, "prompt": LINE_INSTR, "size": "2896x2048", "n": 1, "watermark": False,
                      "image": f"data:image/jpeg;base64,{b64}", "strength": strength}, timeout=300)
            d = r.json()
            if d.get('data'):
                img = requests.get(d['data'][0]['url'], timeout=180).content
                p = os.path.join(LIN, name)
                open(p, 'wb').write(img)
                print(f"LINE OK  {name}  {len(img)//1024}KB", flush=True)
                return p
            print(f"LINE ERR {name} #{a}: {json.dumps(d, ensure_ascii=False)[:180]}", flush=True)
        except Exception as e:
            print(f"LINE EXC {name} #{a}: {e}", flush=True)
        time.sleep(6)
    return None


W, H = 3508, 2480
GREY = (110, 110, 110)
F_SUB = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc'
SUB = {
 '1_体育课后的第一杯水': '作品一《体育课后的第一杯水》',
 '2_食堂门口的一杯温开水': '作品二《食堂门口的一杯温开水》',
 '3_科学课_烧开的水才安全': '作品三《科学课·烧开的水才安全》',
 '4_班级饮水角的值日生': '作品四《班级饮水角的值日生》',
 '5_放学路上_水壶在我书包里': '作品五《放学路上，水壶在我书包里》',
}
MARGIN, ART_W = 120, 3508 - 240
ART_H = int(ART_W / 1.4141)


def sheet(src, dst):
    art = Image.open(src).convert('RGB').resize((ART_W, ART_H), Image.LANCZOS)
    page = Image.new('RGB', (W, H), (255, 255, 255))
    page.paste(art, (MARGIN, 24))
    d = ImageDraw.Draw(page)
    d.text((W - MARGIN, H - 34), SUB[os.path.basename(src).rsplit('.', 1)[0]],
           font=ImageFont.truetype(F_SUB, 46, index=0), fill=GREY, anchor='rs')
    page.save(dst, quality=95, subsampling=0, dpi=(300, 300))


if __name__ == '__main__':
    files = sorted(glob.glob(os.path.join(SRC, '*.jpg')))
    with ThreadPoolExecutor(max_workers=5) as ex:
        list(ex.map(reline, files))

    for kind, label in (('illustration', '配色图'), ('lineart', '线条图')):
        outdir = os.path.join(ROOT, 'A4横版', label)
        os.makedirs(outdir, exist_ok=True)
        for src in sorted(glob.glob(os.path.join(ROOT, kind, '*.jpg'))):
            dst = os.path.join(outdir, os.path.basename(src))
            sheet(src, dst)
            print(f"{label}  {os.path.basename(dst):26s} {os.path.getsize(dst)/1024/1024:.2f}MB  {W}x{H}", flush=True)
        imgs = [Image.open(f).convert('RGB') for f in sorted(glob.glob(os.path.join(outdir, '*.jpg')))]
        pdf = os.path.join(ROOT, 'A4横版', f'{label}_5份_A4横版.pdf')
        imgs[0].save(pdf, save_all=True, append_images=imgs[1:], resolution=300.0)
        print(f"PDF  {os.path.basename(pdf)}  {len(imgs)}页  {os.path.getsize(pdf)/1024/1024:.2f}MB", flush=True)
