#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 fix8 拼合（接 wb id=355 派单）。
沿用 fix7 拼合法：14 镜 concat + 成片混音 master_v4 + fix7 ASS，不重渲、不重算母带。
  - 视频：14 镜全部就绪——本轮 fix8 重渲 5 镜（S7-1/S7-2/S7-3/S8-1/S8-2，11-23）到 shots_fix8，
          其余 9 镜从 fix7 的 shots/ 复制到 shots_fix8（画面一字不动）。
  - 音频：ep03_master_v4.wav（与 fix7 同一个，旁白母带 v4 一字不动）
  - 字幕：subs_ep03_fix7.ass（与 fix7 同一个，458 cue 一字不动）
  - 输出：ep03_final_fix8.mp4（根目录新文件，fix7 成片原地不动）
封装参数逐项照抄 build_ep03_fix8.py / ep03_assemble_fix7.py 终编段。
"""
import hashlib, json, os, subprocess, sys, time, datetime

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_fix8.txt")
# 生成指向 shots_fix8 的 concat（不改 fix7 的 concat_ep03.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_v4.wav")
ASS = os.path.join(PKG, "subs_ep03_fix7.ass")
OLD_MASTER = os.path.join(PKG, "ep03_master_v3.wav")
OLD_ASS = os.path.join(PKG, "subs_ep03.ass")
OLD_FINAL = os.path.join(PKG, "ep03_final.mp4")
OUT = os.path.join(HERE, "ep03_final_fix8.mp4")
TOTAL = 1525.92
# 本轮 fix8 重渲 5 镜（11-23）；其余 9 镜从 fix7 复制（画面不动）
RD7 = ("s7_1", "s7_2", "s7_3", "s8_1", "s8_2")
REUSE = ("s1_2", "s2_1", "s3_1", "s4_1", "s5_1", "s6_1", "s7_2", "s8_2", "s9_1")
ALL = ("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()
    for p in (CONCAT, MASTER, ASS):
        assert os.path.exists(p), "缺文件 " + p
    manifest = {"shots": {}, "master": {}, "ass": {}}

    # 1) 14 镜齐全、编码一致、时长加总 == TOTAL；三类镜次时间戳分层
    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)
        mt = datetime.datetime.fromtimestamp(stat.st_mtime)
        if n in RD7:
            assert mt >= datetime.datetime(2026, 11, 23, 0, 0), (n, "fix8 重渲镜时间戳异常", str(mt))
        else:  # 复用镜（从 fix7 shots 复制，mtime 为复制时刻；内容 sha 与 fix7 一致另行校验）
            pass
        manifest["shots"][n] = {"bytes": stat.st_size, "mtime": int(stat.st_mtime),
                                "sha256": sha(p), "duration_s": float(st["duration"])}
    print("PRECHECK 14 shots OK / 5 fix8重渲 + 9 复用", flush=True)
    print("video concat sum %.2fs vs TOTAL %.2fs (diff %.2f)" %
          (vdur_sum, TOTAL, vdur_sum - TOTAL), flush=True)
    assert abs(vdur_sum - TOTAL) < 1.0, ("14 镜时长加总偏离 TOTAL", vdur_sum, TOTAL)

    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)}
    rep = json.load(open(os.path.join(HERE, "ep03_fix7_master_report.json"), encoding="utf-8"))
    assert manifest["master"]["sha256"] == rep["sha256"], "master_v4 sha 与报告不符（fix8 必须与 fix7 同一个母带）"
    # 字幕 sha 与 fix7 已交付版本一致（一字不动）
    fix7_rep = os.path.join(HERE, "ep03_fix7_assemble_report.json")
    if os.path.exists(fix7_rep):
        f7 = json.load(open(fix7_rep, encoding="utf-8"))
        assert f7["inputs"]["ass"]["sha256"] == manifest["ass"]["sha256"], "字幕 ass 与 fix7 版本不符（fix8 字幕须一字不动）"
        assert f7["inputs"]["master"]["sha256"] == manifest["master"]["sha256"], "母带与 fix7 版本不符"
    print("PRECHECK master %d B (%s) ass %d B" %
          (manifest["master"]["bytes"], manifest["master"]["sha256"][:12],
           manifest["ass"]["bytes"]), flush=True)

    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)

    # 2) 封装：参数逐项照抄，仅换 master/ass/out
    cmd = ["ffmpeg", "-hide_banner", "-nostdin", "-y",
           "-f", "concat", "-safe", "0", "-i", CONCAT, "-i", MASTER,
           "-vf", "ass=subs_ep03_fix7.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 incl 5 fix8 + master_v4 + fix7 ass unchanged)", 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
    for key, p in (("old_master", OLD_MASTER), ("old_ass", OLD_ASS), ("old_final", OLD_FINAL)):
        if os.path.exists(p):
            assert sha(p) != manifest.get("master", {}).get("sha256", ""), "旧新混音撞 sha"

    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镜(5镜fix8重渲+9镜从fix7复制) + master_v4(同一母带) + fix7 ass(一字不动)；未重渲复用镜、未重算母带、未改字幕",
    }
    json.dump(out, open(os.path.join(HERE, "ep03_fix8_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()
