"""Recognize common Session errors and recover through the public API."""

from judgment import Session, JudgmentError
from judgment import JudgmentError, LibErrorKind


def prove_with_budget(work):
    """Run a small proof in a session with the chosen work budget."""
    s = Session(work=work)
    truth = s.true_()
    proof = s.theorem("truth_refl", truth == truth)
    proof.rfl()
    _ = proof.finish()
    return True


def main():
    s = Session()
    prop = s.prop_type()

    # 1. Looking up a fact before it is declared raises NO_MATCH.
    rejected = False
    try:
        _ = s.fact("P_refl")
    except JudgmentError as e:
        rejected = e.kind == LibErrorKind.NO_MATCH
    assert rejected
    p = s.prop("P")
    p_proof = s.theorem("P_refl", p == p)
    p_proof.rfl()
    _ = p_proof.finish()
    assert s.fact("P_refl").statement().same_as(p == p)
    print("NO_MATCH: declare a fact before looking it up")

    # 2. Mixing handles from two different sessions raises WRONG_KERNEL.
    other = Session()
    foreign = other.true_()
    rejected = False
    try:
        _ = s.eq_refl(s.base(), foreign)
    except JudgmentError as e:
        rejected = e.kind == LibErrorKind.WRONG_KERNEL
    assert rejected
    assert other.eq_refl(other.base(), foreign).statement().same_as(foreign == foreign)
    print("WRONG_KERNEL: use the owning session, or rebuild in the receiving session")

    # 3. Using a handle from a discarded transaction raises KERNEL.
    tx = s.transaction()
    old = s.prop("temporary")
    tx.discard()
    rejected = False
    try:
        _ = s.eq_refl(s.base(), old)
    except JudgmentError as e:
        rejected = e.kind == LibErrorKind.KERNEL
    assert rejected
    # Recovery recreates the constant; old cannot be revived.
    fresh = s.prop("temporary")
    assert s.eq_refl(s.base(), fresh).statement().same_as(fresh == fresh)
    print("KERNEL: rebuild discarded handles, or retain them in commit")

    # 4. Using a fixed local variable in a sibling frame raises KERNEL.
    root = s.base()
    x = s.fix(root, "x", prop)
    y = s.fix(root, "y", prop)
    rejected = False
    try:
        _ = s.eq_refl(y[0], x[1])
    except JudgmentError as e:
        rejected = e.kind == LibErrorKind.KERNEL
    assert rejected
    valid = s.eq_refl(x[0], x[1])
    closed = s.forall_intro(x[0], valid)
    assert len(closed.hypotheses()) == 0
    print("KERNEL: prove in the local's frame, then generalize")

    # 5. Exhausting the session work allowance raises LIMIT.
    rejected = False
    try:
        _ = prove_with_budget(1)
    except JudgmentError as e:
        rejected = e.kind == LibErrorKind.LIMIT
    assert rejected
    assert prove_with_budget(100000)
    print("LIMIT: unfinished; a rebuilt request with more work succeeds")


if __name__ == "__main__":
    main()
