# -*- coding: utf-8 -*-
"""
EP03 修片检查点（wb id=202/204）：只取五镜关键帧 + 问题处放大裁切 + 前后对比，
打包交花酱复验。**不拼合、不出整片、不碰音频/字幕/母带**。

发回执前强制跑 wb_gate.py：GO 才发，REVIEW/HOLD 立刻停下等。
"""
import datetime
import hashlib
import json
import os
import subprocess
import sys
import urllib.request
import zipfile

from PIL import Image, ImageDraw

BASE = os.path.dirname(os.path.abspath(__file__))
PKG = os.path.join(BASE, "ep03_package", "ep03_package")
FR = os.path.join(PKG, "frames")
OUT = os.path.join(BASE, "_ep03_fix5_qa")
ZIP = os.path.join(BASE, "ep03_fix5_frames_for_qa.zip")
OP = urllib.request.build_opener(urllib.request.ProxyHandler({}))
SEND = "http://localhost:8801/send?box=huajiang"

SHOTS = {
    "s3_1": (21, [320.0, 329.2], (740, 40, 1280, 320), 2.0),
    "s6_1": (55, [700.0, 743.0], (40, 380, 1240, 620), 1.5),
    "s7_1": (65, [770.0, 779.4], (760, 160, 1200, 400), 2.0),
    "s9_1": (91, [1326.4, 1327.0], (660, 240, 1140, 520), 2.0),
    "s10_1": (99, [1463.0, 1466.0], (170, 190, 1110, 450), 1.5),
}
BEFORE = {
    "s3_1": "ep03_fix_before_s3_320.png",
    "s6_1": "ep03_fix_before_s6_743.png",
    "s7_1": "ep03_fix_before_s7_779.png",
    "s9_1": "ep03_p96_1327.0_newwin.png",
    "s10_1": "ep03_fix_before_s10_1463.png",
}
FPS = 30


def starts():
    dur = json.load(open(os.path.join(BASE, "ep03_durations.json"), encoding="utf-8"))
    res = json.load(open(os.path.join(BASE, "ep03_resynth_durations.json"), encoding="utf-8"))
    sd = [dur["p%03d" % i]["duration_s"] for i in range(1, 110)]
    for v in (res.values() if isinstance(res, dict) else res):
        if v.get("alt"):
            continue
        sd[int(v["id"][1:]) - 1] = v["duration_s"]
    out, t = [], 0.0
    for d in sd:
        out.append(round(t, 3))
        t += d
    return out, round(t, 2)


