#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""moon03 张角示意 v3：v2 两张分别是直角 / 单线，都不合「约 0.5° 的窄角」。
改用更硬的几何描述 + 3 个 seed，人眼挑一张。免费档 flux，不花钱。"""
import importlib.util, os, sys, time, json
from PIL import Image
import numpy as np
import cv2

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "assets_moon03")
sp = importlib.util.spec_from_file_location(
    "pol", r"C:\Users\ngmk\.workbuddy\skills\local-imagegen\scripts\pollinations_gen.py")
pol = importlib.util.module_from_spec(sp); sp.loader.exec_module(pol)
sp2 = importlib.util.spec_from_file_location("v1", os.path.join(HERE, "moon03_imgs.py"))
v1 = importlib.util.module_from_spec(sp2); sp2.loader.exec_module(v1)

STYLE = (
    "Whiteboard marker hand-drawn illustration on warm off-white paper, "
    "bold clean black marker lines, flat and simple, lots of blank clean paper, "
    "vertical 9:16 composition, subject in the upper two thirds, "
    "bottom quarter completely blank paper. "
    "The image consists ONLY of pure geometric line shapes and blank paper. "
)

# 强调两条线都朝右上、夹角很小，且用「窄楔形」而非直角
DESC = (
    "A narrow-angle geometry sketch. ONE single black dot at the LOWER LEFT is the vertex. "
    "From that ONE dot, TWO straight lines both rise up and to the RIGHT, "
    "one line only slightly steeper than the other, so together they form a "
    "VERY NARROW wedge of about fifteen degrees, like a thin slice of pie. "
    "Both lines are long and clearly separate from each other along their whole length. "
    "A small curved ARC joins the two lines right at the vertex dot. "
    "A small empty circle sits at the far upper right where the two lines end. "
    "Nothing else in the picture."
)


def scrub(path, out):
    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
    n, lab, stats, _ = cv2.connectedComponentsWithStats(dark * edge, 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 or bw > w * .10 or bh > h * .06:
            continue
        x0, x1 = max(0, x - 3), min(w, x + bw + 3)
        y0, y1 = max(0, y - 3), min(h, y + bh + 3)
        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 j, seed in enumerate((8303, 8313, 8323), 1):
        raw = os.path.join(OUT, "moon03_v3_%d_raw.png" % j)
        tmp = os.path.join(OUT, "_moon03_v3_%d_tmp.png" % j)
        final = os.path.join(OUT, "moon03_v3_%d.png" % j)
        try:
            pol.t2i(STYLE + DESC, model="flux", width=1024, height=1792,
                    seed=seed, nologo=True, out=raw, timeout=300)
            v1.white_balance(raw, tmp)
            n = scrub(tmp, final)
            print("v3-%d OK bytes=%d scrub=%d" % (j, os.path.getsize(final), n), flush=True)
            rep.append({"var": j, "seed": seed, "ok": True, "bytes": os.path.getsize(final)})
        except Exception as e:
            print("v3-%d FAIL %s" % (j, e), flush=True)
            rep.append({"var": j, "seed": seed, "ok": False, "err": str(e)})
    json.dump(rep, open(os.path.join(HERE, "moon03_v3_report.json"), "w", encoding="utf-8"),
              ensure_ascii=False, indent=2)
    print("DONE", flush=True)


if __name__ == "__main__":
    main()
