#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
科学·03 底图 v2：重画 4 张不合格图（moon03/05/06/07）
v1 人眼验收问题：
  moon03 张角只画了一条斜线（应有同点发出的两条线+弧）；
  moon05「压扁月」画成了第二个圆；
  moon06 顶部出现带叉方框、右下有疑似「1/6」小字；
  moon07 箭头尾部出现网格状汉字残笔。
v2 修正：
  - 删掉 prompt 里所有 text/number/seal 等否定名词（同 S7-2 的反噬坑），
    改纯正面描述「画面只由几何线条构成」；
  - 构图描述改得更硬（TWO distinct lines from ONE dot / strongly flattened oval 等）；
  - 每图 2 个 seed，人眼挑干净的一张；
  - 出图后程序化清除边缘小尺寸孤立墨块（残留小字），只碰边缘、不碰主体长线条。
通道：Pollinations 免费档 flux，nologo=True，不花钱。
"""
import importlib.util, json, os, sys, time
import numpy as np
import cv2
from PIL import Image

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "assets_moon03")
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)

v1 = importlib.util.module_from_spec(
    importlib.util.spec_from_file_location("v1", os.path.join(HERE, "moon03_imgs.py")))
importlib.util.spec_from_file_location("v1", os.path.join(HERE, "moon03_imgs.py"))
spec1 = importlib.util.spec_from_file_location("v1", os.path.join(HERE, "moon03_imgs.py"))
v1 = importlib.util.module_from_spec(spec1)
spec1.loader.exec_module(v1)
white_balance = v1.white_balance

# 纯正面描述：只讲「画面里有什么」，不提任何文字/数字/水印概念
STYLE = (
    "Whiteboard marker hand-drawn illustration on warm off-white paper. "
    "The image consists ONLY of pure clean geometric line shapes in bold confident "
    "black marker strokes, flat and simple, with a few small orange accent strokes. "
    "All remaining paper is completely blank and untouched. "
    "Vertical 9:16 composition, drawing elements stacked from top to bottom, "
    "reaching down to about three quarters of the frame height, "
    "with the bottom quarter left as completely blank clean paper. "
)

RERUN = [
    ("moon03", 8203, 8213,
     "A very narrow ANGLE diagram. ONE single dot at the lower left is the vertex. "
     "From that SAME dot, TWO distinct straight lines rise up to the right, "
     "spreading apart slightly to form a clearly visible narrow wedge. "
     "A small curved ARC is drawn between the two lines right at the dot. "
     "A small empty circle sits at the upper right end of the wedge. "
     "Only these four clean line elements and blank paper."),
    ("moon05", 8205, 8215,
     "A shape comparison stacked vertically. At the TOP, ONE perfectly round circle. "
     "Far BELOW it, ONE strongly FLATTENED wide horizontal oval, clearly much wider "
     "than it is tall, squashed like a flat pancake, unmistakably NOT round. "
     "Three short gently curved horizontal lines float just under the flattened oval "
     "like layers of air. A thin short vertical tick between the two shapes. "
     "Only these clean line elements and blank paper."),
    ("moon06", 8206, 8216,
     "A railway perspective sketch. TWO straight rail lines start wide apart at the "
     "bottom and converge to ONE single vanishing point near the top. "
     "A few short evenly spaced horizontal sleepers cross between the rails. "
     "ONE single short straight horizontal bar crosses between the rails near the "
     "vanishing point, and ONE single straight horizontal bar of the SAME drawn length "
     "crosses between the rails near the bottom. No other shapes anywhere. "
     "Only clean straight lines and blank paper."),
    ("moon07", 8207, 8217,
     "A simple clean side-profile outline of a human head facing right, drawn with "
     "ONE continuous smooth contour line, with a small solid dot for the eye. "
     "A small empty circle floats in front of the face near the top. "
     "BELOW the head, TWO plain straight horizontal arrows pointing right, "
     "one clearly SHORT and one clearly LONG, each made of one straight shaft and "
     "one simple triangular arrowhead. Nothing else. "
     "Only clean lines and blank paper."),
]


def scrub_edge_marks(path, out):
    """清除画面最外缘的孤立小墨块（AI 残留小字/分数），只碰边缘 12% 带。
    主体长线条（长条连通块）一律保留。"""
    a = np.asarray(Image.open(path).convert("RGB")).astype(np.float32)
    h, w = a.shape[:2]
    a2 = a.copy()
    dark = (a.max(axis=2) < 150).astype(np.uint8)
    edge = np.zeros((h, w), np.uint8)
    edge[:int(h * .16), :] = 1
    edge[int(h * .84):, :] = 1
    edge[:, :int(w * .12)] = 1
    edge[:, int(w * .88):] = 1
    m = dark * edge
    n, lab, stats, _ = cv2.connectedComponentsWithStats(m, 8)
    paper = np.median(a[:int(h * .05)].reshape(-1, 3), axis=0)
    fixed = 0
    for i in range(1, n):
        x, y, bw, bh, area = stats[i]
        if area < 5 or area > 900:
            continue
        if bw > w * .10 or bh > h * .06:      # 长线条/主体跳过
            continue
        pad = 3
        x0, x1 = max(0, x - pad), min(w, x + bw + pad)
        y0, y1 = max(0, y - pad), min(h, y + bh + pad)
        a2[y0:y1, x0:x1] = paper[None, None, :]
        fixed += 1
    Image.fromarray(np.clip(a2, 0, 255).astype(np.uint8)).save(out, "PNG", optimize=True)
    return fixed


def main():
    rep = []
    for name, s1, s2, desc in RERUN:
        for j, seed in enumerate((s1, s2), 1):
            raw = os.path.join(OUT, "%s_v2_%d_raw.png" % (name, j))
            final = os.path.join(OUT, "%s_v2_%d.png" % (name, j))
            t0 = time.time()
            try:
                pol.t2i(STYLE + desc, model="flux", width=1024, height=1792,
                        seed=seed, nologo=True, out=raw, timeout=300)
            except Exception as e:
                msg = str(e)
                print("GEN %s v2-%d FAIL %s" % (name, j, msg), flush=True)
                rep.append({"name": name, "var": j, "ok": False, "err": msg})
                if "402" in msg or "pollen" in msg.lower() or "payment" in msg.lower():
                    print("STOP: 计费/余额问题，按纪律停手", flush=True)
                    break
                continue
            tmp = os.path.join(OUT, "_%s_v2_%d_tmp.png" % (name, j))
            white_balance(raw, tmp)
            n = scrub_edge_marks(tmp, final)
            print("GEN %s v2-%d OK bytes=%d scrub=%d %.1fs" %
                  (name, j, os.path.getsize(final), n, time.time() - t0), flush=True)
            rep.append({"name": name, "var": j, "ok": True, "seed": seed,
                        "scrub_blocks": n, "bytes": os.path.getsize(final)})
    json.dump(rep, open(os.path.join(HERE, "moon03_img_v2_report.json"), "w", encoding="utf-8"),
              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()
