#!/usr/bin/env python3
"""Reproduce the exact algebra output and a deterministic release archive."""
from pathlib import Path
import hashlib
import json
import subprocess
import sys
import zipfile

ROOT = Path(__file__).resolve().parent
ARCHIVE = "actual-incidence-attack.zip"
EXCLUDED = {ARCHIVE, "ARCHIVE-SHA256.txt", "archive-validation.txt",
            "SHA256SUMS.txt"}


def digest(data):
    return hashlib.sha256(data).hexdigest()


def check_math_delimiters(path):
    text = path.read_text()
    display = False
    code = False
    for line in text.splitlines():
        if line.startswith(chr(96)*3):
            code = not code
        if code:
            continue
        if line.strip() == r"\[":
            assert not display, (path.name, "nested display")
            display = True
        elif line.strip() == r"\]":
            assert display, (path.name, "unopened display")
            display = False
        elif display:
            assert r"\(" not in line and r"\)" not in line, \
                (path.name, "inline delimiters inside display")
        else:
            assert line.count(r"\(") == line.count(r"\)"), \
                (path.name, "unbalanced inline math", line)
    assert not display and not code, (path.name, "unclosed block")


def main():
    result = subprocess.run(
        [sys.executable, str(ROOT/"verify-actual-incidence.py"),
         "--output", str(ROOT/"exact-results.json")],
        cwd=ROOT, text=True, capture_output=True, check=True,
    )
    (ROOT/"verification-output.txt").write_text(result.stdout)
    exact = json.loads((ROOT/"exact-results.json").read_text())
    assert all(x == "pass" for x in exact["checks"].values())
    for path in ROOT.glob("*.md"):
        check_math_delimiters(path)
    paths = sorted(p for p in ROOT.rglob("*") if p.is_file()
                   and p.name not in EXCLUDED
                   and "__pycache__" not in p.parts
                   and p.suffix != ".pyc")
    manifest = "".join(f"{digest(p.read_bytes())}  {p.relative_to(ROOT).as_posix()}\n"
                       for p in paths)
    (ROOT/"SHA256SUMS.txt").write_text(manifest)
    members = paths+[ROOT/"SHA256SUMS.txt"]
    archive = ROOT/ARCHIVE
    with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED,
                         compresslevel=9) as z:
        for path in sorted(members):
            info = zipfile.ZipInfo(path.relative_to(ROOT).as_posix(),
                                   date_time=(2026, 9, 8, 0, 0, 0))
            info.compress_type = zipfile.ZIP_DEFLATED
            info.external_attr = 0o644 << 16
            z.writestr(info, path.read_bytes())
    with zipfile.ZipFile(archive) as z:
        assert z.testzip() is None
        assert set(z.namelist()) == {p.relative_to(ROOT).as_posix() for p in members}
        for path in members:
            assert z.read(path.relative_to(ROOT).as_posix()) == path.read_bytes()
        for line in manifest.splitlines():
            sha, name = line.split("  ", 1)
            assert digest(z.read(name)) == sha
    (ROOT/"ARCHIVE-SHA256.txt").write_text(f"{digest(archive.read_bytes())}  {ARCHIVE}\n")
    validation = (
        "Exact universal algebra: PASS\n"
        "Markdown mathematics delimiters: PASS\n"
        "Archive CRC and member bytes: PASS\n"
        "Every manifest digest against archived bytes: PASS\n"
        "Primary-source snapshots: metadata and hashes only\n"
        "Scope: conditional two-angle actual filled-vacuum theorem; unrestricted conjecture open\n"
    )
    (ROOT/"archive-validation.txt").write_text(validation)
    print(validation, end="")
    print(f"Archive SHA-256: {digest(archive.read_bytes())}")


if __name__ == "__main__":
    main()
