#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 kontext part2 · 补边归一（花酱 wb 箱 id147 第 3 条）

规则：
- 01：用已批准的 B 版（边缘自适应补边）——对 01 重修 v2 出 B 版；
       part1 的 B 版原样保留作对照，不覆盖。
- 02/03/07：默认 A 版（S5 normalize 纸色补边）；逐张量化接缝，
       若为暗场图且 A 版出现可见接缝，则改交 B 版并在标注里写明。
- 全部：等比缩放（可放大），零裁切零变形，输出严格 1536x864。
- 逐张写 pad log + seam 量化，供花酱复核。
"""
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


s5 = _load("s5", os.path.join(HERE, "ep03_s5_pad.py"))
edge = _load("edge", os.path.join(HERE, "ep03_edge_pad.py"))


def fit_geometry(w, h):
    scale = min(W / w, H / h)
    nw, nh = int(round(w * scale)), int(round(h * scale))
    y = (H - nh) // 2
    return scale, nw, nh, y


def make_A(src, out):
    """A 版：S5 纸色补边（全图高亮低饱和中位色），与 part1 同方案。"""
    _, w0, h0 = s5.load_rgb(src)
    scale, nw, nh, y = fit_geometry(w0, h0)
    info = s5.pad_one(src, out, "center", scale, 0.0)
    return info


def make_B(src, out):
    """B 版：逐列边缘色延伸（已批准的夜景/暗场方案）。"""
    img, w, h = edge.load_rgb(src)
    scale, nw, nh, y = fit_geometry(w, h)
    small = edge.scale_rgb(img, w, h, nw, nh)
    canvas = np.zeros((H, W, 3), dtype=np.float32)
    canvas[y:y + nh] = small.astype(np.float32)
    rng = np.random.default_rng(20261112)
    top = np.median(small[0:8], axis=0).astype(np.float32)
    bot = np.median(small[-8:], axis=0).astype(np.float32)
    for yy in range(y):
        canvas[yy] = top + rng.normal(0, 1.0, (W, 1))
    for yy in range(y + nh, H):
        canvas[yy] = bot + rng.normal(0, 1.0, (W, 1))
    edge.save_rgb(np.clip(canvas, 0, 255).astype(np.uint8), out)
    return {"scaled_size": [nw, nh], "scale": round(scale, 4),
            "pad_px": {"top": y, "bottom": H - nh - y},
            "method": "B 边缘自适应：逐列取紧邻 8 行中位 + σ=1 噪声"}


def seam_report(path, y, nh):
    canvas, _, _ = edge.load_rgb(path)
    return {
        "seam_top": edge.seam_diff(canvas, y, "top"),
        "seam_bottom": edge.seam_diff(canvas, y + nh, "bottom"),
    }


def main():
    # (镜头, 原始图, 交付 A 文件名, 交付 B 文件名, 官方交付版, 说明)
    jobs = [
        ("01v2", "ep03_base_01_kontext_v2_probe.png",
         "ep03_base_01_kontext_v2_final_paperpad.png",
         "ep03_base_01_kontext_v2_final_edgepad.png",
         "B", "01 重修：按 id147 用已批准的 B 版（边缘自适应）；A 版仅作对照"),
        ("02", "ep03_base_02_kontext.png",
         "ep03_base_02_kontext_final_paperpad.png",
         "ep03_base_02_kontext_final_edgepad.png",
         "A", "02 灰烬碑：默认 A 版纸色"),
        ("03", "ep03_base_03_kontext.png",
         "ep03_base_03_kontext_final_paperpad.png",
         "ep03_base_03_kontext_final_edgepad.png",
         "A", "03 案头：默认 A 版纸色"),
        ("07", "ep03_base_07_kontext.png",
         "ep03_base_07_kontext_final_paperpad.png",
         "ep03_base_07_kontext_final_edgepad.png",
         "A", "07 残卷：默认 A 版纸色"),
    ]

    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 = 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 = make_A(src, a_path)
        b_info = make_B(src, b_path)

        a_seam = seam_report(a_path, y, nh)
        b_seam = 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])

        # id147 判定：暗场图 + A 版有可见接缝（>10）→ 改用 B 版并注明
        switched = False
        chosen = official
        if shot != "01v2" and is_dark and a_max > 10.0:
            chosen = "B"
            switched = 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": 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=%sx%d lum=%.1f dark=%s | A_seam=%.2f/%.2f B_seam=%.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)

    with open(os.path.join(HERE, "ep03_kontext_v2_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_v2_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)
    print("pad_log / seam_report written", flush=True)


if __name__ == "__main__":
    main()
