"""Keep conditional calculation steps and their required evidence explicit."""

from std.testing import assert_equal
from judgment import Session, arrow, forall, implies


def main() raises:
    var s = Session()
    var proof = s.theorem("cancel_twice")
    var A = proof.type_var("A")
    var f = proof.var("f", arrow(A, A))
    var D = proof.var("D", arrow(A, s.prop_type()))
    var t = proof.bound_var("t", A)
    var law = proof.given("fix_on_D", forall(t, implies(D(t), f(t) == t)))
    var x = proof.var("x", A)
    var inside = proof.given("inside", D(f(x)))
    var at_x = proof.given("at_x", D(x))
    proof.goal(f(f(x)) == x)

    var chain = proof.calc(f(f(x)))
    # The endpoints and supplied condition determine the rule's arguments.
    chain.eq(
        f(x),
        using=law,
        premises=[inside],
        label="fix at f(x)",
    )

    # Apply infers x from the equality and exposes D(x) as a separate goal.
    var cancel = chain.step("cancel", to=x)
    var premises = cancel.apply(law)
    assert_equal(len(premises), 1)
    assert_equal(premises[0].target().same_as(D(x)), True)
    premises[0].sorry()
    print(chain.format())
    var remaining = chain.obligations()
    assert_equal(len(remaining), 1)
    print("Required premise:", remaining[0].target().format())

    # Having D(x) in the context does not discharge it automatically.
    var domain = chain.select(remaining[0])
    domain.resume()
    domain.exact(at_x)
    assert_equal(len(chain.obligations()), 0)
    proof.exact(chain.finish())
    var theorem = proof.finish()
    assert_equal(len(theorem.axioms()), 0)
    assert_equal(len(theorem.admissions()), 0)
    print(theorem)
