#!/usr/bin/env python3
"""Synthetic ZIP byte-identity experiment for the 2026-10-19 Gumi article.

Python 3.9+ syntax; uses only the standard library. By default prints JSON.
Optional --write-zips creates a NEW directory and writes the sample archives.
This is an experiment with known inputs, not an arbitrary ZIP audit tool.
"""

import argparse
import hashlib
import io
import json
from pathlib import Path
import platform
import stat
import warnings
import zipfile
import zlib


FILES = {
    "data.txt": b"".join(
        (f"item={i:04d}; group={i % 37:02d}; " + "repeat " * 8 + "\n").encode()
        for i in range(500)
    ),
    "readme.txt": b"Gumi ZIP byte identity experiment.\n",
}
STAMP = (2026, 10, 19, 20, 0, 0)


def make_zip(files, *, order=None, stamp=STAMP, mode=0o644,
             comment=b"", method=zipfile.ZIP_DEFLATED, level=6):
    output = io.BytesIO()
    with zipfile.ZipFile(output, "w") as archive:
        archive.comment = comment
        for name in sorted(files) if order is None else order:
            info = zipfile.ZipInfo(name, date_time=stamp)
            info.create_system = 3
            info.external_attr = (stat.S_IFREG | mode) << 16
            info.extra = b""
            archive.writestr(info, files[name],
                             compress_type=method, compresslevel=level)
    return output.getvalue()


def content_manifest(blob):
    rows = []
    seen = set()
    with zipfile.ZipFile(io.BytesIO(blob)) as archive:
        for info in archive.infolist():
            if info.filename in seen:
                raise ValueError("duplicate member: " + info.filename)
            seen.add(info.filename)
            data = archive.read(info)
            rows.append({"name": info.filename, "size": len(data),
                         "sha256": hashlib.sha256(data).hexdigest()})
    return sorted(rows, key=lambda row: row["name"])


def describe(blob, baseline):
    with zipfile.ZipFile(io.BytesIO(blob)) as archive:
        infos = archive.infolist()
        members = [{
            "name": info.filename,
            "date_time": list(info.date_time),
            "create_system": info.create_system,
            "mode_octal": format(stat.S_IMODE(info.external_attr >> 16), "04o"),
            "external_attr": info.external_attr,
            "method": info.compress_type,
            "uncompressed_bytes": info.file_size,
            "compressed_bytes": info.compress_size,
            "crc32_hex": format(info.CRC, "08x"),
            "extra_hex": info.extra.hex(),
        } for info in infos]
        crc_ok = archive.testzip() is None
        # Direct byte comparisons complement the hash-based manifest.
        payloads = {info.filename: archive.read(info) for info in infos}
        comment = archive.comment.decode("ascii")
    return {
        "archive_bytes": len(blob),
        "archive_sha256": hashlib.sha256(blob).hexdigest(),
        "same_archive_bytes_as_baseline": blob == baseline,
        "same_paths_and_payload_bytes_as_inputs": payloads == FILES,
        "crc_check_passed": crc_ok,
        "comment_ascii": comment,
        "members_in_archive_order": members,
        "content_manifest": content_manifest(blob),
    }


def require(condition, label):
    if not condition:
        raise RuntimeError("check failed: " + label)


