#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 S5 程序化补留白（按花酱 wb 箱 id139 四条硬条件实现）

  1) 只加边、不裁切不拉伸：
     - 原图整幅等比缩放（保持宽高比，绝不做非等比变形），一个像素都不裁掉；
     - 只在空出来的区域填「边」，原图区域像素原样保留；
     - 输出画布严格 1536x864（交付规格不变）。
  2) 垫色取纸色：从原图自身高亮像素中位采样，不用纯白/纯灰硬填。
  3) 单独标注：每次垫图追加一条 JSON 记录，供交付清单列明「哪张垫过」。
  4) 内容本身有问题（主体裁切/画错/缺元素）→ 判重画，不垫（本脚本不处理，由人工判定）。

接缝默认硬边（最忠实「只加边」）；补边区叠加极轻纸纹（±2，固定种子可复现），
避免大片死色块。所有处理都写进标注，供花酱复核。

用法：
  # 仅尺寸归一（引擎出 1536x896，等比缩到高 864 后左右补纸色边，不裁切不变形）
  python ep03_s5_pad.py --in raw.png --out norm.png --shot 01 --mode normalize \
      --reason "仅尺寸归一" --log ep03_s5_pad_log.json
  # S5 补留白（主体铺满时缩小腾出左侧卡片区 + 底部字幕区）
  python ep03_s5_pad.py --in raw.png --out padded.png --shot 01 --side both --scale 0.70 \
      --reason "主体铺满、左侧无对照卡区、底部字幕区被占" --log ep03_s5_pad_log.json
  python ep03_s5_pad.py --in raw.png --probe     # 只打印采样纸色与建议参数

⚠ 「只加边、不裁切不拉伸」的落地解释：原图整幅**等比缩放**（保持宽高比，
   绝非非等比拉伸变形），一个像素都不裁掉，再在空出的区域补纸色边。
   因 sd-cli 会输出 1536x896 而交付规格是 1536x864，即使不做补留白也必须
   走一次等比缩放+补边做尺寸归一。两种模式都逐张写进标注，供花酱复核。
