# -*- coding: utf-8 -*-
"""EP03 fix7 第2步交帧：打包验证帧推8800根目录→逐字节自测→回执花酱。"""
import os, sys, json, hashlib, urllib.request, shutil

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

BASE = r"D:/Download/muse_exchange"
QA = os.path.join(BASE, "ep03_fix7_qa")
ZIP = os.path.join(BASE, "ep03_fix7_10shots_qa.zip")
SHEET = os.path.join(QA, "ep03_fix7_10shots_qa_sheet.png")

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()

# 打包验证帧目录（png 全收）
import zipfile
pngs = sorted(f for f in os.listdir(QA) if f.endswith(".png"))
with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED) as z:
    for f in pngs:
        z.write(os.path.join(QA, f), f)
print("zip", os.path.getsize(ZIP), sha(ZIP), "pngs", len(pngs), flush=True)

# 推 8800 根目录（zip + 拼图）
def upload(p):
    name = os.path.basename(p)
    data = open(p, "rb").read()
    req = urllib.request.Request("http://localhost:8800/upload?name=" + urllib.parse.quote(name),
                                 data=data, headers={"Content-Type": "application/octet-stream"})
    return urllib.request.urlopen(req, timeout=60).read().decode("utf-8", "replace")
import urllib.parse
for p in (ZIP, SHEET):
    print("UPLOAD", os.path.basename(p), upload(p), flush=True)

# 逐字节自测
def selftest(p):
    name = os.path.basename(p)
    remote = urllib.request.urlopen("http://localhost:8800/download?name=" + urllib.parse.quote(name), timeout=60).read()
    local = open(p, "rb").read()
    ok = remote == local and hashlib.sha256(remote).hexdigest() == sha(p)
    print("SELFTEST", name, "PASS" if ok else "FAIL", len(remote), len(local), flush=True)
    assert ok, name
for p in (ZIP, SHEET):
    selftest(p)

# 报告 json（本地留档）
report = {
    "stage": "ep03_fix7_step2_frames",
    "master_v4": {"file": "ep03_narration_master_v4.wav", "bytes": os.path.getsize(os.path.join(BASE,"ep03_narration_master_v4.wav")),
                  "sha256": sha(os.path.join(BASE,"ep03_narration_master_v4.wav")), "duration_s": 1525.92, "lufs": -16.36, "tp": -1.17},
    "qa_zip": {"file": os.path.basename(ZIP), "bytes": os.path.getsize(ZIP), "sha256": sha(ZIP)},
    "qa_sheet": {"file": os.path.basename(SHEET), "bytes": os.path.getsize(SHEET), "sha256": sha(SHEET)},
    "frames": pngs,
}
json.dump(report, open(os.path.join(BASE, "ep03_fix7_qa_report.json"), "w", encoding="utf-8"),
          ensure_ascii=False, indent=2)
print("report written", flush=True)
