#!/usr/bin/env python3
"""Fail-closed audit for the sealed 4x5 triangular-torus receipt."""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path

EXPECTED_DIRECT = {
    "18": 40, "20": 204, "22": 1160, "24": 5240,
    "26": 12160, "28": 20940, "30": 35080, "32": 42040,
    "34": 39360, "36": 22500, "38": 5680, "40": 352,
}
EXPECTED_DAMAGED = {
    "10": 44, "12": 260, "14": 2960, "16": 10380,
    "18": 30880, "20": 48442, "22": 46640, "24": 29000,
    "26": 11740, "28": 3200, "30": 960, "32": 200,
    "34": 40, "36": 10,
}


def fail(message: str) -> None:
    raise SystemExit(f"RECEIPT_REJECTED: {message}")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("receipt", type=Path)
    parser.add_argument("--source", type=Path, required=True)
    args = parser.parse_args()
    try:
        receipt = json.loads(args.receipt.read_text(encoding="utf-8"))
    except Exception as exc:
        fail(f"cannot read JSON: {exc}")
    if receipt.get("schema") != "mathcase-triangular-torus-4x5-half-fill-v1":
        fail("schema")
    actual_source = hashlib.sha256(args.source.read_bytes()).hexdigest()
    if receipt.get("source_sha256") != actual_source:
        fail("source SHA-256")
    if receipt.get("status") != "PASS_EXACT_INDEPENDENT_TRIANGULAR_ENUMERATION":
        fail("status")
    graph = receipt.get("graph")
    if graph != {
        "cols": 5,
        "directions": ["right", "down", "down-right"],
        "edges": 60,
        "marked_vertices": 10,
        "rows": 4,
    }:
        fail("graph metadata")
    if receipt.get("direct_histogram") != EXPECTED_DIRECT:
        fail("direct histogram")
    if receipt.get("transfer_histogram") != EXPECTED_DIRECT:
        fail("transfer histogram")
    if receipt.get("damaged_without_diagonals_histogram") != EXPECTED_DAMAGED:
        fail("damaged control histogram")
    checks = receipt.get("checks")
    expected_checks = {
        "all_vertices_degree_6": True,
        "damaged_control_differs": True,
        "damaged_same_total": True,
        "direct_transfer_match": True,
        "edge_count": 60,
        "expected_dip_bins": {"18": 40, "20": 204, "22": 1160},
        "expected_dip_match": {"18": True, "20": True, "22": True},
        "half_filled_total": True,
        "vertex_count": 20,
    }
    if checks != expected_checks:
        fail("control summary")
    print("PASS_TRIANGULAR_RECEIPT_AUDIT")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
