#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 S7-2 老僧人肖像 v2（wb 箱 id=196）
v1 问题（人眼验收）：A 左下红印、B 左侧毛笔字+两枚红印；两版都留长白须（偏道士/寿星），
线条偏漫画硬描、不够水彩绘本；僧人识别不够硬。
v2 修正：
  - 明确剃净须发（clean-shaven，NO beard/mustache/goatee），避免道士/寿星观感
  - 四角全空白、全图任何位置禁红印/书法/题款/签名（写进 prompt 三处）
  - 画风改柔和水彩晕染（写意淡彩），弱化黑色硬描边
  - 强化僧人识别：光头戒疤 + 素灰褐袈裟斜披 + 无冠无巾无发
  - 出 4 张（2 构图 × 2 seed），人眼挑最好的 2 张作候选
  - 程序化清角兜底：检测高饱和红色印痕/孤立深色小字，局部 inpaint 成纸色
通道：Pollinations 免费档 flux t2i，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

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

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 (NO thick black outlines, "
    "NO comic-book inking, NO flat cartoon cel shading), matte handmade paper grain visible, "
    "quiet restrained and tender, large clean pale empty paper around the subject. "
)

SUBJECT_FRONT = (
    "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 on the crown, a gaunt face covered with deep 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 is COMPLETELY CLEAN-SHAVEN: absolutely NO beard, NO long white beard, NO moustache, "
    "NO goatee, NO whiskers, NO facial hair of any kind except the white eyebrows. "
    "He wears a plain faded grey-brown Buddhist kasaya monk robe with a simple diagonal "
    "drape across one shoulder and a soft round collar, no pattern, no embroidery. "
    "Unmistakably a humble aged Buddhist monk: bald shaved head and monk robe are the two "
    "clear identifiers. NOT a Taoist priest, NOT a Confucian scholar, NOT a young man, "
    "NOT an emperor, NOT a prince, NOT the Jianwen Emperor: no hair, no topknot, no Taoist "
    "cap, no crown, no hat, no imperial dragon robe, no official cap, no jade belt, "
    "no jewelry, no throne, no sword, no fan, no staff. "
    "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. "
)

SUBJECT_SIDE = (
    "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, deeply wrinkled gaunt face, long drooping white eyebrows, "
    "heavy-lidded tired eyes gazing slightly downward, hollow cheeks, thin folded lips, "
    "a few age spots. He is COMPLETELY CLEAN-SHAVEN: absolutely NO beard, NO long white "
    "beard, NO moustache, NO goatee, NO whiskers, NO facial hair except white eyebrows. "
    "He wears a plain faded ochre-grey Buddhist kasaya monk robe with a simple diagonal "
    "shoulder drape, no pattern. Unmistakably a humble aged Buddhist monk: bald shaved "
    "head and monk robe are the clear identifiers. NOT a Taoist priest, NOT a scholar, "
    "NOT a young man, NOT an emperor, NOT a prince, NOT the Jianwen Emperor: no hair, "
    "no topknot, no Taoist cap, no crown, no hat, no imperial dragon robe, no official cap, "
    "no jewelry, no throne, no staff. 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. ALL FOUR CORNERS of the image must be completely blank clean "
    "paper with nothing in them. No frame, no border, no rectangle, no panel, no scenery, "
    "no landscape, no buildings, no other people, no props, no floating objects. "
)

NEG = (
    "STRICTLY NO text, NO words, NO Chinese characters, NO calligraphy, NO brush lettering, "
    "NO inscription, NO caption, NO title, NO letters, NO numbers, NO digits, "
    "NO red seal, NO red stamp, NO seal mark anywhere including all four corners, "
    "NO signature, NO watermark, NO logo, NO emblem. The entire image contains only the "
    "monk's portrait and blank paper, nothing else. "
    "Not a photograph, not photorealistic, not 3D render, not CGI, not oil painting, "
    "not anime, not manga, not a comic, not a caricature, not a historical portrait copy, "
    "not based on any real person or any existing painting, no extra limbs, no deformed "
    "face, no extra heads, no duplicate figures."
)

