#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 S7-2 老僧肖像 v4（提示词工程修正）
根因：v2/v3 在 prompt 里写满 "NO beard / NO moustache / NO red seal / NO calligraphy"
等否定名词，等于反复把「胡须 / 印章 / 书法」概念喂给模型 —— 结果微侧三张全留长白须、
几乎每张都自带红印。这与 EP03 07 镜「prompt 里出现日历二字就画出日历」是同一个坑。
v4 修正：
  - 彻底删除所有「须/胡/印章/文字」相关词（含否定式），改用纯正面描述：
    「smooth lean shaved face, smooth bare chin」「corners are untouched blank paper」
  - 印章/文字一律交给程序化 clean_marks 兜底（v3 已验证清得干净）
  - 保留 E 的成功配方（正面、暖米纸、淡彩水墨、细线、灰褐袈裟）
  - 抽 4 张不同 seed 的正面/微侧，人眼挑 1~2 张与 cand1 配成 2 候选
通道：Pollinations 免费档 flux，nologo=True，不烧 pollen、不碰 ImageGen 积分、不充值
"""
import importlib.util, json, os, sys, time

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
import numpy as np
import cv2

OUT_DIR = os.path.join(HERE, "_s72_work")
V3 = importlib.util.spec_from_file_location("v3mod", os.path.join(HERE, "ep03_s72_monk_gen_v3.py"))
v3 = importlib.util.module_from_spec(V3)
V3.loader.exec_module(v3)
clean_marks = v3.clean_marks

STYLE = (
    "Traditional Chinese freehand ink-and-watercolor picture-book illustration in the warm "
    "gentle manner of Cai Gao's classic Chinese picture books: soft translucent layered "
    "watercolor washes with gentle wet bleeding edges on warm ivory textured paper, "
    "muted earthy palette of warm beige, soft sepia, pale ochre and pale grey ink, "
    "very fine delicate light brown-grey ink lines only, matte handmade paper grain visible, "
    "quiet restrained and tender, large clean pale empty paper around the subject. "
    "A standalone character study on blank paper; the four corners are untouched blank "
    "paper, completely empty and clean. "
)

# 正面描述「干净的脸」，不出现任何「须/胡/beard/moustache」字样
FACE = (
    "ONE single head-and-shoulders portrait of a VERY OLD Ming-dynasty Buddhist MONK, "
    "more than ninety years old: a completely bald smooth shaved scalp with three tiny "
    "faint incense-burn scar dots, a lean smooth-shaven face with a smooth bare chin and "
    "a smooth upper lip, deeply lined with fine wrinkles, long drooping white eyebrows, "
    "heavy drooping eyelids over calm weary downcast eyes, hollow sunken cheeks, "
    "prominent cheekbones, thin closed lips, a few faint age spots. "
    "He wears a plain faded pale ochre-grey Buddhist kasaya monk robe with a simple "
    "diagonal drape across one shoulder and a soft round collar. "
    "Unmistakably a humble aged Buddhist monk: the bald shaved head and the monk robe "
    "are the two clear identifiers. He is a poor wandering monk, humble and weathered, "
    "with a gentle tired expression. "
)

FRONT = (
    "Front-facing straight-on symmetrical portrait, head centered, head and shoulders "
    "filling about 65 percent of the frame height, gentle soft light from upper left. "
)
SIDE = (
    "Slight three-quarter view with the face turned just a little to the viewer's left, "
    "head centered, head and shoulders filling about 65 percent of the frame height, "
    "gentle soft light from upper left. "
)

BG = (
    "The background is completely plain clean warm ivory paper, entirely blank and empty "
    "behind and around the figure; the soft watercolor edges of the portrait fade gently "
    "into the blank paper. No frame, no border, no panel, no scenery, no landscape, "
    "no buildings, no other people, no props, no floating objects. "
    "Only the monk's portrait and blank clean paper exist in this image. "
    "Illustration, not a photograph, not 3D render, not anime, not a comic, "
    "not a historical portrait copy, not based on any real person, "
    "no extra limbs, no deformed face, no duplicate figures."
)

VARIANTS = [
    ("J", FRONT, 7411),
    ("K", FRONT, 7421),
    ("L", SIDE,  7431),
    ("M", SIDE,  7441),
]


def main():
    report = []
    for tag, pose_prompt, seed in VARIANTS:
        prompt = STYLE + FACE + pose_prompt + BG
        raw = os.path.join(OUT_DIR, "ep03_s72_monk_%s_raw.png" % tag)
        tmp = os.path.join(OUT_DIR, "_%s_norm.png" % tag)
        out = os.path.join(OUT_DIR, "ep03_s72_monk_%s_clean.png" % tag)
        t0 = time.time()
        try:
            pol.t2i(prompt, model="flux", width=768, height=1024,
                    seed=seed, nologo=True, out=raw, timeout=300)
        except Exception as e:
            msg = str(e)
            print("GEN %s FAIL %s" % (tag, msg), flush=True)
            report.append({"tag": tag, "ok": False, "err": msg})
            if "402" in msg or "pollen" in msg.lower() or "payment" in msg.lower():
                print("STOP: 计费/余额问题，按纪律停手", flush=True)
                break
            continue
        Image.open(raw).convert("RGB").resize((756, 1008), Image.LANCZOS).save(tmp)
        n = clean_marks(tmp, out)
        print("GEN %s OK blocks=%d bytes=%d %.1fs" %
              (tag, n, os.path.getsize(out), time.time() - t0), flush=True)
        report.append({"tag": tag, "ok": True, "seed": seed,
                       "pose": "正面" if pose_prompt is FRONT else "微侧",
                       "cleaned_blocks": n, "bytes": os.path.getsize(out), "prompt": prompt})
    with open(os.path.join(OUT_DIR, "gen_report_v4.json"), "w", encoding="utf-8") as f:
        json.dump(report, f, ensure_ascii=False, indent=2)
    print("DONE", flush=True)


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