"""Correct a supplied premise, then defer and recover the remaining goal."""

from std.testing import assert_equal, assert_true
from judgment_shell import LibErrorKind, Session, implies


def main() raises:
    var s = Session()
    var join = s.theorem("join")
    var Left = join.prop("Left")
    var Right = join.prop("Right")
    var left = join.given("left", Left)
    var right = join.given("right", Right)
    join.goal(Left & Right)
    join.exact(join.conjoin(left, right))
    var conjunction = join.finish()

    var P = s.prop("P")
    var Q = s.prop("Q")
    var target = implies(P & Q, Q & P)
    var proof = s.theorem("recover_application", target)
    var pair = proof.intro("pair")
    var p = proof.left(pair)
    var q = proof.right(pair)

    # Q & P needs Q first. Supplying P leaves the original goal intact.
    var before = proof.format()
    try:
        _ = proof.apply(conjunction, using=[p])
    except error:
        assert_equal(error.kind, LibErrorKind.NO_MATCH)
        print(error.message)
    assert_equal(proof.format(), before)

    # Correct the first premise; P remains an explicit obligation.
    _ = proof.apply(conjunction, using=[q])
    var second = proof.select("premise_2")
    second.sorry()
    var remaining = proof.obligations()
    assert_equal(len(remaining), 1)
    assert_true(remaining[0].target().same_as(P))
    assert_equal(remaining[0].status(), "deferred")
    print("Deferred premise:", remaining[0].path()[0], "requires", remaining[0].target().format())

    # Sorry saves unfinished work; it does not supply evidence.
    var blocked = False
    try:
        _ = proof.finish()
    except error:
        assert_equal(error.kind, LibErrorKind.SHAPE)
        blocked = True
    assert_true(blocked)
    print("Finish blocked:", blocked)

    # Recover by name, resume, and supply the checked fact explicitly.
    second = proof.select("premise_2")
    second.resume()
    second.exact(p)
    var theorem = proof.finish()
    assert_true(theorem.statement().same_as(target))
    assert_equal(len(theorem.axioms()), 0)
    assert_equal(len(theorem.admissions()), 0)
    print(theorem)
