#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 fix7 拼合（接 wb id=345 放行）。
沿用 fix6 拼合法：14 镜 concat + 成片混音 master_v4 + fix7 ASS，不重渲、不重算母带。
  - 视频：14 镜全部就绪——本轮 fix7 重渲 10 镜（11-22），复用 3 镜（11-15）+ s1_1（11-20）。
  - 音频：ep03_master_v4.wav（旁白 v4 + BGM 垫床 + 末级 loudnorm，本轮 ep03_fix7_make_master.py 生成）
  - 字幕：subs_ep03_fix7.ass（458 cue，v1.5 + 六段定稿，钟声 894.40s）
  - 输出：ep03_final_fix7.mp4（根目录新文件，旧版原地不动）
封装参数逐项照抄 build_ep03_fix7.py / ep03_assemble_fix6.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")
CONCAT = os.path.join(PKG, "concat_ep03.txt")
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_fix7.mp4")
TOTAL = 1525.92
# 本轮 fix7 重渲 10 镜（11-22）；其余 4 镜复用
RD7 = ("s1_2", "s2_1", "s3_1", "s4_1", "s5_1", "s6_1", "s7_1", "s7_3", "s8_1", "s10_1")
REUSE = ("s7_2", "s8_2", "s9_1")  # 11-15 复用镜
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, 22, 0, 0), (n, "fix7 重渲镜时间戳异常", str(mt))
        elif n in REUSE:
            assert mt < datetime.datetime(2026, 11, 16), (n, "复用镜时间戳异常", str(mt))
        else:  # s1_1 (11-20 fix6)
            assert datetime.datetime(2026, 11, 20, 0, 0) <= mt < datetime.datetime(2026, 11, 21), (n, "s1_1 时间戳异常", str(mt))
        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 / 10 fix7重渲 + 3 复用 + s1_1(fix6)", 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 与报告不符"
    # 字幕 sha 与已传根目录的 fix7 ass 一致
    root_assoc = os.path.join(HERE, "subs_ep03_fix7.ass")
    if os.path.exists(root_assoc):
        assert sha(root_assoc) == manifest["ass"]["sha256"], "字幕 ass 与根目录版本不符"
    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 + master_v4 + fix7 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
    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镜(10镜fix7重渲+3镜复用+s1_1 fix6) + master_v4 + fix7 ass；未重渲复用镜、未重算母带、未改字幕",
    }
    json.dump(out, open(os.path.join(HERE, "ep03_fix7_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()
