"""Export checked proof-DAG theorems into a library and track external claims in a session."""
from std.tempfile import mkdtemp
from std.testing import assert_equal, assert_true
from judgment_shell import (
    ClaimTable, EvidenceLevel, Session, assume_claim, export_claims, label,
)
from judgment_store import Library
from termbank import Budget


def main() raises:
    var budget = Budget(10000000)
    var path = String(mkdtemp(), "/lib")
    var lib = Library.create(path, "none")

    # Track an external claim in a session and export its guarded implication.
    var s = Session.open(lib.profile_snapshot(budget))
    var root = s.base()
    var a = s.type_var("a")
    var fx = s.fix(root, "x", a)
    var x = fx[1]
    var reflexive = x == x
    var claims = ClaimTable(s)
    var h = assume_claim(s, claims, fx[0], reflexive, "x = x?", "solver", "1", budget)
    var guarded = export_claims(s, claims, s.hypothesis(h), [h, fx[0]], budget)
    var guarded_label = label(s, claims, guarded, budget)
    assert_equal(len(guarded_label.claims), 1)
    print("Stored claim:", guarded_label.claims[0].query, "from", guarded_label.claims[0].decider, guarded_label.claims[0].version)

    # Close and publish the guarded theorem into the proof-DAG library, then recheck it.
    var fact = s.prove_step("claimed.refl", guarded)
    var change = lib.change()
    change.add(s.export(fact, "claimed.refl"))
    _ = change.publish()

    var reopened = Library.open(path)
    var check = reopened.recheck(budget, workers=1)
    assert_true(check.rows > 0)
    var s2 = Session.open(reopened.snapshot(budget, workers=1))
    var cited = s2.cite(s2.import_fact("claimed.refl"))
    var fresh_claims = ClaimTable(s2)
    var bare = label(s2, fresh_claims, cited, budget)
    assert_equal(bare.level, EvidenceLevel.CHECKED)
    assert_equal(len(bare.claims), 0)
    print("Rechecked library theorem; plain citation has", len(bare.claims), "claims")