CANDS = [
    ("C", SUBJECT_FRONT, 7311, "正面·干净剃须·柔水彩", "front"),
    ("D", SUBJECT_SIDE,  7312, "微侧·干净剃须·柔水彩", "side"),
    ("E", SUBJECT_FRONT, 7331, "正面·换种子", "front"),
    ("F", SUBJECT_SIDE,  7332, "微侧·换种子", "side"),
]


def clean_corners(path, out):
    """兜底：检测四角区域的红印/孤立深色字迹，用局部纸色 inpaint 抹掉。
    只碰四角空白区（宽 22%、高 26%），不碰画面中央的人物。"""
    im = Image.open(path).convert("RGB")
    a = np.asarray(im).astype(np.float32)
    h, w = a.shape[:2]
    a2 = a.copy()
    # 纸色基准：取顶部中央一条（人物光头通常在中部偏上，取最上 3% 行做纸色估计）
    paper = np.median(a[int(h * 0.005):int(h * 0.03), int(w * 0.35):int(w * 0.65)].reshape(-1, 3), axis=0)
    corners = [
        (0, int(w * 0.20), 0, int(h * 0.24)),              # 左上
        (int(w * 0.80), w, 0, int(h * 0.24)),              # 右上
        (0, int(w * 0.20), int(h * 0.76), h),              # 左下
        (int(w * 0.80), w, int(h * 0.76), h),              # 右下
    ]
    total = 0
    for x0, x1, y0, y1 in corners:
        reg = a[y0:y1, x0:x1]
        r, g, b = reg[:, :, 0], reg[:, :, 1], reg[:, :, 2]
        mx, mn = reg.max(axis=2), reg.min(axis=2)
        # 红色印痕（高饱和偏红）或近黑小字（明显暗于纸）
        red = (r > g + 28) & (r > b + 28) & (r > 90) & (g < 170)
        dark = (mx < 135) & (np.abs(paper.mean() - mx) > 45)
        mask = red | dark
        # 只抹「小块孤立」痕迹：整角墨迹占比 < 22% 才处理，避免误伤人物衣褶
        if mask.mean() < 0.22 and mask.sum() > 8:
            # 用纸色 + 极轻噪声替换，边缘做 6px 羽化
            try:
                from scipy.ndimage import binary_dilation, gaussian_filter
                m = binary_dilation(mask, iterations=5).astype(np.float32)
                m = gaussian_filter(m, sigma=2.0)
                m = np.clip(m * 1.35, 0, 1)[:, :, None]
            except Exception:
                m = mask.astype(np.float32)[:, :, None]
            patch = a2[y0:y1, x0:x1]
            a2[y0:y1, x0:x1] = patch * (1 - m) + paper[None, None, :] * m
            total += int(mask.sum())
    Image.fromarray(np.clip(a2, 0, 255).astype(np.uint8)).save(out, "PNG", optimize=True)
    return total


def main():
    results = []
    for tag, subj, seed, note, pose 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:
            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)
            results.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
        im = Image.open(raw).convert("RGB").resize((756, 1008), Image.LANCZOS)
        im.save(final, "PNG", optimize=True)
        scrub = clean_corners(final, final)
        results.append({"tag": tag, "ok": True, "note": note, "pose": pose, "seed": seed,
                        "bytes": os.path.getsize(final), "scrub_px": scrub,
                        "prompt": prompt})
        print("OUT %s bytes=%d scrub_px=%d %.1fs" %
              (tag, os.path.getsize(final), scrub, time.time() - t0), flush=True)
    with open(os.path.join(OUT_DIR, "gen_report_v2.json"), "w", encoding="utf-8") as f:
        json.dump(results, 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()
