#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 全量交付包 8800 自测：分片在列 / 字节一致 / 合并 sha256 / zip CRC / manifest。"""
import hashlib
import io
import json
import os
import urllib.parse
import urllib.request
import zipfile

HERE = os.path.dirname(os.path.abspath(__file__))
op = urllib.request.build_opener(urllib.request.ProxyHandler({}))


def get(name):
    u = "http://127.0.0.1:8800/download?name=" + urllib.parse.quote(name)
    with op.open(u, timeout=180) as r:
        return r.headers.get("Content-Length"), r.read()


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


lst = json.loads(op.open("http://127.0.0.1:8800/list", timeout=20).read().decode())
idx = json.load(open(os.path.join(HERE, "ep03_vox_full_index.json"), encoding="utf-8"))
zipname = idx["zip"]
zip_local = open(os.path.join(HERE, zipname), "rb").read()

print("=== 分片逐片自测 ===")
merged = bytearray()
for p in idx["parts"]:
    name = p["file"]
    local = open(os.path.join(HERE, name), "rb").read()
    cl, remote = get(name)
    ok = (name in lst and int(cl) == len(local) and remote == local
          and sha256(local) == p["sha256"])
    print("  %-38s in_list=%s CL=%s got=%d identical=%s sha=%s" % (
        name, name in lst, cl, len(remote), remote == local,
        sha256(local) == p["sha256"]))
    assert ok, "分片自测失败: " + name
    merged.extend(remote)

print("=== 合并与 zip 校验 ===")
print("  merged bytes %d / index %d / local zip %d" % (
    len(merged), idx["zip_bytes"], len(zip_local)))
print("  merged sha256 %s" % sha256(bytes(merged)))
print("  index sha256  %s" % idx["zip_sha256"])
assert len(merged) == idx["zip_bytes"] == len(zip_local)
assert sha256(bytes(merged)) == idx["zip_sha256"] == sha256(zip_local)
z = zipfile.ZipFile(io.BytesIO(bytes(merged)))
bad = z.testzip()
print("  zip testzip bad member:", bad)
assert bad is None
names = z.namelist()
wavs = [n for n in names if n.startswith("wav/") and n.endswith(".wav")]
print("  zip members %d | wav %d | docs %d" % (
    len(names), len(wavs), len([n for n in names if n.startswith("docs/")])))
assert len(wavs) == 109
m = json.loads(z.read("manifest.json"))
print("=== manifest ===")
print("  recipe   :", m["recipe"])
print("  wav_count:", m["wav_count"])
print("  integrity:", json.dumps(m.get("integrity", {}), ensure_ascii=False)[:400])
assert m["wav_count"] == 109 and m.get("integrity", {}).get("all_ok") is True

print("=== 小文档字节自测 ===")
for n in ["ep03_vox_full_index.json", "ep03_durations.json", "ep03_durations.md",
          "ep03_synth_script.txt", "ep03_synth_report.md",
          "ep03_vox_integrity_check.md", "ep03_vox_integrity_check.json",
          "ep03_oldref_reject_manifest.json"]:
    local = open(os.path.join(HERE, n), "rb").read()
    cl, remote = get(n)
    print("  %-38s in_list=%s CL=%s identical=%s" % (
        n, n in lst, cl, remote == local))
    assert n in lst and remote == local
print("ALL SELFTEST PASS")