"""
import argparse
import json
import os
import subprocess
import sys

import numpy as np

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

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


def load_rgb(path):
    """用 ffmpeg 解码任意图片为 rgb24，返回 (h, w, 3) uint8。"""
    p = subprocess.run(
        [FF, "-v", "error", "-i", path, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
        capture_output=True,
    )
    n = len(p.stdout)
    if n == 0:
        raise RuntimeError("ffmpeg 解码失败: %s" % path)
    # 用 ffprobe 拿尺寸更稳；这里按已知 1536x864 优先，否则探测
    w, h = W, H
    if n != W * H * 3:
        info = subprocess.run(
            [r"D:\tools\ffmpeg\bin\ffprobe.exe", "-v", "error",
             "-select_streams", "v:0", "-show_entries", "stream=width,height",
             "-of", "csv=p=0", path],
            capture_output=True, text=True,
        ).stdout.strip()
        try:
            w, h = [int(x) for x in info.split(",")[:2]]
        except Exception:
            raise RuntimeError("尺寸未知且非 1536x864: %s (%d bytes)" % (path, n))
    if n != w * h * 3:
        raise RuntimeError("解码字节数不匹配: %s got %d expect %d" % (path, n, w * h * 3))
    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("写图失败: %s %s" % (path, (p.stderr or b"")[-300:]))


def sample_paper_color(img):
    """纸色 = 画面中「高亮低饱和」像素的中位 RGB（水彩纸暖白），而非纯白。"""
    f = img.astype(np.float32)
    lum = f.mean(axis=2)
    mx = f.max(axis=2)
    mn = f.min(axis=2)
    sat = mx - mn
    # 亮度高、饱和度低 => 纸/留白区域
    mask = (lum > np.percentile(lum, 60)) & (sat < 42)
    px = img[mask]
    if len(px) < 1000:
        mask = lum > np.percentile(lum, 75)
        px = img[mask]
    med = np.median(px, axis=0)
    return tuple(int(round(v)) for v in med), int(mask.sum())


def pad_one(src_path, out_path, side, scale, paper_noise=2.0):
    img, w, h = load_rgb(src_path)
    paper, nsample = sample_paper_color(img)

    # sd-cli 会把非 64 倍数的高度上对齐（864 -> 896），故源图未必是 1536x864。
    # 这里按「源图实际尺寸」等比缩放，绝不裁切、绝不非等比拉伸；
    # 若给定 scale 会超出目标画布，自动收紧到刚好装得下。
    nw, nh = int(round(w * scale)), int(round(h * scale))
    if nw > W or nh > H:
        fit = min(W / nw, H / nh)
        nw, nh = int(nw * fit), int(nh * fit)
    nw, nh = max(1, nw), max(1, nh)

    # 等比缩小原图（ffmpeg area 插值，保持宽高比，不裁切、不拉伸）
    small_bytes = subprocess.run(
        [FF, "-v", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
         "-s", "%dx%d" % (w, h), "-i", "-", "-vf", "scale=%d:%d:flags=area" % (nw, nh),
         "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
        input=img.tobytes(), capture_output=True,
    ).stdout
    if len(small_bytes) != nw * nh * 3:
        raise RuntimeError("缩放失败: got %d expect %d" % (len(small_bytes), nw * nh * 3))
    small = np.frombuffer(small_bytes, dtype=np.uint8).reshape(nh, nw, 3).copy()

    # 纸色底 + 极轻纸纹（固定种子，可复现；只在补边区可见）
    base = np.empty((H, W, 3), dtype=np.float32)
    base[:] = np.array(paper, dtype=np.float32)
    if paper_noise > 0:
        rng = np.random.default_rng(20261112)
        base += rng.normal(0.0, paper_noise, (H, W, 1)).astype(np.float32)

    # 摆位：原图完整贴入，未裁切；空出的就是「加的边」
    if side == "left":          # 主体靠右，左侧留白
        x, y = W - nw, (H - nh) // 2
    elif side == "bottom":      # 主体靠上，底部留字幕区
        x, y = (W - nw) // 2, 0
    elif side == "both":        # 主体右上，左侧 + 底部都留白
        x, y = W - nw, 0
    elif side == "right":
        x, y = 0, (H - nh) // 2
    elif side == "center":
        x, y = (W - nw) // 2, (H - nh) // 2
    else:
        raise ValueError("side 必须是 left/bottom/both/right/center")

    canvas = np.clip(base, 0, 255).astype(np.uint8)
    canvas[y:y + nh, x:x + nw] = small
    save_rgb(canvas, out_path)

    return {
        "source_size": [w, h],
        "target_size": [W, H],
        "paper_rgb": list(paper),
        "paper_sample_pixels": nsample,
        "scale": scale,
        "scaled_size": [nw, nh],
        "placement_xy": [x, y],
        "pad_px": {"left": x, "right": W - nw - x, "top": y, "bottom": H - nh - y},
        "paper_noise_sigma": paper_noise,
        "seam": "硬边（未羽化，最忠实『只加边』；如需过渡再单独处理）",
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--in", dest="src")
    ap.add_argument("--out", dest="out")
    ap.add_argument("--shot", default="")
    ap.add_argument("--side", default="both", choices=["left", "bottom", "both", "right", "center"])
    ap.add_argument("--scale", type=float, default=0.70)
    ap.add_argument("--mode", default="pad", choices=["pad", "normalize"],
                    help="pad=S5 补留白；normalize=仅尺寸归一（自动取最大可装下比例、居中补边）")
    ap.add_argument("--noise", type=float, default=2.0)
    ap.add_argument("--reason", default="")
    ap.add_argument("--log", dest="log", default="")
    ap.add_argument("--probe", action="store_true")
    a = ap.parse_args()

    if a.probe:
        img, w, h = load_rgb(a.src)
        paper, n = sample_paper_color(img)
        print("尺寸 %dx%d | 纸色 RGB=%s | 采样像素 %d" % (w, h, paper, n))
        for s in (0.70, 0.75, 0.80, 0.85):
            nw, nh = int(round(w * s)), int(round(h * s))
            if nw > W or nh > H:
                fit = min(W / nw, H / nh)
                nw, nh = int(nw * fit), int(nh * fit)
            print("  scale=%.2f -> %dx%d, 左侧留白 %d px, 底部留白 %d px (%.0f%% 高度)"
                  % (s, nw, nh, W - nw, H - nh, (H - nh) / H * 100))
        return

    if not a.src or not a.out:
        ap.error("需要 --in 与 --out（或用 --probe）")

    # normalize 模式：源图 1536x896 → 等比缩到刚好装进 1536x864（高 864 → 宽 1481），
    # 左右各补约 27px 纸色边。scale 给 1.0，由 pad_one 的自动 fit 收紧。
    if a.mode == "normalize":
        # 自动 fit 到目标画布：可缩小（sd-cli 恒出 1536x896 → 归到 864），
        # 也可放大（Pollinations 免费 kontext 实测出 1392x752 → 需放大到宽 1536）。
        # 全程等比、零裁切、零变形；空出的区域补极窄纸色边。
        _, w0, h0 = load_rgb(a.src)
        scale = min(W / w0, H / h0)
        side = "center"
    else:
        scale = a.scale
        side = a.side
    info = pad_one(a.src, a.out, side, scale, 0.0 if a.mode == "normalize" else a.noise)
    info["effective_scale"] = round(min(info["scaled_size"][0] / info["source_size"][0],
                                        info["scaled_size"][1] / info["source_size"][1]), 4)
    rec = {
        "shot": a.shot,
        "mode": a.mode,
        "raw": os.path.basename(a.src),
        "padded": os.path.basename(a.out),
        # normalize 只是规格对齐，不算「补留白」，绝不能记成垫过
        "padded_flag": a.mode == "pad",
        "side": side,
        "reason": a.reason,
        "content_ok": a.mode == "pad",
        "method": ("S5 补留白：原图整幅等比缩放 → 纸色补边 → 输出 1536x864；垫色取自原图纸色"
                   if a.mode == "pad" else
                   "仅尺寸归一：原图整幅等比缩放（自动 fit，可缩小可放大）→ 空出区域补极窄纸色边 → 输出 1536x864；不是补留白"),
        "params": info,
    }
    print(json.dumps(rec, ensure_ascii=False, indent=2))
    if a.log:
        rows = []
        if os.path.exists(a.log):
            try:
                rows = json.load(open(a.log, encoding="utf-8"))
            except Exception:
                rows = []
        rows = [r for r in rows if not (r.get("shot") == a.shot and r.get("padded") == rec["padded"])]
        rows.append(rec)
        with open(a.log, "w", encoding="utf-8") as f:
            json.dump(rows, f, ensure_ascii=False, indent=2)
        print("标注已追加: %s (%d 条)" % (a.log, len(rows)))


if __name__ == "__main__":
    main()
