#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 kontext part3 · 补边归一与接缝量化（花酱 wb 箱 id148）

规则沿用 id147 第 3 条（id148 未改）：
- 01（含 v3）：用已批准的 B 版边缘自适应补边；A 版仅作对照。
- 07（含 v2）：默认 A 版纸色；若暗场图且 A 版出现可见接缝（>10）才改 B 并注明。
- 全部等比缩放（可放大），零裁切零变形，输出严格 1536x864。
- 额外：量化 01 v2→v3 的明度/暗部占比变化，作为「风格漂移」的客观佐证。
"""
import importlib.util, json, os, sys

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
W, H = 1536, 864

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


def _load(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    m = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(m)
    return m


v2pad = _load("v2pad", os.path.join(HERE, "ep03_kontext_v2_pad.py"))
edge = v2pad.edge
s5 = v2pad.s5


def brightness_stats(path):
    img, w, h = edge.load_rgb(path)
    f = img.astype(np.float32)
    lum = 0.2126 * f[:, :, 0] + 0.7152 * f[:, :, 1] + 0.0722 * f[:, :, 2]
    sat = f.max(axis=2) - f.min(axis=2)
    return {
        "size": [w, h],
        "mean_luminance": round(float(lum.mean()), 1),
        "median_luminance": round(float(np.median(lum)), 1),
        "dark_pixel_pct_lt80": round(float((lum < 80).mean() * 100), 1),
        "bright_pixel_pct_gt200": round(float((lum > 200).mean() * 100), 1),
        "mean_saturation_range": round(float(sat.mean()), 1),
    }


def main():
    jobs = [
        ("01v3", "ep03_base_01_kontext_v3_probe.png",
         "ep03_base_01_kontext_v3_final_paperpad.png",
         "ep03_base_01_kontext_v3_final_edgepad.png",
         "B", "01 第三版：沿用 id147 已批准的 B 版（边缘自适应）；A 版仅作对照"),
        ("07v2", "ep03_base_07_kontext_v2.png",
         "ep03_base_07_kontext_v2_final_paperpad.png",
         "ep03_base_07_kontext_v2_final_edgepad.png",
         "A", "07 重跑版：默认 A 版纸色，暗场＋可见接缝才切 B"),
    ]

    pad_log, seams = [], {}
    for shot, raw, a_name, b_name, official, note in jobs:
        src = os.path.join(HERE, raw)
        img, w0, h0 = edge.load_rgb(src)
        scale, nw, nh, y = v2pad.fit_geometry(w0, h0)
        lum = float(img.astype(np.float32).mean())
        is_dark = lum < 120.0

        a_path = os.path.join(HERE, a_name)
        b_path = os.path.join(HERE, b_name)
        a_info = v2pad.make_A(src, a_path)
        b_info = v2pad.make_B(src, b_path)

        a_seam = v2pad.seam_report(a_path, y, nh)
        b_seam = v2pad.seam_report(b_path, y, nh)
        a_max = max(a_seam["seam_top"][0], a_seam["seam_bottom"][0])
        b_max = max(b_seam["seam_top"][0], b_seam["seam_bottom"][0])

        switched = False
        chosen = official
        if shot != "01v3" and is_dark and a_max > 10.0:
            chosen, switched = "B", True

        rec = {
            "shot": shot, "raw": raw, "raw_size": [w0, h0],
            "target_size": [W, H], "scale": round(scale, 4),
            "scaled_size": [nw, nh], "pad_px": {"top": y, "bottom": H - nh - y},
            "mode": "normalize（仅尺寸归一，不是 S5 补留白）",
            "padded_flag": False,
            "mean_luminance_rgb": round(lum, 1), "is_dark": is_dark,
            "A_paper": {"file": a_name, "paper_rgb": a_info["paper_rgb"],
                        "seam_top": a_seam["seam_top"], "seam_bottom": a_seam["seam_bottom"]},
            "B_edge": {"file": b_name,
                       "seam_top": b_seam["seam_top"], "seam_bottom": b_seam["seam_bottom"]},
            "official": chosen, "rule": note, "switched_to_B": switched,
            "note": ("暗场图且 A 版接缝 %.2f > 10 → 按 id147 改交 B 版（%.2f）" % (a_max, b_max))
                    if switched else "A 版接缝 %.2f，未触发暗场切换" % a_max,
        }
        pad_log.append(rec)
        seams[shot] = {"A": a_seam, "B": b_seam, "A_max": round(a_max, 2),
                       "B_max": round(b_max, 2), "official": chosen}
        print("%-5s raw=%dx%d lum=%.1f dark=%s | A=%.2f/%.2f B=%.2f/%.2f -> official=%s%s"
              % (shot, w0, h0, lum, is_dark,
                 a_seam["seam_top"][0], a_seam["seam_bottom"][0],
                 b_seam["seam_top"][0], b_seam["seam_bottom"][0],
                 chosen, " (SWITCHED)" if switched else ""), flush=True)

    # 01 v2 → v3 明度/暗部量化（风格漂移客观佐证；v3 用原始 probe 图，v2 用官方 B 版）
    style = {
        "v2_official_B": brightness_stats(os.path.join(HERE, "ep03_base_01_kontext_v2_final_edgepad.png")),
        "v3_raw_probe": brightness_stats(os.path.join(HERE, "ep03_base_01_kontext_v3_probe.png")),
    }
    style["delta"] = {
        "mean_luminance": round(style["v3_raw_probe"]["mean_luminance"]
                                - style["v2_official_B"]["mean_luminance"], 1),
        "dark_pixel_pct_lt80": round(style["v3_raw_probe"]["dark_pixel_pct_lt80"]
                                     - style["v2_official_B"]["dark_pixel_pct_lt80"], 1),
        "bright_pixel_pct_gt200": round(style["v3_raw_probe"]["bright_pixel_pct_gt200"]
                                        - style["v2_official_B"]["bright_pixel_pct_gt200"], 1),
    }
    print("style stats:", json.dumps(style, ensure_ascii=False), flush=True)

    with open(os.path.join(HERE, "ep03_kontext_v3_pad_log.json"), "w", encoding="utf-8") as f:
        json.dump(pad_log, f, ensure_ascii=False, indent=2)
    with open(os.path.join(HERE, "ep03_kontext_v3_seam_report.json"), "w", encoding="utf-8") as f:
        json.dump({"unit": "相邻 6 行 RGB 均差（越小接缝越不可见）",
                   "threshold_dark_switch": "暗场(mean_lum<120) 且 A_max>10 → 改交 B",
                   "shots": seams}, f, ensure_ascii=False, indent=2)
    with open(os.path.join(HERE, "ep03_kontext_v3_style_report.json"), "w", encoding="utf-8") as f:
        json.dump({"purpose": "01 v2→v3 夜色加深的客观量化，兼作风漂移佐证（人眼验收为准）",
                   "stats": style}, f, ensure_ascii=False, indent=2)
    print("pad_log / seam_report / style_report written", flush=True)


if __name__ == "__main__":
    main()
