"""Check a proposed substitution, preserve its guard, and retain a reusable theorem."""

from judgment import Session, arrow, implies, JudgmentError
from judgment import LibErrorKind


def main():
    s = Session()
    a_type = s.declare_type("A")
    a = s.symbol("a", a_type)
    b = s.symbol("b", a_type)
    c = s.symbol("c", a_type)
    f = s.symbol("f", arrow(a_type, a_type))

    tx = s.transaction()
    outer = s.base()
    guard = a == b
    assumed = s.assume(outer, guard, "ab")
    input = f(a)
    candidate = f(b)
    expected = input == candidate

    # Check congruence under the guard hypothesis a = b.
    same_function = s.eq_refl(assumed, f)
    argument_equality = s.hypothesis(assumed)
    checked = s.congruence(same_function, [argument_equality])
    assert checked.statement().same_as(expected)
    assert len(checked.hypotheses()) == 1
    assert checked.hypotheses()[0].same_as(guard)

    # The same evidence cannot justify a different replacement.
    wrong = input == f(c)
    rejected = False
    try:
        _ = s.convert(checked, wrong)
    except JudgmentError as e:
        rejected = e.kind == LibErrorKind.KERNEL
    assert rejected

    exported = s.imp_intro(assumed, checked)
    conditional = implies(guard, expected)
    assert exported.statement().same_as(conditional)
    assert len(exported.hypotheses()) == 0
    saved = s.prove_step("rewrite_f", exported)
    retained = tx.commit(expressions=[a, b, f], facts=[saved])

    # Use retained handles and look up the saved theorem; do not reuse old inner handles.
    ra = retained.expressions()[0]
    rb = retained.expressions()[1]
    rf = retained.expressions()[2]
    theorem = s.fact("rewrite_f")
    context = s.base()
    rule = s.use(context, theorem)
    final_guard = ra == rb
    final_expected = rf(ra) == rf(rb)
    assert rule.statement().same_as(implies(final_guard, final_expected))
    assert len(theorem.axioms()) == 0

    premise = s.assume(context, final_guard, "guard")
    result = s.imp_elim(s.lift_to(rule, premise), s.hypothesis(premise))
    assert result.statement().same_as(final_expected)
    assert len(result.hypotheses()) == 1
    assert result.hypotheses()[0].same_as(final_guard)
    print("Accepted: f(a) = f(b), under a = b")
    print("Rejected: the same evidence for f(a) = f(c)")
    print("Retained theorem: a = b implies f(a) = f(b)")
    print("Reuse still requires evidence for a = b")


if __name__ == "__main__":
    main()
