#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
科学·03《月亮错觉》9 张满幅白板底图（版式 v3）
花酱 wb id=180/181/182/183 口径：满幅 9:16 竖构图、元素上下排布、底部 15% 空白纸面、
墨迹最下缘 ≤1550px（与字幕条留 20px）、字幕中心锁死 SUB_CY=1600、底 12% UI 区不得进关键内容。
画风：白板手绘马克笔（暖白纸、粗黑线、扁平无立体阴影），与 01 冰山 / 02 蜜蜂一致。

通道：Pollinations **免费档 flux** t2i + nologo=True（不烧 pollen、不碰 ImageGen 积分、不充值），
符合「视频号没见到钱之前不花钱」。首镜 402 立即停手、不重试不换通道。

⚠ 数字/文字一律不在 AI 图里生成（AI 画中文与数字必错，02 已踩过），
   由后续 moon03_overlay.py 用字体程序化精确叠加，保证「0.5°」「6400 公里」零错。
"""
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 = os.path.join(HERE, "assets_moon03")
os.makedirs(OUT, exist_ok=True)

STYLE = (
    "Whiteboard marker hand-drawn illustration on warm off-white paper, "
    "bold confident black marker outlines, flat simple shapes with NO shading, "
    "NO 3D, NO gradient, NO realistic rendering, clean minimal sketch, "
    "a few small orange accent strokes only, lots of clean empty paper, "
    "vertical 9:16 composition with the drawing elements arranged STACKED from top to bottom. "
    "The BOTTOM 18 percent of the frame must be completely blank empty paper "
    "with absolutely no drawing, no marks, no ink. "
    "No text, no words, no letters, no numbers, no digits, no Chinese characters, "
    "no caption, no arrows with labels, no seal, no watermark, no logo, no signature, "
    "no border, no frame, no panel. "
)

SHOTS = [
    ("moon01", 8101,
     "TWO moons drawn one above the other on a simple horizon line near the top: "
     "the UPPER moon is a small circle high in the sky, the LOWER moon is a clearly "
     "LARGER circle sitting just above a simple flat horizon line. "
     "A large bold hand-drawn QUESTION MARK centered below them. "
     "A few short straight ground lines under the horizon. Simple and graphic."),
    ("moon02", 8102,
     "A simple side-view stick-figure ARM stretched out straight toward the top right, "
     "with an open HAND at the end and one small PINKY FINGER tip highlighted, "
     "and a small circle moon drawn far away above the fingertip. "
     "A thin dashed measuring line from the eye to the fingertip. "
     "Simple whiteboard anatomy sketch, bold marker lines."),
    ("moon03", 8103,
     "A simple angle diagram: one dot at the lower left as the observer, "
     "TWO straight lines spreading slightly upward to a small circle moon at top right, "
     "forming a very narrow angle with a small arc between the two lines at the dot. "
     "Clean geometric whiteboard sketch with lots of empty paper. "
     "No numbers or text of any kind."),
    ("moon04", 8104,
     "A large circle representing EARTH on the left with a tiny dot person standing "
     "on its top edge, and a small circle MOON drawn far to the upper right. "
     "TWO simple straight sight lines from the tiny person toward the moon: "
     "one straight up to the zenith, one toward the horizon. "
     "Clean minimal whiteboard astronomy sketch, bold outlines, lots of blank paper. "
     "No numbers or text."),
    ("moon05", 8105,
     "TWO moons drawn stacked for comparison: the UPPER one is a normal round circle, "
     "the LOWER one is a visibly FLATTENED wide oval ellipse, "
     "with a few short curved horizontal lines around the lower one suggesting layers of air. "
     "Clean whiteboard sketch, bold black outlines, a few orange accent strokes."),
    ("moon06", 8106,
     "Classic Ponzo illusion railway diagram: TWO straight rail lines converging "
     "toward a single vanishing point near the top of the frame, "
     "with ONE short horizontal bar drawn near the top between the rails "
     "and ONE horizontal bar of the SAME exact drawn length near the bottom between the rails. "
     "A few short sleepers across the rails. Clean bold marker lines. "
     "No numbers or text."),
    ("moon07", 8107,
     "A simple side-profile outline of a human HEAD facing right in minimal whiteboard "
     "style, with a small circle moon in front of the eye near the top, "
     "and TWO straight arrows of clearly DIFFERENT lengths pointing right, "
     "one short and one long, drawn stacked below the head. "
     "Bold clean marker lines, flat, lots of blank paper. No text."),
    ("moon08", 8108,
     "A simple hand holding a small round COIN up at arm's length toward a "
     "small circle moon drawn near the top of the frame, "
     "with a thin dashed straight line from the eye to the coin and on to the moon. "
     "Minimal whiteboard sketch, bold marker outlines, flat shapes."),
    ("moon09", 8109,
     "A single large simple round MOON circle near the top, "
     "and below it a simple straight RULER drawn horizontally with a few short "
     "even tick marks along its edge. A small bold hand-drawn question mark "
     "between the moon and the ruler. Very clean and sparse, lots of empty paper."),
]


def white_balance(path, out, target=(250, 246, 236)):
    """02 的 bee_regen_v3.py 口径：把直出偏橙纸色统一到暖白 (250,246,236)。
    只做低饱和亮区的温和映射，不动黑色墨线。"""
    a = np.asarray(Image.open(path).convert("RGB")).astype(np.float32)
    mx, mn = a.max(axis=2), a.min(axis=2)
    sat = mx - mn
    lum = a.mean(axis=2)
    # 纸色候选：亮且低饱和
    m = (lum > 190) & (sat < 45)
    if m.sum() > 1000:
        cur = np.median(a[m], axis=0)
        delta = np.asarray(target, np.float32) - cur
        # 按亮度加权，越接近纸面调整越多，墨线附近衰减
        k = np.clip((lum - 150) / 105.0, 0, 1)[:, :, None]
        k *= np.clip((50 - sat) / 50.0, 0, 1)[:, :, None]
        a = a + delta[None, None, :] * k
    Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)).save(out, "PNG", optimize=True)
    return os.path.getsize(out)


def main():
    rep = []
    for name, seed, desc in SHOTS:
        raw = os.path.join(OUT, name + "_raw.png")
        final = os.path.join(OUT, name + ".png")
        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 FAIL %s" % (name, msg), flush=True)
            rep.append({"name": name, "ok": False, "err": msg})
            if "402" in msg or "pollen" in msg.lower() or "payment" in msg.lower():
                print("STOP: 计费/余额问题，按纪律停手", flush=True)
                break
            continue
        n = white_balance(raw, final)
        print("GEN %s OK bytes=%d %.1fs" % (name, n, time.time() - t0), flush=True)
        rep.append({"name": name, "ok": True, "seed": seed, "bytes": n,
                    "prompt": STYLE + desc})
    json.dump(rep, open(os.path.join(HERE, "moon03_img_report.json"), "w", encoding="utf-8"),
              ensure_ascii=False, indent=2)
    print("DONE ok=%d/%d" % (sum(1 for r in rep if r["ok"]), len(SHOTS)), flush=True)


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