#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 fix9 拼合（接 wb id=372 第3步）。
14镜 concat（沿用 fix8 的 shots_fix8，画面一字不动）+ 成片混音 master_v5 + fix9 ASS 烧录。
  - 视频：shots_fix8 的 14 镜（fix8 重渲 5 镜 + 复用 9 镜），本轮不重渲
  - 音频：ep03_master_v5.wav（旁白母带 v5 + BGM 垫床，本轮 ep03_fix9_make_master.py 生成）
  - 字幕：subs_ep03_fix9.ass（花酱重切，458 cue，末条 25:24.32，总长 1524.32s）
  - 输出：ep03_final_fix9.mp4（根目录新文件，fix8 成片原地不动）
封装参数逐项照抄 ep03_assemble_fix8.py 终编段，仅换 master/ass/out/TOTAL。
"""
import hashlib, json, os, subprocess, sys, 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_fix8")
CONCAT = os.path.join(PKG, "concat_ep03_fix9.txt")
_all_order = ("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")
with open(CONCAT, "w", encoding="utf-8") as _f:
    for _n in _all_order:
        _f.write("file '%s'\n" % os.path.join(SHOTS, _n + ".mp4"))
MASTER = os.path.join(PKG, "ep03_master_v5.wav")
# 烧用 ASS：根目录花酱所传版本复制到 PKG（cwd=PKG 相对路径引用），一字不改
ASS_SRC = os.path.join(HERE, "subs_ep03_fix9.ass")
ASS = os.path.join(PKG, "subs_ep03_fix9.ass")
OUT = os.path.join(HERE, "ep03_final_fix9.mp4")
TOTAL = 1524.32
ALL = _all_order

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()
    # 字幕复制到 PKG（如内容不同则覆盖，保证烧用的是花酱所传版本）
    src_sha = sha(ASS_SRC)
    if not os.path.exists(ASS) or sha(ASS) != src_sha:
        import shutil
        shutil.copy2(ASS_SRC, ASS)
    assert sha(ASS) == src_sha, "烧用 ASS 与根目录版本不符"
    for p in (CONCAT, MASTER, ASS):
        assert os.path.exists(p), "缺文件 " + p
    manifest = {"shots": {}, "master": {}, "ass": {}}

    # 1) 14 镜齐全、编码一致；画面沿用 fix8（不重渲），加总应接近旧 TOTAL 1525.92
    vdur_sum = 0.0
    for n in ALL:
        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,duration",
            "-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)
        vdur_sum += float(st["duration"])
        stat = os.stat(p)
        manifest["shots"][n] = {"bytes": stat.st_size, "sha256": sha(p),
                                "duration_s": float(st["duration"])}
    print("PRECHECK 14 shots OK (沿用 fix8，未重渲)", flush=True)
    print("video concat sum %.2fs vs audio TOTAL %.2fs (diff %.2f)" %
          (vdur_sum, TOTAL, vdur_sum - TOTAL), flush=True)
    assert abs(vdur_sum - 1525.92) < 1.0, ("14镜加总非fix8口径", vdur_sum)

    for key, p in (("master", MASTER), ("ass", ASS)):
        stat = os.stat(p)
        manifest[key] = {"path": p, "bytes": stat.st_size,
                         "mtime": int(stat.st_mtime), "sha256": sha(p)}
    # master_v5 sha 与本轮 make_master 报告一致
    rep = json.load(open(os.path.join(HERE, "ep03_fix9_master_v5_report.json"), encoding="utf-8"))
    assert manifest["master"]["sha256"] == rep["sha256"], "master_v5 sha 与报告不符"
    assert not rep.get("tp_over_minus1"), "master_v5 真峰超 -1，按工单不硬拼"
    # 旁白母带 v5 sha 与 fix9 step2 报告一致
    s2 = json.load(open(os.path.join(HERE, "ep03_fix9_master_v5_report.json"), encoding="utf-8"))
    print("PRECHECK master %d B (%s) ass %d B" %
          (manifest["master"]["bytes"], manifest["master"]["sha256"][:12],
           manifest["ass"]["bytes"]), flush=True)

    # 2) 封装：参数逐项照抄，仅换 master/ass/out/TOTAL
    cmd = ["ffmpeg", "-hide_banner", "-nostdin", "-y",
           "-f", "concat", "-safe", "0", "-i", CONCAT, "-i", MASTER,
           "-vf", "ass=subs_ep03_fix9.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 fix8 + master_v5 + fix9 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)

    # 3) 终验
    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

    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,
        "master_report": rep, "elapsed_s": round(time.time() - t0, 1),
        "note": "14镜沿用fix8不重渲 + master_v5(旁白v5+BGM) + fix9 ass(花酱重切458cue)；视频加总1526.37按 -t 1524.32 截断，p62/p67后画面与音频存在约1.1-1.6s轻微错位(画面对齐v4时长、母带短1.60s)",
    }
    json.dump(out, open(os.path.join(HERE, "ep03_fix9_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()
