#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 S7-2 老僧人面孔小肖像（wb 箱 id=196）
- 只此一张小图，程序层用，非 12 镜底图重开
- 免费档 Pollinations flux t2i（nologo=True，不烧 pollen、不碰 ImageGen 积分、不充值）
- 2 个候选：A 正面 / B 微侧，同风格不同 seed
- 出 768x1024 后 LANCZOS 归一到 756x1008（252:336 = 3:4）
- 纪律：首镜 402 立即停手，不重试、不换通道、不充值
"""
import importlib.util, json, os, sys, time, traceback

HERE = os.path.dirname(os.path.abspath(__file__))
SKILL_PY = r"C:\Users\ngmk\.workbuddy\skills\local-imagegen\scripts\pollinations_gen.py"
spec = importlib.util.spec_from_file_location("polgen", SKILL_PY)
pol = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pol)

from PIL import Image

OUT_DIR = os.path.join(HERE, "_s72_work")
os.makedirs(OUT_DIR, exist_ok=True)

STYLE = (
    "Chinese ink and watercolor picture-book illustration, in the gentle refined manner of "
    "Cai Gao's classic Chinese picture books: fine crisp pen linework combined with "
    "transparent layered watercolor washes on warm ivory textured paper, muted earthy palette "
    "of warm beige, soft sepia, pale ochre and gentle grey ink, soft wet bleeding edges, "
    "restrained and quiet, large areas of clean pale empty paper. "
)

SUBJECT_A = (
    "ONE single head-and-shoulders portrait of a VERY OLD Ming-dynasty Buddhist monk, "
    "over ninety years of age: completely bald clean-shaven head with a few faint small "
    "incense-burn scar dots on the crown, deeply lined wrinkled face, drooping long white "
    "eyebrows, thin sparse white stubble beard, hollow sunken cheeks, prominent cheekbones, "
    "heavy drooping eyelids, calm weary downcast eyes, visible age spots, "
    "wearing a plain faded grey-brown kasaya monk robe draped diagonally over one shoulder. "
    "Unmistakably a humble aged Buddhist monk. Absolutely NOT a young man, NOT an emperor, "
    "NOT a prince, NOT a noble, NOT the Jianwen Emperor: no crown, no hat, no hair, "
    "no imperial dragon robe, no official cap, no jade belt, no jewelry, no throne. "
    "Front-facing straight-on symmetrical portrait, head centered, face and shoulders filling "
    "about 60 percent of the frame height, gentle soft light from upper left. "
)

SUBJECT_B = (
    "ONE single head-and-shoulders portrait of a VERY OLD Ming-dynasty Buddhist monk, "
    "over ninety years of age: completely bald shaven scalp with a few faint incense scar dots, "
    "a face mapped with deep wrinkles, long drooping white eyebrows, sparse white whiskers, "
    "gaunt hollow cheeks, heavy-lidded tired eyes gazing slightly downward, thin folded lips, "
    "a simple worn faded ochre-grey kasaya monk robe with a visible diagonal shoulder drape. "
    "Unmistakably a humble aged Buddhist monk, NOT a young man, NOT an emperor, "
    "NOT a prince, NOT the Jianwen Emperor: no crown, no hat, no hair, no dragon robe, "
    "no official cap, no jewelry, no throne. Slight three-quarter view, face turned just a "
    "little to the viewer's left, head centered, face and shoulders filling about 60 percent "
    "of the frame height, gentle soft light from upper left. "
)

BG = (
    "Plain clean warm ivory paper background, completely blank and empty behind the figure, "
    "the watercolor edges of the portrait fading softly into the blank paper at all four sides, "
    "no frame, no border, no rectangle, no panel, no scenery, no landscape, no buildings, "
    "no other people, no props, no objects. "
)

NEG = (
    "ABSOLUTELY no text, no words, no Chinese characters, no letters, no numbers, no digits, "
    "no caption, no seal, no red stamp, no watermark, no logo, no signature, no calligraphy. "
    "Not a photograph, not photorealistic, not 3D render, not CGI, not oil painting, "
    "not anime, not cartoon, not a historical portrait copy, not based on any real person "
    "or any existing painting, no extra limbs, no deformed face, no extra heads."
)

CANDS = [
    ("A", SUBJECT_A, 7301, "正面，seed7301"),
    ("B", SUBJECT_B, 7302, "微侧，seed7302"),
]


def main():
    results = []
    for tag, subj, seed, note in CANDS:
        prompt = STYLE + subj + BG + NEG
        raw = os.path.join(OUT_DIR, "ep03_s72_monk_%s_raw.png" % tag)
        final = os.path.join(OUT_DIR, "ep03_s72_monk_%s.png" % tag)
        t0 = time.time()
        try:
            out, size = pol.t2i(prompt, model="flux", width=768, height=1024,
                                seed=seed, nologo=True, out=raw, timeout=300)
            print("GEN %s OK bytes=%d %.1fs" % (tag, size, time.time() - t0), flush=True)
        except Exception as e:
            msg = str(e)
            print("GEN %s FAIL %s" % (tag, msg), flush=True)
            results.append({"tag": tag, "ok": False, "err": msg, "note": note})
            # 402/计费类错误立即停手，不重试不换通道
            if "402" in msg or "pollen" in msg.lower() or "payment" in msg.lower():
                print("STOP: 计费/余额问题，按纪律停手", flush=True)
                break
            continue
        im = Image.open(raw).convert("RGB")
        w0, h0 = im.size
        im2 = im.resize((756, 1008), Image.LANCZOS)
        im2.save(final, "PNG", optimize=True)
        results.append({"tag": tag, "ok": True, "note": note, "seed": seed,
                        "raw": w0, "rawh": h0, "raw_bytes": size,
                        "final_bytes": os.path.getsize(final),
                        "prompt": prompt})
        print("OUT %s %dx%d -> 756x1008 bytes=%d" % (tag, w0, h0, os.path.getsize(final)), flush=True)
    with open(os.path.join(OUT_DIR, "gen_report.json"), "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=2)
    print("DONE", json.dumps([{k: r[k] for k in ("tag", "ok")} for r in results]), flush=True)


if __name__ == "__main__":
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass
    main()