def experiment():
    archives = {
        "baseline": make_zip(FILES),
        "repeat": make_zip(FILES),
        "time_plus_2s": make_zip(FILES, stamp=(2026, 10, 19, 20, 0, 2)),
        "reverse_order": make_zip(FILES, order=sorted(FILES, reverse=True)),
        "mode_0600": make_zip(FILES, mode=0o600),
        "archive_comment": make_zip(FILES, comment=b"build B"),
        "stored": make_zip(FILES, method=zipfile.ZIP_STORED),
        "deflate_level_1": make_zip(FILES, level=1),
        "time_plus_1s": make_zip(FILES, stamp=(2026, 10, 19, 20, 0, 1)),
    }
    baseline = archives["baseline"]
    results = {name: describe(blob, baseline) for name, blob in archives.items()}
    checks = []
    for name, result in results.items():
        require(result["same_paths_and_payload_bytes_as_inputs"], name + " payload bytes")
        require(result["crc_check_passed"], name + " CRC")
        require(result["content_manifest"] == results["baseline"]["content_manifest"],
                name + " content manifest")
        checks.append(name + ": payload bytes, CRC, and manifest equal")
    for name in ["repeat", "time_plus_1s"]:
        require(archives[name] == baseline, name + " exact archive bytes")
        checks.append(name + ": exact archive bytes equal")
    for name in ["time_plus_2s", "reverse_order", "mode_0600", "archive_comment",
                 "stored", "deflate_level_1"]:
        require(archives[name] != baseline, name + " archive byte difference")
        require(results[name]["archive_sha256"] != results["baseline"]["archive_sha256"],
                name + " observed SHA-256 difference")
        checks.append(name + ": archive bytes and observed SHA-256 differ")
    require(all(member["date_time"] == list(STAMP)
                for member in results["time_plus_1s"]["members_in_archive_order"]),
            "odd second is read back as zero seconds in these headers")

    changed = dict(FILES)
    changed["data.txt"] += b"changed\n"
    renamed = {"renamed.txt": FILES["data.txt"], "readme.txt": FILES["readme.txt"]}
    boundary_archives = {
        "changed_payload": make_zip(changed),
        "renamed_member": make_zip(renamed),
    }
    boundaries = {name: describe(blob, baseline)
                  for name, blob in boundary_archives.items()}
    for name, result in boundaries.items():
        require(not result["same_paths_and_payload_bytes_as_inputs"], name + " path/bytes comparison")
        require(result["content_manifest"] != results["baseline"]["content_manifest"],
                name + " manifest differs")
        checks.append(name + ": path/content manifest differs")
    require(sorted(row["sha256"] for row in boundaries["renamed_member"]["content_manifest"])
            == sorted(row["sha256"] for row in results["baseline"]["content_manifest"]),
            "renaming preserves payload hash multiset but changes paths")

    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always", UserWarning)
        duplicate = make_zip(FILES, order=sorted(FILES) + ["readme.txt"])
    with zipfile.ZipFile(io.BytesIO(duplicate)) as archive:
        duplicate_names = archive.namelist()
    try:
        content_manifest(duplicate)
    except ValueError as error:
        duplicate_error = str(error)
    else:
        raise RuntimeError("duplicate name was not rejected by manifest")
    require(duplicate_names.count("readme.txt") == 2, "duplicate fixture")
    boundaries["duplicate_member"] = {
        "archive_bytes": len(duplicate),
        "member_names": duplicate_names,
        "manifest_error": duplicate_error,
        "writer_warnings": [str(w.message) for w in caught],
    }
    checks.append("duplicate_member: manifest rejects duplicate path before mapping")
    archives.update(boundary_archives)
    archives["duplicate_member"] = duplicate
    report = {
        "experiment_date": "2026-10-19",
        "environment": {
            "python": platform.python_version(),
            "implementation": platform.python_implementation(),
            "platform": platform.platform(),
            "zlib_compile_version": zlib.ZLIB_VERSION,
            "zlib_runtime_version": zlib.ZLIB_RUNTIME_VERSION,
        },
        "scope": "Known synthetic regular-file inputs; no cross-tool or cross-environment reproducibility claim.",
        "fixture": {name: {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
                    for name, data in sorted(FILES.items())},
        "baseline_policy": {"date_time": list(STAMP), "mode_octal": "0644",
                            "create_system": 3, "method": "DEFLATE", "level": 6,
                            "order": sorted(FILES), "extra_hex": "", "comment_ascii": ""},
        "variants": results,
        "boundaries": boundaries,
        "checks_passed": checks,
        "status": "passed",
    }
    return report, archives


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--write-zips", type=Path, help="new directory for generated sample ZIPs")
    args = parser.parse_args()
    report, archives = experiment()
    if args.write_zips is not None:
        args.write_zips.mkdir(parents=True, exist_ok=False)
        for name, blob in archives.items():
            (args.write_zips / (name + ".zip")).write_bytes(blob)
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
