"""Match a stored claim-backed theorem and discharge its exact guard."""
from std.testing import assert_equal, assert_true
from judgment_shell import (
    ClaimTable, LawBundle, Pattern, Session, TheoremStore,
    assume_claim, export_claims, match_terms, schemas, validate,
)
from termbank import Budget


def main() raises:
    var s = Session()
    var budget = Budget(1000000)
    var prop = s.prop_type()
    var p = s.prop("P")
    var root = s.base()
    var x = s.fix(root, "X", prop)
    var claims = ClaimTable(s)
    var h = assume_claim(s, claims, x[0], x[1], "prove X", "example", "1", budget)
    var source = export_claims(s, claims, s.hypothesis(h), [h, x[0]], budget)
    var fact = s.prove_step("identity", source)
    var after = s.base()
    var store = TheoremStore(s, claims^)
    var id = store.register(s, fact, Optional(source), budget)
    var record = store.get(id, budget)
    var matches = match_terms(s, Pattern(record.conclusion, record.variables.copy()), p, budget)
    assert_equal(len(matches), 1)
    assert_true(matches[0].assignment[0][1].same_as(p))
    var instance = store.instantiate(s, id, after, [], [p], budget)
    assert_equal(len(store.label(s, instance, budget).claims), 1)
    var evidence = s.assume(after, p)
    var result = store.apply(s, id, evidence, [], [p], s.hypothesis(evidence), budget)
    assert_true(result.statement().same_as(p))
    assert_equal(len(result.hypotheses()), 1)
    assert_equal(len(store.label(s, result, budget).claims), 0)
    var bundle = LawBundle(s, "Generic", [("P", p)], [("identity", fact)])
    var standard = schemas()
    validate(s, bundle, standard[3], budget)
    print("matching, guarded theorem use, and bundles: ok")