def sha(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            h.update(b)
    return h.hexdigest()


def frame_of(name, t0, t):
    i = int(round((t - t0) * FPS))
    p = os.path.join(FR, "%s_%04d.jpg" % (name, i))
    if not os.path.exists(p):
        raise FileNotFoundError(p)
    return Image.open(p).convert("RGB"), i, p


def main():
    os.makedirs(OUT, exist_ok=True)
    ST, TOTAL = starts()
    report = {"generated_at": datetime.datetime.now().isoformat(timespec="seconds"),
              "total_narr_s": TOTAL, "shots": {}, "audio_untouched": {}}

    # 音频/字幕未被本次只渲改写：mtime 必须早于只渲日志
    logp = os.path.join(BASE, "ep03_fix_five_render.log")
    log_mt = os.path.getmtime(logp) if os.path.exists(logp) else 0
    for rel in ["ep03_master.wav", "subs_ep03.ass", "ep03_narration_master_v2.wav"]:
        p = os.path.join(PKG, rel)
        if os.path.exists(p):
            mt = os.path.getmtime(p)
            report["audio_untouched"][rel] = {
                "bytes": os.path.getsize(p), "sha256": sha(p),
                "mtime": datetime.datetime.fromtimestamp(mt).isoformat(timespec="seconds"),
                "older_than_fix_render": mt < log_mt}

    after, crops, pairs = {}, {}, {}
    for name, (seg, times, box, scale) in SHOTS.items():
        t0 = ST[seg - 1]
        shot_mp4 = os.path.join(PKG, "shots", name + ".mp4")
        ims = []
        for t in times:
            im, i, src = frame_of(name, t0, t)
            dst = os.path.join(OUT, "fix5_%s_t%.1f.png" % (name, t))
            im.save(dst)
            ims.append((t, dst, i))
        after[name] = ims
        # 放大裁切（取该镜第二个时点，即 QA 问题帧附近）
        im, _, _ = frame_of(name, t0, times[-1])
        c = im.crop(box)
        c = c.resize((int(c.width * scale), int(c.height * scale)), Image.LANCZOS)
        cp = os.path.join(OUT, "crop_%s.png" % name)
        c.save(cp)
        crops[name] = cp
        # 前后对比（取同一问题的前帧）
        bf = os.path.join(BASE, BEFORE[name])
        pairs[name] = (bf if os.path.exists(bf) else None, ims[-1][1])
        report["shots"][name] = {
            "seg_start_s": t0, "times_s": times,
            "frame_indices": [x[2] for x in ims],
            "mp4_bytes": os.path.getsize(shot_mp4) if os.path.exists(shot_mp4) else None,
            "mp4_sha256": sha(shot_mp4) if os.path.exists(shot_mp4) else None,
            "crop_box": list(box), "crop_scale": scale}

    # 五镜总览拼图
    tw, th, cols = 640, 360, 2
    rows = len(SHOTS) * 1
    sheet = Image.new("RGB", (tw * cols, (th + 26) * len(SHOTS)), (240, 238, 230))
    d = ImageDraw.Draw(sheet)
    for r, name in enumerate(SHOTS):
        for c, (t, p, _) in enumerate(after[name]):
            sheet.paste(Image.open(p).convert("RGB").resize((tw, th), Image.LANCZOS),
                        (c * tw, r * (th + 26) + 26))
            d.text((c * tw + 5, r * (th + 26) + 6), "%s  t=%.1fs  AFTER" % (name, t), fill=(0, 0, 0))
    sp = os.path.join(OUT, "fix5_sheet.png")
    sheet.save(sp)

    # 前后对比拼图（5 行 × 2 列）
    bw, bh = 640, 360
    ba = Image.new("RGB", (bw * 2, (bh + 26) * len(SHOTS)), (240, 238, 230))
    bd = ImageDraw.Draw(ba)
    for r, name in enumerate(SHOTS):
        for c, p in enumerate(pairs[name]):
            if p and os.path.exists(p):
                ba.paste(Image.open(p).convert("RGB").resize((bw, bh), Image.LANCZOS),
                         (c * bw, r * (bh + 26) + 26))
            bd.text((c * bw + 5, r * (bh + 26) + 6),
                    "%s  %s" % (name, "BEFORE" if c == 0 else "AFTER"), fill=(0, 0, 0))
    bap = os.path.join(OUT, "fix5_before_after.png")
    ba.save(bap)

    # 改动 diff + 改后脚本副本
    dif = subprocess.run(["diff", "-u",
                          os.path.join(PKG, "build_ep03.py.bak_before_fix5_20261115"),
                          os.path.join(PKG, "build_ep03.py")],
                         capture_output=True, text=True, encoding="utf-8", errors="replace")
    open(os.path.join(OUT, "build_ep03.fix5.diff"), "w", encoding="utf-8").write(dif.stdout)
    with open(os.path.join(PKG, "build_ep03.py"), "rb") as f:
        open(os.path.join(OUT, "build_ep03.fixed.py"), "wb").write(f.read())

    readme = """# EP03 修片五镜关键帧（待花酱复验，未拼合）

接 wb id=202 / id=204。只重渲 `s3_1 / s6_1 / s7_1 / s9_1 / s10_1` 五镜，
`EP3_ONLY` + `EP3_NO_FINAL=1` 使音频、字幕、总封装全部跳过：
**没有拼合、没有出新整片、没有重写母带或 ass**。其余 9 镜沿用原 shots。

## 5 项改动
1. S3-1：标签 `(1120,120)` → `(820,100)`（起笔 x≈830，11 字不再出右沿；最终再上移 20px，
   让白底板与「湘王朱柏自焚」底板 y≈95–135 完全错开）；
   箭头 `(1120,120)→(920,210)` → `(1120,190)→(920,280)`，整条下移 70px 避开湘王红字。
2. S6-1：节点年份/副标 y 偏移 `22/52` → `42/76`，`side=-1` 年份不再被 y=480 时间线穿字；
   副标 `GRAY(120,116,108)` → `INK(43,43,46)` 提对比；
   「史书越含糊」pill `(44,540)` → `(760,44)`（左下 y≥600 实测贴烧录字幕 y≈650–690）。
3. S7-1：朝阳门整组 `(872,250)` → `(960,300)`，`dy=-36` → `dy=10`，与南京蓝标错开。
4. S9-1：紫框与标注**原本就在**（真实窗口 1326.24–1327.74s，QA 扫的 1324.7–1326.2s 偏早）；
   按分镜补画框内三艘帆船剪影，不动时间窗、不动坐标。若你认为空框可接受，回一句即撤。
5. S10-1：`card(..., "落版金句", ...)` → `title=""`；`card()` 增加空标题分支（正文 yoff 78→40），
   其余 17 处 card 均传非空 title，行为不变。

## 文件
- `fix5_sheet.png`：五镜修片后各 2 帧总览
- `fix5_before_after.png`：逐镜前/后对比
- `fix5_<name>_t<秒>.png`：10 张关键帧全分辨率
- `crop_<name>.png`：5 张问题处放大裁切
- `build_ep03.fix5.diff` / `build_ep03.fixed.py`：改动与改后脚本
- `manifest.json`：五镜 mp4 字节/sha、帧号、音频/字幕未改动证明、gate 记录

## 检查点
**验过之前不拼合、不出整片。** 你验过放行后我才做：拼合 → 复测三项（成片 mp4 实测）→
分块回传 + `subs_ep03.ass` → 回执。每步开工前跑 `wb_gate.py` 读 wb 箱。
"""
    open(os.path.join(OUT, "README_EP03_修片五镜_待验.md"), "w", encoding="utf-8").write(readme)
    report["gate_log_tail"] = []
    gl = os.path.join(BASE, "wb_gate_log.jsonl")
    if os.path.exists(gl):
        report["gate_log_tail"] = [json.loads(x) for x in open(gl, encoding="utf-8")][-6:]
    open(os.path.join(OUT, "manifest.json"), "w", encoding="utf-8").write(
        json.dumps(report, ensure_ascii=False, indent=2))

    # 打包
    if os.path.exists(ZIP):
        os.remove(ZIP)
    with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED) as z:
        for fn in sorted(os.listdir(OUT)):
            z.write(os.path.join(OUT, fn), fn)
    print("ZIP", ZIP, os.path.getsize(ZIP), "sha", sha(ZIP)[:20], flush=True)
    with zipfile.ZipFile(ZIP) as z:
        print("MEMBERS", len(z.namelist()), "BAD", z.testzip(), flush=True)

    # 8800 自测
    lst = json.loads(OP.open("http://localhost:8800/list", timeout=20).read())
    got = OP.open("http://localhost:8800/download?name=" + os.path.basename(ZIP), timeout=120).read()
    local = open(ZIP, "rb").read()
    print("SELFTEST in_list", os.path.basename(ZIP) in lst,
          "CL", len(local), "GOT", len(got), "IDENTICAL", got == local, flush=True)
    if not (os.path.basename(ZIP) in lst and got == local):
        raise SystemExit("8800 selftest FAILED")

    # 先人眼复验模式：只生成材料，不发回执
    if os.environ.get("EP3_FIX5_NO_SEND") == "1":
        print("EP3_FIX5_NO_SEND=1：材料与 zip 已生成，暂不发回执（待人眼复验）", flush=True)
        return 0

    # 发回执前强制读信箱
    g = subprocess.run([sys.executable, os.path.join(BASE, "wb_gate.py"),
                        "--tag", "pre_send_qa_frames"],
                       capture_output=True, text=True, encoding="utf-8", errors="replace")
    print(g.stdout.strip(), flush=True)
    if g.returncode != 0:
        print("GATE != GO，按规矩停下等，本条不发送回执。", flush=True)
        return 2

    txt = """【EP03 修片五镜关键帧交验｜未拼合、未出整片，请复验】接 wb id=202/204

■ 本步完成
只重渲 `s3_1 / s6_1 / s7_1 / s9_1 / s10_1` 五镜（`EP3_ONLY` + `EP3_NO_FINAL=1`），
音频、字幕、总封装**全部跳过**：没有拼合、没有新整片、没有重写母带或 ass，其余 9 镜沿用原 shots。
每步前 gate 已读 wb 箱（pre_edit_coords / pre_render_five_shots / pre_send_qa_frames 均 GO）。

■ 交付（交换目录顶层）
`ep03_fix5_frames_for_qa.zip`（8800 逐字节自测通过），内含：
`fix5_sheet.png` 五镜各 2 帧总览、`fix5_before_after.png` 逐镜前后对比、
10 张全分辨率关键帧、5 张问题处放大裁切、`build_ep03.fix5.diff`、改后脚本副本、
`manifest.json`（五镜 mp4 字节/sha、帧号、音频与字幕未改动证明、gate 记录）、README。

■ 5 项改法（请按放大裁切逐项验）
1. S3-1 标签 `(1120,120)`→`(820,100)` 不再出右沿（首轮到 `(820,120)` 时我发现白底板与湘王红字底板有一条窄重叠，又上移 20px 重渲了这一镜做干净）；箭头整条下移 70px 到 `(1120,190)→(920,280)`，避开「湘王朱柏自焚」。
2. S6-1 年份/副标 y 偏移 `22/52`→`42/76` 不再被 y=480 时间线穿字；副标由 GRAY 改 INK 提对比；「史书越含糊」pill `(44,540)`→`(760,44)` 右上空白（左下 y≥600 实测贴烧录字幕，故未按你建议放左下）。
3. S7-1 朝阳门整组 `(872,250)`→`(960,300)`、`dy` 改 `+10`，与南京蓝标错开。
4. S9-1 紫框与标注**原本就在**（真实窗口 1326.24–1327.74s，QA 扫的 1324.7–1326.2s 偏早）；只按分镜补了框内三艘帆船剪影，时间窗/坐标没动。若你认为空框可接受，回一句我就撤掉这项、这镜不重渲。
5. S10-1 去掉「落版金句」标题行只留三行正文；`card()` 加空标题分支让正文上移，其余 17 处 card 均有标题、行为不变。

■ 检查点（不越线）
**你验过之前不拼合、不出整片。** 放行后我才做：拼合 → 复测三项（响度/真峰/底床，测成片 mp4）→ 分块回传 + `subs_ep03.ass` → 回执。
若哪项要再调，直接在帧图上圈，我只重渲受影响镜、不动其余四镜与音频。"""
    body = {"from": "workbuddy", "kind": "note", "text": txt,
            "files": [os.path.basename(ZIP)]}
    req = urllib.request.Request(
        SEND, data=json.dumps(body, ensure_ascii=False).encode("utf-8"),
        headers={"Content-Type": "application/json"}, method="POST")
    with OP.open(req, timeout=30) as r:
        print("REPLY HTTP", r.status, r.read().decode("utf-8"), flush=True)
    return 0


if __name__ == "__main__":
    sys.exit(main())
