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

from judgment import LibErrorKind, Session, implies, JudgmentError


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

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

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

    # Correct the first premise; P remains an explicit obligation.
    _ = proof.apply(conjunction, using=[q])
    second = proof.select("premise_2")
    second.sorry()
    remaining = proof.obligations()
    assert len(remaining) == 1
    assert remaining[0].target().same_as(P)
    assert 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.
    blocked = False
    try:
        _ = proof.finish()
    except JudgmentError as error:
        assert error.kind == LibErrorKind.SHAPE
        blocked = True
    assert 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)
    theorem = proof.finish()
    assert theorem.statement().same_as(target)
    assert len(theorem.axioms()) == 0
    assert len(theorem.admissions()) == 0
    print(theorem)


if __name__ == "__main__":
    main()
