#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 kontext part3（花酱 wb 箱 id148 / 刚 15:39 拍板）

  1) 01v3（只试一次）：以 v2 官方 B 版 ep03_base_01_kontext_v2_final_edgepad.png 为底，
     形制原样保住（单层宽体大殿、重檐歇山、一排红柱红门），
     只动夜色与火光 —— 夜空加深到深蓝、屋顶火焰舌强化（清晰橙黄火舌＋黑烟）。
     不成则保留 v2，不再多抽。封面 12 等这版结果出来再说，先不动。
  2) 07v2（只试一次）：以本地抽象纸面草稿 ep03_base_07.png 为底；
     prompt 全程不出现「日历」二字（含否定句也避开），
     主体改为「受损的古代史册、四页被撕去、撕口是空白旧纸」，
     明写无字、无数字、无格线、无表格。再不成也别多抽，只作对照、等定方向。
  3) 02/03 直接过，不再修（本脚本不碰这两镜）。

  纪律：每镜只跑 1 次，共 2 次调用（约 0.06 pollen）；
        首镜 402 立即停手，不重试、不充值、不换模型/通道、不碰 ImageGen 积分。
"""
import argparse, importlib.util, json, os, subprocess, sys, time, urllib.error

HERE = os.path.dirname(os.path.abspath(__file__))
SKILL_PY = r"C:\Users\ngmk\.workbuddy\skills\local-imagegen\scripts\pollinations_gen.py"
FFPROBE = r"D:\tools\ffmpeg\bin\ffprobe.exe"
REPORT = os.path.join(HERE, "ep03_kontext_v3_report.json")

# 01 第三版：形制、构图、留白一律「保住原样」，只允许改夜色与火光
PROMPT_01_V3 = (
    "Watercolor picture-book illustration editing. PRESERVE the reference image almost "
    "entirely: keep EXACTLY the same building shape and silhouette, the same one SINGLE-STOREY "
    "broad horizontal early-Ming Chinese palace hall (Fengtian Hall) with its very wide low "
    "rectangular body, the same one row of tall red columns and red doors, the same "
    "double-eaved xieshan hip-and-gable golden tiled roof sitting DIRECTLY on that one low "
    "body, and the same framing and composition. Do NOT add a second storey, upper floor, "
    "upper windows, tower, pavilion, pagoda or Japanese castle keep. Do NOT change the "
    "building's proportions or position. Keep the existing clean pale empty paper at the "
    "bottom of the frame unchanged. "
    "CHANGE ONLY the sky and the fire: 1) Deepen the night sky from its current lighter "
    "tone into a rich deep dark indigo navy blue, clearly a midnight sky, darker and more "
    "saturated, with the dark blue extending evenly across the whole sky. "
    "2) Strengthen the fire on and above the roof into clearly visible distinct orange-yellow "
    "flame tongues with bright yellow cores and orange tips licking upward, plus thick "
    "billowing black dark smoke plumes rising and drifting; add a warm orange fire glow "
    "reflecting on the roof tiles and red walls. The flames must read as individual shaped "
    "tongues of fire, not a flat orange haze. "
    "Keep the soft wet watercolor edges and textured paper. No text, no letters, no Chinese "
    "characters, no numbers, no seal, no red stamp, no watermark, no logo, no people, "
    "no modern objects, no extra buildings, no Beijing corner tower, no Tiananmen."
)

# 07 重跑：全 prompt 不出现 calendar 一词（含否定句），主体改「受损古代史册」
PROMPT_07_V2 = (
    "Minimalist abstract watercolor on aged textured paper. PRESERVE the reference image's "
    "large clean empty pale paper area, the soft torn paper edges, the ragged deckle border, "
    "and the overall sparse abstract composition with the subject confined to the UPPER part "
    "of the frame and the entire bottom third left as completely clean empty paper. "
    "PLACE ONE single main subject in the upper part: a DAMAGED ANCIENT BLANK HISTORY "
    "MANUSCRIPT, an old worn thread-bound book of plain aged paper, lying slightly tilted. "
    "EXACTLY FOUR of its pages have been torn away: show four separate visible ragged torn "
    "page stubs / torn page roots along the inner edge, with uneven fibrous torn paper edges. "
    "Every remaining page and every torn stub is COMPLETELY BLANK pale old paper. "
    "ABSOLUTELY NO writing, NO letters, NO Chinese characters, NO words, NO numbers, "
    "NO digits, NO dates, NO grid lines, NO ruled lines, NO table, NO chart, NO boxes, "
    "NO printed marks, NO ink, NO stamp, NO seal, no red stamp, no watermark, no logo. "
    "The book is only blank paper and torn blank paper — nothing is drawn or written on it. "
    "No landscape, no village, no houses, no figures, no people, no modern objects. "
    "Warm watercolor on textured paper, soft wet edges, quiet and empty, lots of negative "
    "space. Keep the bottom third as clean empty paper for subtitles."
)

SHOTS = {
    "01v3": {
        "name": "南京宫城夜火·第三版（保形制，只改夜色与火光）",
        "input": "ep03_base_01_kontext_v2_final_edgepad.png",
        "out": "ep03_base_01_kontext_v3_probe.png",
        "prompt": PROMPT_01_V3,
        "edits": "底=v2 官方 B 版；形制/构图/留白原样保住，只加深夜空到深蓝、强化屋顶橙黄火舌与黑烟；只试一次，不成保留 v2",
    },
    "07v2": {
        "name": "残卷·重跑第二版（受损古代史册，去日历表述）",
        "input": "ep03_base_07.png",
        "out": "ep03_base_07_kontext_v2.png",
        "prompt": PROMPT_07_V2,
        "edits": "底=本地抽象纸面草稿；prompt 全程不出现「日历」二字；主体=受损古代史册＋四页撕痕＋空白旧纸；明写无字/无数字/无格线/无表格；只试一次",
    },
}

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


def load_module():
    spec = importlib.util.spec_from_file_location("pollinations_gen", SKILL_PY)
    m = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(m)
    return m


def probe_size(p):
    r = subprocess.run([FFPROBE, "-v", "error", "-select_streams", "v:0",
                        "-show_entries", "stream=width,height", "-of", "csv=p=0", p],
                       capture_output=True, text=True)
    return r.stdout.strip()


def error_body(e):
    try:
        return e.read().decode("utf-8", "replace")[:1200]
    except Exception:
        return ""


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--timeout", type=int, default=300)
    ap.add_argument("--only", nargs="*", default=[], help="只跑指定镜头（默认两镜全跑）")
    a = ap.parse_args()

    order = ["01v3", "07v2"]
    if a.only:
        order = [x for x in order if x in a.only]

    mod = load_module()
    report = {
        "batch": "EP03 kontext part3（花酱 wb 箱 id148 / 刚 15:39 拍板）",
        "channel": "Pollinations kontext i2i，nologo，key 本机读取；不换模型/通道，不碰 ImageGen 积分",
        "discipline": "每镜只跑 1 次，共约 0.06 pollen；402 立即停手；02/03 直接过不重跑；封面 12 不动",
        "runs": [], "stopped": False,
    }
    if os.path.exists(REPORT):
        try:
            report["runs"] = json.load(open(REPORT, encoding="utf-8")).get("runs", [])
        except Exception:
            pass

    for s in order:
        d = SHOTS[s]
        inp = os.path.join(HERE, d["input"])
        out = os.path.join(HERE, d["out"])
        if not os.path.exists(inp):
            print("MISSING base image:", inp, flush=True)
            break
        t0 = time.time()
        rec = {
            "shot": s, "name": d["name"], "input": d["input"],
            "input_bytes": os.path.getsize(inp), "output": d["out"],
            "edits": d["edits"], "prompt": d["prompt"],
            "model": "kontext", "requested_size": [1536, 864],
            "cost": "kontext i2i 约 0.0300 pollen/次",
            "ts": time.strftime("%Y-%m-%d %H:%M:%S"),
        }
        try:
            _, sz = mod.i2i(d["prompt"], inp, model="kontext", width=1536, height=864,
                            out=out, timeout=a.timeout)
            rec.update(ok=True, bytes=sz, elapsed_s=round(time.time() - t0, 1),
                       size_raw=probe_size(out),
                       note="服务端未按请求宽高返回；后续走等比缩放＋补边归一到 1536x864")
            print("OK   %-5s %s  %d B  %.1fs" % (s, rec["size_raw"], sz, rec["elapsed_s"]), flush=True)
        except urllib.error.HTTPError as e:
            body = error_body(e)
            rec.update(ok=False, http=e.code, error="HTTP %s %s" % (e.code, e.reason),
                       error_body=body, elapsed_s=round(time.time() - t0, 1))
            print("FAIL %-5s HTTP %s  %s" % (s, e.code, body[:300]), flush=True)
        except Exception as e:
            rec.update(ok=False, error="%s: %s" % (type(e).__name__, str(e)[:500]),
                       elapsed_s=round(time.time() - t0, 1))
            print("FAIL %-5s %s" % (s, rec["error"][:200]), flush=True)

        report["runs"] = [x for x in report["runs"] if x.get("shot") != s]
        report["runs"].append(rec)
        with open(REPORT, "w", encoding="utf-8") as f:
            json.dump(report, f, ensure_ascii=False, indent=2)

        if not rec["ok"] and rec.get("http") == 402:
            report["stopped"] = True
            report["stop_reason"] = "%s 返回 402，余额不足；按纪律停手，不重试、不充值、不换通道" % s
            print("STOP: 402", flush=True)
            break

    report["summary"] = {
        "attempted": len(report["runs"]),
        "ok": sum(1 for x in report["runs"] if x.get("ok")),
        "failed": sum(1 for x in report["runs"] if not x.get("ok")),
        "stopped": report["stopped"],
    }
    with open(REPORT, "w", encoding="utf-8") as f:
        json.dump(report, f, ensure_ascii=False, indent=2)
    print("report:", REPORT, json.dumps(report["summary"], ensure_ascii=False), flush=True)


if __name__ == "__main__":
    main()
