"""Load a published proof-DAG library, recheck it, open a session snapshot, and import theorems."""
from std.tempfile import mkdtemp
from std.testing import assert_equal, assert_true
from judgment_shell import Session
from judgment_store import Library, StoreErrorKind
from termbank import Budget


def publish_example(path: String) raises:
    var lib = Library.create(path, "none")
    var budget = Budget(10000000)
    var s = Session.open(lib.profile_snapshot(budget))
    var t_fact = s.prove_step("basics.truth", s.truth(s.base()))
    var t_step = s.truth(s.base())
    var both_fact = s.prove_step("pairs.both", s.and_intro(t_step, t_step))
    var change = lib.change()
    change.add(s.export(t_fact, "basics.truth"))
    change.add(s.export(both_fact, "pairs.both"))
    _ = change.publish()


def main() raises:
    var path = String(mkdtemp(), "/lib")
    publish_example(path)

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

    # Look up a theorem by name or by canonical statement identity.
    var info = lib.find("pairs.both").value().copy()
    assert_true(Bool(lib.find(String("judgment.stmt.", info.sid))))
    assert_true(not lib.find("pairs.none"))
    print("Found pairs.both:", info.name, "| unknown absent:", not lib.find("pairs.none"))

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

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