#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 渲染工单（tim 箱 id=166）第 1 步：分块组装 + 硬校验 + 解压。

花酱给的硬指标：总字节 204107612、sha256
e044ac45278032340842abb0982bf2bc534c329b82c9fd486232f4f09389bb5a
不对就不要渲、先报花酱。
"""
import hashlib
import json
import os
import zipfile

HERE = os.path.dirname(os.path.abspath(__file__))
PARTS = [os.path.join(HERE, "ep03_package.zip.part_%02d" % i) for i in range(10)]
ZIP = os.path.join(HERE, "ep03_package.zip")
DEST = os.path.join(HERE, "ep03_package")
EXPECT_BYTES = 204107612
EXPECT_SHA = "e044ac45278032340842abb0982bf2bc534c329b82c9fd486232f4f09389bb5a"

report = {"parts": [], "expect_bytes": EXPECT_BYTES, "expect_sha256": EXPECT_SHA}


def main():
    for p in PARTS:
        assert os.path.exists(p), "missing " + p
        report["parts"].append({"file": os.path.basename(p), "bytes": os.path.getsize(p)})

    h = hashlib.sha256()
    total = 0
    with open(ZIP, "wb") as out:
        for p in PARTS:
            with open(p, "rb") as f:
                while True:
                    b = f.read(1024 * 1024)
                    if not b:
                        break
                    out.write(b)
                    h.update(b)
                    total += len(b)
    got_sha = h.hexdigest()
    report["assembled_bytes"] = total
    report["assembled_sha256"] = got_sha
    report["bytes_ok"] = total == EXPECT_BYTES
    report["sha_ok"] = got_sha == EXPECT_SHA
    print("ASSEMBLED", total, got_sha)
    print("BYTES_OK", report["bytes_ok"], "SHA_OK", report["sha_ok"])

    if not (report["bytes_ok"] and report["sha_ok"]):
        print("!!! HARD CHECK FAILED - DO NOT RENDER, REPORT TO HUAJIANG")
        with open(os.path.join(HERE, "ep03_assemble_report.json"), "w", encoding="utf-8") as f:
            json.dump(report, f, ensure_ascii=False, indent=2)
        return

    # unzip -t 等价
    with zipfile.ZipFile(ZIP) as z:
        bad = z.testzip()
        names = z.namelist()
        report["zip_testzip"] = bad
        report["member_count"] = len(names)
    print("ZIP_TESTZIP", bad, "MEMBERS", len(names))
    if bad is not None:
        print("!!! ZIP CORRUPT - DO NOT RENDER")
        return

    os.makedirs(DEST, exist_ok=True)
    with zipfile.ZipFile(ZIP) as z:
        z.extractall(DEST)
    report["extracted_to"] = DEST
    report["top_members"] = names[:30]

    # 找 build_ep03.py / README_TIM.md
    found = {}
    for root, dirs, files in os.walk(DEST):
        for fn in files:
            if fn in ("build_ep03.py", "README_TIM.md", "monk_face.png"):
                found[fn] = os.path.join(root, fn)
    report["key_files"] = found
    print("KEY_FILES", json.dumps(found, ensure_ascii=False, indent=2))

    with open(os.path.join(HERE, "ep03_assemble_report.json"), "w", encoding="utf-8") as f:
        json.dump(report, f, ensure_ascii=False, indent=2)
    print("DONE", "STEP1_OK" if report["bytes_ok"] and report["sha_ok"] and bad is None else "FAILED")


if __name__ == "__main__":
    main()
