"""Validate packaging, source fidelity and recorded computation (not mathematics)."""
import csv
import json
from pathlib import Path
from exact_arithmetic import certificate


def main():
    root = Path(__file__).resolve().parents[1]
    required = [
        "00_EXECUTIVE_STATE.md", "01_ARCHIVE_AUDIT.md", "02_CLAIM_LEDGER.md",
        "03_CANONICAL_FRONTIER.md", "04_ATTACK_LOG.md", "05_NEW_MATHEMATICS.md",
        "06_ADVERSARIAL_REFEREE.md", "07_NEXT_PROOF_OBLIGATIONS.md",
        "08_SOURCE_AUDIT.md", "README.md", "results/exact_results.json",
        "results/test_output.txt", "results/claim_ledger.json",
    ]
    for filename in required:
        if not (root/filename).is_file():
            raise AssertionError("Missing deliverable: " + filename)
    for path in root.rglob("*.md"):
        text = path.read_text(encoding="utf-8")
        if "\ufffd" in text:
            raise AssertionError("Replacement character: " + str(path))
        if any(x in text for x in ("\\(", "\\)", "\\[", "\\]")):
            raise AssertionError("Noncanonical math delimiter: " + str(path))
        if any(ord(c)<32 and c not in "\n\t" for c in text):
            raise AssertionError("Control character: " + str(path))
        if text.count("$$") % 2:
            raise AssertionError("Unbalanced display math: " + str(path))
    ledger = json.loads((root/"results/claim_ledger.json").read_text())
    fields = {
        "claim_id","statement","status","status_type","internal_source",
        "external_source","hypotheses","normalization","quantifiers",
        "depends_on","reproduced_here","notes",
    }
    ids = {r["claim_id"] for r in ledger}
    if len(ids) != len(ledger):
        raise AssertionError("Duplicate claim id")
    for r in ledger:
        if set(r) != fields:
            raise AssertionError("Claim fields: " + r["claim_id"])
        if any(d not in ids for d in r["depends_on"]):
            raise AssertionError("Dangling dependency: " + r["claim_id"])
        if not isinstance(r["reproduced_here"], bool):
            raise AssertionError("Non-boolean reproduction marker")
    recorded = json.loads((root/"results/exact_results.json").read_text())
    computed = json.loads(json.dumps(certificate()))
    if recorded != computed:
        raise AssertionError("Recorded arithmetic differs from source")
    with (root/"results/archive_inventory.csv").open(newline="") as f:
        inventory = list(csv.DictReader(f))
    if len(inventory) != 176:
        raise AssertionError("Unexpected archive inventory")
    log = (root/"results/test_output.txt").read_text()
    if "Ran 12 tests" not in log or not log.rstrip().endswith("OK"):
        raise AssertionError("Expected executed test log absent")
    result = {
        "required_files_present": True, "markdown_utf8_and_delimiters": "PASS",
        "claim_count": len(ledger), "claim_fields_and_dependency_ids": "PASS",
        "recorded_arithmetic_equals_fresh_computation": True,
        "archive_inventory_count": len(inventory),
        "test_log": "12 tests OK",
        "mathematical_proof_formalized": False,
    }
    output = json.dumps(result, ensure_ascii=False, indent=2) + "\n"
    (root/"results/deliverable_validation.json").write_text(output, encoding="utf-8")
    print(output, end="")


if __name__ == "__main__":
    main()
