#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 kontext 图的「边缘自适应补边」候选（对照 S5 的全图纸色补边）。

背景：kontext 服务端实出 1392x752，需等比放大到 1536x830 后上下各补 17px
才能归一到 1536x864。S5 的 sample_paper_color 在夜景图上取到中灰蓝
[100,103,108]（画面没有大片暖白纸区），底部深灰边与浅米地面有可见分界。

本脚本改用「逐列边缘色延伸」：上下补边的每一列颜色取自放大图紧邻的
8 行像素中位，再加 σ=1 极轻噪声。因为夜空/烟/地面在水平方向本就变化，
逐列取色能让补边与原图边缘连续，硬接缝最小。

⚠ 这是对花酱 id139 第 2 条「垫色取纸色」的一种偏离候选，仅供对比选择，
   不擅自替换已批准的 S5 版本。两版都进先验包，由花酱定。
"""
import json, os, subprocess, sys

import numpy as np

FF = r"D:\tools\ffmpeg\bin\ffmpeg.exe"
FFPROBE = r"D:\tools\ffmpeg\bin\ffprobe.exe"
W, H = 1536, 864

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


def load_rgb(path):
    info = subprocess.run([FFPROBE, "-v", "error", "-select_streams", "v:0",
                           "-show_entries", "stream=width,height", "-of", "csv=p=0", path],
                          capture_output=True, text=True).stdout.strip()
    w, h = [int(x) for x in info.split(",")[:2]]
    p = subprocess.run([FF, "-v", "error", "-i", path, "-f", "rawvideo",
                        "-pix_fmt", "rgb24", "-"], capture_output=True)
    if len(p.stdout) != w * h * 3:
        raise RuntimeError("解码失败 %s (%d bytes, %dx%d)" % (path, len(p.stdout), w, h))
    return np.frombuffer(p.stdout, dtype=np.uint8).reshape(h, w, 3).copy(), w, h


def save_rgb(arr, path):
    p = subprocess.run([FF, "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24",
                        "-s", "%dx%d" % (arr.shape[1], arr.shape[0]), "-i", "-",
                        "-frames:v", "1", path], input=arr.tobytes(), capture_output=True)
    if p.returncode != 0 or not os.path.exists(path):
        raise RuntimeError("写图失败: " + (p.stderr or b"")[-300:].decode("utf-8", "replace"))


def scale_rgb(img, w, h, nw, nh):
    p = subprocess.run([FF, "-v", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
                        "-s", "%dx%d" % (w, h), "-i", "-",
                        "-vf", "scale=%d:%d:flags=lanczos" % (nw, nh),
                        "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
                       input=img.tobytes(), capture_output=True)
    if len(p.stdout) != nw * nh * 3:
        raise RuntimeError("缩放失败")
    return np.frombuffer(p.stdout, dtype=np.uint8).reshape(nh, nw, 3).copy()


def seam_diff(canvas, y_seam, direction):
    """接缝两侧相邻 6 行均值 RGB 差（越小越连续）。"""
    if direction == "top":     # 补边在 y_seam 之上，原图在 y_seam 之下
        a = canvas[y_seam - 6:y_seam].mean(axis=(0, 1))
        b = canvas[y_seam:y_seam + 6].mean(axis=(0, 1))
    else:                       # 原图在 y_seam 之上，补边在 y_seam 之下
        a = canvas[y_seam - 6:y_seam].mean(axis=(0, 1))
        b = canvas[y_seam:y_seam + 6].mean(axis=(0, 1))
    return round(float(np.abs(a - b).mean()), 2), [int(round(v)) for v in a], [int(round(v)) for v in b]


def main():
    here = os.path.dirname(os.path.abspath(__file__))
    src = os.path.join(here, "ep03_base_01_kontext_probe.png")
    base = os.path.join(here, "ep03_base_01_kontext_final.png")   # S5 纸色补边版
    out = os.path.join(here, "ep03_base_01_kontext_final_edgepad.png")
    report_path = os.path.join(here, "ep03_kontext_seam_report.json")

    img, w, h = load_rgb(src)
    scale = min(W / w, H / h)
    nw, nh = int(round(w * scale)), int(round(h * scale))
    small = scale_rgb(img, w, h, nw, nh)
    y = (H - nh) // 2

    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)      # (W,3) 逐列
    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))
    save_rgb(np.clip(canvas, 0, 255).astype(np.uint8), out)

    base_img, _, _ = load_rgb(base)
    cand, _, _ = load_rgb(out)

    report = {
        "source": os.path.basename(src), "source_size": [w, h],
        "scaled_size": [nw, nh], "target_size": [W, H],
        "scale": round(scale, 4), "pad_px": {"top": y, "bottom": H - nh - y},
        "variants": {
            "A_paper_pad(S5 id139 approved)": {
                "file": os.path.basename(base),
                "color": "全图高亮低饱和中位 RGB [100,103,108]（夜景图上非暖白纸色）",
                "seam_top": seam_diff(base_img, y, "top"),
                "seam_bottom": seam_diff(base_img, y + nh, "bottom"),
            },
            "B_edge_adaptive(candidate, NOT approved)": {
                "file": os.path.basename(out),
                "color": "逐列取紧邻 8 行中位 + σ=1 噪声（边缘色垂直延伸）",
                "seam_top": seam_diff(cand, y, "top"),
                "seam_bottom": seam_diff(cand, y + nh, "bottom"),
            },
        },
        "note": "seam 值为 [相邻6行RGB均差, 上/下侧均值RGB, 下侧均值RGB]；数值越小接缝越不可见。B 版偏离花酱『垫色取纸色』条件，仅供对比，由花酱定夺。",
    }
    with open(report_path, "w", encoding="utf-8") as f:
        json.dump(report, f, ensure_ascii=False, indent=2)
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
