#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 S7-2 老僧肖像 v3（收口）
- v2 人眼结论：C/D/F 留长白须偏道士、清角误伤衣摆（白色抹花）；E 达标但左下有淡红印章。
- v3：
  1) 精确去印：只找四角空白区里「小红连通块」+「小深字块」，整块外接矩形+边距用
     外围纸色填充，2px 羽化；严格跳过长条/大块（衣褶），不碰画面中央人物。
  2) 对 E 从 raw 重新归一 + 精确去印 => 候选 1（正面）
  3) 抽 3 张微侧变体（不同 seed），人眼挑 1 张 => 候选 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  # 默认环境无 scipy，用 cv2.connectedComponentsWithStats 做连通域

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

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. "
    "A standalone character study, not a hanging scroll, not an album leaf, "
    "not mounted, no decorative mounting marks. "
)

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 pale grey-brown Buddhist kasaya monk robe with a simple diagonal "
    "shoulder drape and a soft round collar, 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_NEG = (
    "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. "
    "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, NO signature, NO watermark, NO logo, "
    "NO emblem. The entire image contains only the monk's portrait and blank paper. "
    "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."
)

VARIANTS = [
    ("G", 7341),
    ("H", 7351),
    ("I", 7361),
]


def clean_marks(path, out):
    """精确去印：只在四角空白区找小连通块（红印/深字），整块外接矩形用外围纸色填。
    长条、大块（衣褶）一律跳过，中央人物区不碰。返回清理块数。"""
    im = Image.open(path).convert("RGB")
    a = np.asarray(im).astype(np.float32)
    h, w = a.shape[:2]
    a2 = a.copy()
    # 纸色：整图上边缘中央 + 左右边缘中段的亮像素中位数
    edge = np.concatenate([
        a[:int(h * 0.03), int(w * 0.3):int(w * 0.7)].reshape(-1, 3),
        a[int(h * 0.35):int(h * 0.65), :int(w * 0.03)].reshape(-1, 3),
        a[int(h * 0.35):int(h * 0.65), int(w * 0.97):].reshape(-1, 3),
    ], axis=0)
    bright = edge[edge.mean(axis=1) > 190]
    paper = np.median(bright if len(bright) > 100 else edge, axis=0)

    r, g, b = a[:, :, 0], a[:, :, 1], a[:, :, 2]
    mx = a.max(axis=2)
    # 红印（含淡橙红）+ 四角孤立深色小字
    red = (r > g + 16) & (r > b + 16) & (r > 110) & (g < 205)
    dark = (mx < 150) & ((paper.mean() - mx) > 55)
    marks = red | dark

    # 只在四角：x<24% 或 >76%，且 y<26% 或 >72%
    corner = np.zeros((h, w), bool)
    corner[:int(h * 0.26), :int(w * 0.24)] = True
    corner[:int(h * 0.26), int(w * 0.76):] = True
    corner[int(h * 0.72):, :int(w * 0.24)] = True
    corner[int(h * 0.72):, int(w * 0.76):] = True
    marks &= corner

    nlab, lab, stats, cents = cv2.connectedComponentsWithStats(marks.astype(np.uint8), 8)
    fixed = 0
    for i in range(1, nlab):
        x, y, bw, bh, area = stats[i]
        ys = slice(y, y + bh); xs = slice(x, x + bw)
        # 小块印章/题款：面积 8..4000，且外接框不能是长条或大块（衣褶/衣摆）
        if area < 8 or area > 4000:
            continue
        if bh > int(h * 0.11) or bw > int(w * 0.11):
            continue
        if bh / max(bw, 1) > 3.5 or bw / max(bh, 1) > 3.5:
            continue
        pad = 5
        y0, y1 = max(0, y - pad), min(h, y + bh + pad)
        x0, x1 = max(0, x - pad), min(w, x + bw + pad)
        # 外围环采样纸色（比全局纸色更贴局部光照）
        ring = np.concatenate([
            a2[max(0, y0 - 6):y0, x0:x1].reshape(-1, 3),
            a2[y1:min(h, y1 + 6), x0:x1].reshape(-1, 3),
            a2[y0:y1, max(0, x0 - 6):x0].reshape(-1, 3),
            a2[y0:y1, x1:min(w, x1 + 6)].reshape(-1, 3),
        ], axis=0)
        ring_b = ring[ring.mean(axis=1) > 180]
        local_paper = np.median(ring_b if len(ring_b) > 20 else ring, axis=0)
        # 整块矩形填纸色，边缘 2px 羽化（避免硬边）
        m = np.ones((y1 - y0, x1 - x0), np.float32)
        m[:2, :] *= 0.45; m[-2:, :] *= 0.45; m[:, :2] *= 0.45; m[:, -2:] *= 0.45
        m = m[:, :, None]
        patch = a2[y0:y1, x0:x1]
        a2[y0:y1, x0:x1] = patch * (1 - m) + local_paper[None, None, :] * m
        fixed += 1
    Image.fromarray(np.clip(a2, 0, 255).astype(np.uint8)).save(out, "PNG", optimize=True)
    return fixed


def main():
    report = []
    # 1) E 从 raw 重做（v2 的清角抹法不够干净）
    e_raw = os.path.join(OUT_DIR, "ep03_s72_monk_E_raw.png")
    e_tmp = os.path.join(OUT_DIR, "_e_norm.png")
    Image.open(e_raw).convert("RGB").resize((756, 1008), Image.LANCZOS).save(e_tmp)
    e_out = os.path.join(OUT_DIR, "ep03_s72_cand1_front.png")
    n1 = clean_marks(e_tmp, e_out)
    report.append({"tag": "cand1_front", "from": "E", "pose": "正面", "cleaned_blocks": n1,
                   "bytes": os.path.getsize(e_out)})
    print("CAND1 (from E) blocks=%d bytes=%d" % (n1, os.path.getsize(e_out)), flush=True)

    # 2) 抽 3 张微侧
    for tag, seed in VARIANTS:
        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(STYLE + SIDE + BG_NEG, 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": "微侧",
                       "cleaned_blocks": n, "bytes": os.path.getsize(out)})
    with open(os.path.join(OUT_DIR, "gen_report_v3.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()
