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

from judgment import Session, arrow, forall, implies


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

    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.
    cancel = chain.step("cancel", to=x)
    premises = cancel.apply(law)
    assert len(premises) == 1
    assert premises[0].target().same_as(D(x)) == True
    premises[0].sorry()
    print(chain.format())
    remaining = chain.obligations()
    assert len(remaining) == 1
    print("Required premise:", remaining[0].target().format())

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


if __name__ == "__main__":
    main()
