#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Short 1 v2（id=383）：只重渲 0.8s 片头标题卡（加「帝」字），
其余 12 段画面 mp4 + ASS + AAC 音频流逐字节复用 v1，拼 ep03_short1_v2.mp4。
"""
import hashlib, json, os, subprocess

BASE = r"D:/Download/muse_exchange"
PKG = os.path.join(BASE, "ep03_package", "ep03_package")
TMP = os.path.join(BASE, "ep03_short1_tmp")
FR = json.load(open(os.path.join(BASE, "ep03_short1_frames_report.json"), encoding="utf-8"))
ASS = os.path.join(BASE, "ep03_short1_subs.ass")
AAC = os.path.join(TMP, "aac0p0.m4a")      # v1 已实测 I=-14.30 / TP=-1.18 的音频流
OUT = os.path.join(BASE, "ep03_short1_v2.mp4")


def sha(p):
    return hashlib.sha256(open(p, "rb").read()).hexdigest()


def run(a, cwd=None):
    r = subprocess.run(a, capture_output=True, text=True, encoding="utf-8", errors="replace", cwd=cwd)
    assert r.returncode == 0, (" ".join(a)[:200], (r.stderr or "")[-800:])
    return r


def before_map():
    d = {}
    for ln in open(os.path.join(BASE, "v2_sha_before.txt"), encoding="utf-8"):
        h, p = ln.strip().split(None, 1)
        d[p.lstrip("*")] = h
    return d


def main():
    b = before_map()
    aac_key = [k for k in b if k.endswith("/" + os.path.basename(AAC))][0]
    assert sha(AAC) == b[aac_key], "AAC 音频流被改动"
    assert sha(ASS) == b["ep03_short1_subs.ass"], "ASS 字幕被改动"
    # 1) 只重渲片头 0.8s
    seg0 = os.path.join(TMP, "seg00.mp4")
    run(["ffmpeg", "-v", "error", "-y", "-loop", "1", "-framerate", "30", "-t", "0.800",
         "-i", os.path.join(BASE, "ep03_short1_frames", "00_intro.png"),
         "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "17", "-r", "30", "-an", seg0])
    # 2) 其余 12 段逐字节核对（未被触碰）
    segs = []
    for i in range(len(FR["scenes"])):
        p = os.path.join(TMP, "seg%02d.mp4" % i)
        key = p.replace("\\", "/").split("/muse_exchange/")[-1]
        if i > 0:
            assert sha(p) == b[key], ("SEG CHANGED", i, key)
        segs.append(p)
    print("REST 12 SEGMENTS BYTE-IDENTICAL PASS", flush=True)
    # 3) concat + 烧字幕（ASS 文件 v1 已拷进 PKG，内容未变）
    lst = os.path.join(TMP, "concat_v2.txt")
    with open(lst, "w", encoding="utf-8") as f:
        for p in segs:
            f.write("file '%s'\n" % p.replace("\\", "/"))
    raw = os.path.join(TMP, "video_raw_v2.mp4")
    run(["ffmpeg", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", lst,
         "-c", "copy", raw])
    sub = os.path.join(TMP, "video_sub_v2.mp4")
    run(["ffmpeg", "-v", "error", "-y", "-i", raw,
         "-vf", "ass=ep03_short1_subs.ass:fontsdir=fonts",
         "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "17", "-r", "30", "-an", sub],
        cwd=PKG)
    # 4) 原 AAC 流直接 mux
    run(["ffmpeg", "-v", "error", "-y", "-i", sub, "-i", AAC,
         "-map", "0:v:0", "-map", "1:a:0", "-c", "copy", "-shortest", OUT])
    rep = {"out": OUT, "bytes": os.path.getsize(OUT), "sha256": sha(OUT),
           "aac_reused_sha256": sha(AAC), "ass_reused_sha256": sha(ASS),
           "only_intro_rerendered": True, "rest_12_segments_identical": True,
           "note": "id=383：仅 0.0–0.8s 片头标题第二行由「不知所终」改「帝不知所终」；其余素材逐字节复用 v1"}
    json.dump(rep, open(os.path.join(BASE, "ep03_short1_v2_build_report.json"), "w",
                        encoding="utf-8"), ensure_ascii=False, indent=2)
    print("BUILT", OUT, rep["bytes"], "sha", rep["sha256"], flush=True)

if __name__ == "__main__":
    main()
