"""Check the exact certificate bytes and inventory both target theorems."""
from pathlib import Path
import gzip
import hashlib
import json
import sys

def inventory(path, target_names, permitted):
    names = {0: ""}
    declarations = {}
    axioms = set()
    content = hashlib.sha256()
    with gzip.open(path, "rb") as exported:
        for line in exported:
            content.update(line)
            if line.startswith(b'{"in":'):
                record = json.loads(line)
                element = record.get("str", record.get("num"))
                parent = names[element["pre"]]
                leaf = element.get("str", element.get("i"))
                names[record["in"]] = f"{parent}.{leaf}" if parent else str(leaf)
            elif line.startswith((b'{"axiom":', b'{"thm":')):
                record = json.loads(line)
                if "axiom" in record:
                    axioms.add(names[record["axiom"]["name"]])
                else:
                    theorem = record["thm"]
                    name = names[theorem["name"]]
                    if name in target_names:
                        declarations[name] = theorem["type"]
    if declarations.keys() != target_names:
        raise ValueError("expected both exact target theorem names")
    if axioms != permitted:
        raise ValueError(f"unexpected exported axioms: {sorted(axioms)}")
    return content.hexdigest(), declarations, axioms

bundle = Path(sys.argv[1])
manifest = json.loads((bundle / "manifest.json").read_text())
entry = manifest["certificates"]["solution"]
targets = set(manifest["theorems"])
permitted = set(manifest["permitted_axioms"])
digest, declarations, axioms = inventory(bundle / entry["file"], targets, permitted)
if digest != entry["uncompressed_sha256"]:
    raise ValueError("uncompressed certificate hash mismatch")
print("Uncompressed SHA-256:", digest)
print("Exported theorem declarations:", json.dumps(declarations, sort_keys=True))
print("All exported axiom declarations:", ", ".join(sorted(axioms)))
