"""Load a published proof-DAG library, recheck it, open a session snapshot, and import theorems.

This example opens the library that `docs/examples/store/load_library.mojo`
publishes in `publish_example`, at the path in `JUDGMENT_EXAMPLE_LIBRARY` (the
documentation gate publishes it there). See `binary_roundtrip.py` to create and
publish a library from Python.
"""
import os

from judgment import Budget, Library, Session, StoreError


def main():
    path = os.environ["JUDGMENT_EXAMPLE_LIBRARY"]

    # Open the library and independently recheck every stored proof row.
    lib = Library.open(path)
    budget = Budget(10000000)
    check = lib.recheck(budget, workers=1)
    assert len(lib.theorems()) == 2
    assert check.rows > 0
    print("Rechecked", len(lib.theorems()), "theorems")

    # Look up a theorem by name or by canonical statement identity.
    info = lib.find("pairs.both")
    assert lib.find(f"judgment.stmt.{info.sid}") is not None
    assert lib.find("pairs.none") is None
    print("Found pairs.both:", info.name, "| unknown absent:", lib.find("pairs.none") is None)

    # Open a session over the full rechecked snapshot and cite the theorem.
    snap = lib.snapshot(budget, workers=1)
    s = Session.open(snap)
    fact = s.import_fact("pairs.both")
    print("Cited from snapshot:", fact)

    # Opening a non-existent library directory fails with a typed StoreError.
    refused = "accepted"
    try:
        Library.open(path + "/missing")
    except StoreError as error:
        refused = str(error.kind)
    assert refused != "accepted"
    print("Missing library refused:", refused)


main()
