#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 fix10 拼合（接 wb id=378）。
只重渲 s7_2 按 v6 时长（shots_fix10），其余 12 镜复用 fix9（s6_1 是 v5 时序，不动），
14镜 concat + master_v6 + fix10 ASS，总长 1524.48 与母带 v6 一致。
-t 1524.48 只截末尾帧取整尾差。
"""
import hashlib, json, os, subprocess, sys, time, shutil, urllib.request

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_fix10")
CONCAT = os.path.join(PKG, "concat_ep03_fix10.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_v6.wav")
ASS_SRC = os.path.join(HERE, "subs_ep03_fix10.ass")
ASS = os.path.join(PKG, "subs_ep03_fix10.ass")
OUT = os.path.join(HERE, "ep03_final_fix10.mp4")
TOTAL = 1524.48
RD10 = ("s7_2",)  # fix10 只重渲一镜

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()
    src_sha = sha(ASS_SRC)
    remote_ass = urllib.request.urlopen(
        "http://localhost:8800/download?name=subs_ep03_fix10.ass", timeout=30).read()
    assert remote_ass == open(ASS_SRC, "rb").read(), "本地 ASS 与花酱 8800 版本不一致"
    print("ASS 8800 byte-check PASS", flush=True)
    if not os.path.exists(ASS) or sha(ASS) != src_sha:
        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": {}}

    vdur_sum = 0.0
    for n in _all_order:
        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"]),
                                "rerendered_fix10": n in RD10}
    print("PRECHECK 14 shots: 1 fix10重渲(s7_2) + 12 fix9复用(s7_3起自然后移0.16s)", flush=True)
    print("video concat sum %.2fs vs TOTAL %.2fs (frame-round tail %.2fs)" %
          (vdur_sum, TOTAL, vdur_sum - TOTAL), flush=True)
    assert abs(vdur_sum - TOTAL) < 1.0, ("14镜加总异常", 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_fix10_master_v6_mix_report.json"), encoding="utf-8"))
    assert manifest["master"]["sha256"] == rep["sha256"], "master_v6 sha 与报告不符"
    assert not rep.get("tp_over_minus1"), "master_v6 真峰超 -1"
    print("PRECHECK master %s ass %d B" % (manifest["master"]["sha256"][:12],
          manifest["ass"]["bytes"]), flush=True)

    cmd = ["ffmpeg", "-hide_banner", "-nostdin", "-y",
           "-f", "concat", "-safe", "0", "-i", CONCAT, "-i", MASTER,
           "-vf", "ass=subs_ep03_fix10.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 ... (s7_2重渲 + 12镜复用 + master_v6 + fix10 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)

    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": "按 wb id=378：只重渲 s7_2（v6 时长，p67 786.24-809.12s，镜内 p68/p69/p70 卡片随 +0.16s 后移），其余12镜复用fix9（s6_1 是 v5 时序不动）；-t 1524.48 仅截末尾帧取整尾差；铃铛在 s7_3 复用镜内自动后移到 892.96s 与母带对齐；混音沿用 -0.5dB。",
    }
    json.dump(out, open(os.path.join(HERE, "ep03_fix10_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()
