#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 修片版拼合（接 wb id=205/206 放行 + id=303 催办，2026-11-19）。

原则：不重渲、不重算母带、不重写字幕、不覆盖旧成片。
  - 视频：concat_ep03.txt 的 14 镜 shots（其中 s3_1/s6_1/s7_1/s9_1/s10_1
          是 11-15 修片后重渲版，其余 9 镜复用原 shots）
  - 音频：原 ep03_master.wav（旁白母带 + BGM 垫床 + loudnorm，11-15 00:21）
  - 字幕：原 subs_ep03.ass（包内相对路径 + cwd=BASE，沿用 Windows 兼容修复）
  - 输出：ep03_final_fix5.mp4（根目录新文件名，旧 ep03_final.mp4 原地不动）
封装参数逐项照抄 build_ep03.py 总封装段，不做任何创作性改动。
"""
import hashlib
import json
import os
import subprocess
import sys
import time

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

HERE = os.path.dirname(os.path.abspath(__file__))
PKG = os.path.join(HERE, "ep03_package", "ep03_package")
SHOTS = os.path.join(PKG, "shots")
CONCAT = os.path.join(PKG, "concat_ep03.txt")
MASTER = os.path.join(PKG, "ep03_master.wav")
ASS = os.path.join(PKG, "subs_ep03.ass")
OUT = os.path.join(HERE, "ep03_final_fix5.mp4")
OLD = os.path.join(PKG, "ep03_final.mp4")
TOTAL = 1520.32
FIX_SHOTS = ("s3_1", "s6_1", "s7_1", "s9_1", "s10_1")
ALL_SHOTS = ("s1_1", "s1_2", "s2_1", "s3_1", "s4_1", "s5_1", "s6_1",
             "s7_1", "s7_2", "s7_3", "s8_1", "s8_2", "s9_1", "s10_1")


def sha(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for c in iter(lambda: f.read(1 << 20), b""):
            h.update(c)
    return h.hexdigest()


def main():
    t0 = time.time()
    assert os.path.exists(CONCAT), "concat 清单缺失"
    assert os.path.exists(MASTER) and os.path.exists(ASS), "母带或字幕缺失"

    # 1) 硬校验：14 镜齐全、编码一致、五镜是修片后时间戳
    manifest = {"shots": {}, "master": {}, "ass": {}, "old_final": {}}
    for n in ALL_SHOTS:
        p = os.path.join(SHOTS, n + ".mp4")
        assert os.path.exists(p), "缺镜 " + n
        pr = subprocess.run(
            ["ffprobe", "-v", "error", "-select_streams", "v:0",
             "-show_entries", "stream=codec_name,width,height,r_frame_rate,pix_fmt",
             "-of", "json", p], capture_output=True, text=True)
        st = json.loads(pr.stdout)["streams"][0]
        assert (st["codec_name"], st["width"], st["height"],
                st["r_frame_rate"], st["pix_fmt"]) == \
               ("h264", 1280, 720, "30/1", "yuv420p"), (n, st)
        stat = os.stat(p)
        manifest["shots"][n] = {
            "bytes": stat.st_size, "mtime": int(stat.st_mtime), "sha256": sha(p),
            "probe": st,
        }
    # 五镜必须是 11-15 08:40 之后（修片重渲），其余 9 镜必须是 11-15 00:30 之前（原版）
    import datetime
    for n in FIX_SHOTS:
        mt = datetime.datetime.fromtimestamp(manifest["shots"][n]["mtime"])
        assert mt >= datetime.datetime(2026, 11, 15, 8, 40), (n, str(mt))
    for n in ALL_SHOTS:
        if n in FIX_SHOTS:
            continue
        mt = datetime.datetime.fromtimestamp(manifest["shots"][n]["mtime"])
        assert mt <= datetime.datetime(2026, 11, 15, 0, 30), (n, str(mt))
    for key, p in (("master", MASTER), ("ass", ASS), ("old_final", OLD)):
        stat = os.stat(p)
        manifest[key] = {"path": p, "bytes": stat.st_size,
                         "mtime": int(stat.st_mtime), "sha256": sha(p)}
    print("PRECHECK 14 shots OK / 5 fixed shots fresh / 9 originals untouched", flush=True)
    print("PRECHECK master %d B  ass %d B  old_final %d B" %
          (manifest["master"]["bytes"], manifest["ass"]["bytes"],
           manifest["old_final"]["bytes"]), flush=True)

    # 2) 复用 concat 清单，逐行确认文件都存在
    lines = [l.strip() for l in open(CONCAT, encoding="utf-8") if l.strip()]
    assert len(lines) == 14, ("concat 行数", len(lines))
    for l in lines:
        p = l.split("file '", 1)[1].rstrip("'")
        assert os.path.exists(p), ("concat 指向不存在", p)

    # 3) 封装：参数逐项照抄 build_ep03.py，仅输出文件名不同
    cmd = ["ffmpeg", "-hide_banner", "-nostdin", "-y",
           "-f", "concat", "-safe", "0", "-i", CONCAT, "-i", MASTER,
           "-vf", "ass=subs_ep03.ass:fontsdir=fonts",
           "-c:v", "libx264", "-pix_fmt", "yuv420p",
           "-x264-params", "colorprim=bt709:transfer=bt709:colormatrix=bt709",
           "-color_range", "tv", "-crf", "17",
           "-c:a", "aac", "-b:a", "192k", "-t", str(TOTAL), OUT]
    print("ASSEMBLE start ... (14 shots + master + ass)", flush=True)
    r = subprocess.run(cmd, cwd=PKG, capture_output=True, text=True,
                       encoding="utf-8", errors="replace")
    if r.returncode != 0:
        print("FFMPEG FAILED rc=%d" % r.returncode, flush=True)
        print(r.stderr[-3000:], flush=True)
        raise SystemExit(1)
    print("ASSEMBLE done %.1fs" % (time.time() - t0), flush=True)

    # 4) 终验：时长/编码/字节/hash；确认旧成片与母带/字幕未被改动
    probe = json.loads(subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries",
         "stream=codec_name,codec_type,width,height,r_frame_rate,duration,"
         "color_range,color_space,color_transfer,color_primaries,pix_fmt",
         "-show_entries", "format=duration,size", "-of", "json", OUT],
        capture_output=True, text=True).stdout)
    vst = next(s for s in probe["streams"] if s["codec_type"] == "video")
    ast = next(s for s in probe["streams"] if s["codec_type"] == "audio")
    vdur, adur = float(vst["duration"]), float(ast["duration"])
    print("VERIFY video %.2fs audio %.2fs target %.2fs" % (vdur, adur, TOTAL), flush=True)
    assert abs(vdur - TOTAL) < 1.0 and abs(adur - TOTAL) < 1.0, (vdur, adur)
    assert (vst["codec_name"], vst["width"], vst["height"],
            vst["r_frame_rate"]) == ("h264", 1280, 720, "30/1"), vst
    assert ast["codec_name"] == "aac", ast
    for key, p in (("master", MASTER), ("ass", ASS), ("old_final", OLD)):
        now = {"bytes": os.path.getsize(p), "sha256": sha(p)}
        assert now["bytes"] == manifest[key]["bytes"] and \
               now["sha256"] == manifest[key]["sha256"], (key, "被改动")
    print("VERIFY master/ass/old_final sha256 unchanged", flush=True)

    out = {
        "output": os.path.basename(OUT),
        "bytes": os.path.getsize(OUT),
        "sha256": sha(OUT),
        "video_duration_s": vdur, "audio_duration_s": adur,
        "video": vst, "audio": ast,
        "inputs": manifest,
        "elapsed_s": round(time.time() - t0, 1),
        "note": "复用 14 镜 shots + 原母带 + 原 ass；未重渲、未重算母带、未改字幕、未覆盖旧成片",
    }
    json.dump(out, open(os.path.join(HERE, "ep03_fix5_assemble_report.json"), "w",
                        encoding="utf-8"), ensure_ascii=False, indent=2)
    print("DONE %s  %d B  sha256=%s" % (out["output"], out["bytes"], out["sha256"]),
          flush=True)


if __name__ == "__main__":
    main()
