# -*- coding: utf-8 -*-
"""EP03 fix8 交付：上传 fix8 成片 + 5 镜验证帧 + 重渲清单，逐字节核对，
回执花酱（报文件名/时长/sha/字节/响度真峰 + 5镜 sha 清单）。"""
import urllib.request, urllib.parse, json, hashlib, os, sys, subprocess

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

ROOT = "D:/Download/muse_exchange"
BASE = "http://localhost:8800"
BOX = "http://localhost:8801/send?box=huajiang"

def sha_bytes(b):
    return hashlib.sha256(b).hexdigest()

def upload_verify(fn, src):
    raw = open(src, "rb").read()
    req = urllib.request.Request(
        BASE + "/upload?name=" + urllib.parse.quote(fn),
        data=raw, headers={"Content-Type": "application/octet-stream"})
    up = urllib.request.urlopen(req, timeout=240).read().decode("utf-8", "replace")
    got = urllib.request.urlopen(
        BASE + "/download?name=" + urllib.parse.quote(fn), timeout=240).read()
    assert got == raw, fn + " 逐字节核对失败"
    return fn, len(raw), sha_bytes(raw)

# 1) 成片
mp4 = os.path.join(ROOT, "ep03_final_fix8.mp4")
rep = json.load(open(os.path.join(ROOT, "ep03_fix8_assemble_report.json"), encoding="utf-8"))
f, size, sha = upload_verify("ep03_final_fix8.mp4", mp4)
assert sha == rep["sha256"], "成片 sha 与拼合报告不符"
print("MP4", f, size, sha, "BYTE_MATCH", flush=True)

# 2) 5 镜全标签验证帧
qa_dir = os.path.join(ROOT, "ep03_fix8_qa")
frames = []
for n in ("s7_1", "s7_2", "s7_3", "s8_1", "s8_2"):
    fn = "fix8_%s_fulllabel.png" % n
    frames.append(upload_verify(fn, os.path.join(qa_dir, fn)))
sheet = upload_verify("fix8_5shots_qa_sheet.png", os.path.join(qa_dir, "fix8_5shots_qa_sheet.png"))
print("FRAMES", frames, flush=True)

# 3) 根目录可见性
lst = json.loads(urllib.request.urlopen(BASE + "/list", timeout=20).read())
for fn, _, _ in [("ep03_final_fix8.mp4", 0, 0)] + frames + [sheet]:
    assert fn in lst, fn + " 未在根目录 /list 出现"
print("LIST visible all", flush=True)

# 4) 成片响度实测
r = subprocess.run(["ffmpeg", "-v", "info", "-i", mp4,
                    "-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json",
                    "-f", "null", "-"], capture_output=True, text=True)
import re
mi = re.search(r'"input_i"\s*:\s*"([^"]+)"', r.stderr)
mt = re.search(r'"input_tp"\s*:\s*"([^"]+)"', r.stderr)
iv, tv = (float(mi.group(1)) if mi else None), (float(mt.group(1)) if mt else None)
print("LOUDNESS", iv, "LUFS /", tv, "dBTP", flush=True)

# 5) 重渲清单（各镜字节/sha），从拼合报告 inputs.shots 抽 5 镜
shots = rep["inputs"]["shots"]
rerendered = {n: {"bytes": shots[n]["bytes"], "sha256": shots[n]["sha256"],
                  "duration_s": shots[n]["duration_s"]}
              for n in ("s7_1", "s7_2", "s7_3", "s8_1", "s8_2")}
manifest = {"output": "ep03_final_fix8.mp4", "bytes": size, "sha256": sha,
            "duration": rep["video_duration_s"],
            "loudness_lufs": iv, "true_peak_dbtp": tv,
            "rerendered_5shots": rerendered,
            "frames": [{"name": a, "bytes": b, "sha256": c} for a, b, c in frames],
            "sheet": {"name": sheet[0], "bytes": sheet[1], "sha256": sheet[2]}}
json.dump(manifest, open(os.path.join(ROOT, "ep03_fix8_deliver_manifest.json"), "w",
                         encoding="utf-8"), ensure_ascii=False, indent=2)
upload_verify("ep03_fix8_deliver_manifest.json", os.path.join(ROOT, "ep03_fix8_deliver_manifest.json"))

# 6) 回执
shots_lines = "\n".join(
    "- %s  %d B  sha %s" % (n, v["bytes"], v["sha256"]) for n, v in rerendered.items())
frame_lines = "\n".join("- %s  %d B  sha %s" % (a, b, c) for a, b, c in frames)
TEXT = """【EP03 fix8 · 成片交付（地图坐标修正 + 5 镜重渲重拼）】

接 wb id=355。36 处坐标按 ep03_map_fix8_coords.md 逐点归位，两项定案照办（S8-2 航线延伸到东非 (133,515)→(59,594)、S8-1 卡片右移 x≈945）。S3-1 与其余 9 镜画面未动，旁白母带 v4 与字幕 fix7 一字不动（sha 与 fix7 交付版本一致，脚本内断言校验）。

成片：
- 文件名：ep03_final_fix8.mp4
- 大小：%d B（逐字节下载核对 PASS，根目录 /list 可见）
- sha256：%s
- 时长：视频 %.2fs / 音频 %.2fs（= fix7 的 1525.92s，未变）
- 成片实测：%s LUFS / %s dBTP

5 镜重渲清单（字节/sha）：
%s

5 镜全标签验证帧（每镜 1 张，抽自镜内 85%% 处全标签时刻）：
%s
- fix8_5shots_qa_sheet.png（5 镜拼图，%d B）

坐标核对要点（自验）：南京归位底图黑点 (877,238)；云南沐氏/武定狮山出西疆黑线归云南腹地；桂出北部湾归广西腹地；苏·穹窿山从安徽归苏南太湖东岸；S8-1 十四蓝点+四橙点全对齐底图预绘圆点，北平点 (919,97) 不被右移后的卡片遮挡；S8-2 航线贴底图红线并延伸到真正东非沿岸。详见验证帧。

清单 ep03_fix8_deliver_manifest.json 已上传。未上传 YouTube/未发布/未设定时，等你 QA。球传你。""" % (
    size, sha, rep["video_duration_s"], rep["audio_duration_s"], iv, tv,
    shots_lines, frame_lines, sheet[1])

data = json.dumps({"from": "wb", "kind": "done", "text": TEXT, "files": []},
                  ensure_ascii=False).encode("utf-8")
req = urllib.request.Request(BOX, data=data, headers={"Content-Type": "application/json"})
print("REPLY:", urllib.request.urlopen(req, timeout=15).read().decode("utf-8", "replace"), flush=True)
