#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 kontext part2（花酱 wb 箱 id147 / 刚已充 $2）
  1) 02/03/07：按已固化的 ep03_kontext_shots.json 逐镜修法续跑（img2img 保构图）
  2) 01：只重修一版（单层宽体大殿 + 底部 1/3 留空），不成保留现有 B 版
  3) 纪律：每镜只跑 1 次；第一张作余额实证，402 立即停手；不换模型/通道/积分

余额说明：官方 /account/balance 对本机 key 返回 403（无 account:usage 权限、
无独立预算），读不到数值；/account/key 200 valid:true、/account/profile 200、
flux 免费探针 200。故以「首镜 02 实调」作余额到账实证：200 即继续，402 即停手。
"""
import argparse, importlib.util, json, os, subprocess, sys, time, urllib.error

HERE = os.path.dirname(os.path.abspath(__file__))
CFG = os.path.join(HERE, "ep03_kontext_shots.json")
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_v2_report.json")

# 01 重修：只加强「单层宽体大殿」与「底部三分之一留空」，其余沿用已达标项
PROMPT_01_V2 = (
    "Keep the night palace-fire watercolor scene of the reference image, but make these "
    "specific corrections to the ARCHITECTURE and the COMPOSITION only: "
    "1) The building MUST be ONE SINGLE-STOREY broad horizontal early-Ming Chinese palace "
    "hall (Fengtian Hall): a very wide, long, LOW rectangular hall body with one single row "
    "of tall red columns and red doors at ground level, and a double-eaved xieshan "
    "hip-and-gable roof with golden glazed tiles sitting DIRECTLY on that one low hall body. "
    "The two eaves belong to the roof, NOT to two floors. Absolutely NO second storey, "
    "NO upper floor, NO upper windows, NO upper gallery, NO stacked tower, NO pavilion on "
    "top, NO multi-tiered pagoda, NO Japanese castle keep, NO watchtower. The silhouette "
    "must be a long low horizontal rectangle, roughly 4 times wider than it is tall, NOT a "
    "tall square tower. "
    "2) The ENTIRE bottom third of the frame must be completely empty clean pale watercolor "
    "paper for subtitles: no steps, no staircases, no stone terrace, no balustrade, no wall, "
    "no figures, no shadows, no ground line in that zone. Compress the whole building and its "
    "platform into the UPPER TWO THIRDS of the frame. "
    "3) Preserve: deep dark blue night sky, clearly visible orange flames and fire glow rising "
    "from the roof, drifting dark smoke, red walls, golden roof tiles, distant dark mountain "
    "silhouette, soft wet watercolor edges on 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 Beijing corner tower, no Tiananmen."
)

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):
    """抓 402/403 响应体原文（含 available balance），不猜测。"""
    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()

    cfg = json.load(open(CFG, encoding="utf-8"))
    mod = load_module()

    # 顺序：02 作余额实证 → 03 → 07 → 01 重修
    order = ["02", "03", "07", "01v2"]
    if a.only:
        order = [x for x in order if x in a.only]

    report = {
        "batch": "EP03 kontext part2（花酱 id147 / 刚已充 $2）",
        "channel": cfg["channel"],
        "balance_check": {
            "ts": time.strftime("%Y-%m-%d %H:%M:%S"),
            "method": "官方只读端点 /account/balance 被 403 拦（key 无 account:usage 权限且无独立预算），读不到数值；改用首镜 02 实调作余额到账实证",
            "account_key": "HTTP 200 valid=true type=secret name=huajiang permissions.account=null pollenBudget=null",
            "account_profile": "HTTP 200",
            "flux_free_probe": "HTTP 200 / 256x256 / 9711 B（免费档不烧 pollen）",
            "reference_402": "2026-11-12 14:08 INSUFFICIENT_BALANCE: cost ~0.0300 pollen, available 0.0020",
            "decision": "02 返回 200 即判定充值到账并继续；若 402 立即停手并回报错误体",
        },
        "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:
        if s == "01v2":
            d = dict(cfg["shots"]["01"])
            d["name"] = "南京宫城夜火·重修 v2（单层宽体大殿 + 底部1/3留空）"
            d["prompt"] = PROMPT_01_V2
            d["input"] = "ep03_base_01.png"   # 同底图重跑，口径与 part1 严格可比
            outname = "ep03_base_01_kontext_v2_probe.png"
            edits = "只试一次：单层宽体奉天殿（one storey, broad horizontal hall, 重檐歇山）、底部三分之一严格留空；不成保留现有 B 版"
        else:
            d = cfg["shots"][s]
            outname = "ep03_base_%s_kontext.png" % s
            edits = d["edits"]

        inp = os.path.join(HERE, d["input"])
        out = os.path.join(HERE, outname)
        t0 = time.time()
        rec = {
            "shot": s, "name": d["name"], "input": d["input"],
            "output": outname, "edits": edits, "prompt": d["prompt"],
            "model": "kontext", "cost": "kontext i2i 约 0.0300 pollen/次（刚已充 $2）",
            "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)

        # 首镜（或任何一镜）402 = 余额未到账/耗尽 → 按纪律停手
        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"],
        "note": "每镜只跑 1 次；01 重修只试一次，不成保留 part1 的 B 版",
    }
    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()
