"""Retain checked results across transactions, discard scratch work, and check out snapshots."""

from judgment import Session, JudgmentError
from judgment import LibErrorKind


def main():
    s = Session()
    base = s.snapshot()

    tx = s.transaction()
    candidate = s.prop("candidate")
    proof = s.theorem("candidate_refl", candidate == candidate)
    proof.rfl()
    old_fact = proof.finish()

    retained = tx.commit(expressions=[candidate], facts=[old_fact])
    kept_term = retained.expressions()[0]
    kept_fact = retained.facts()[0]
    expected = kept_term == kept_term
    assert kept_fact.statement().same_as(expected)
    assert s.fact("candidate_refl").statement().same_as(expected)

    old_rejected = False
    try:
        _ = old_fact.statement()
    except JudgmentError as e:
        old_rejected = e.kind == LibErrorKind.KERNEL
    assert old_rejected

    scratch = s.transaction()
    temporary = s.prop("temporary")
    scratch.discard()

    discarded_rejected = False
    try:
        _ = temporary.format()
    except JudgmentError as e:
        discarded_rejected = e.kind == LibErrorKind.KERNEL
    assert discarded_rejected

    s.checkout(base)
    rolled_back = False
    try:
        _ = s.fact("candidate_refl")
    except JudgmentError as e:
        rolled_back = e.kind == LibErrorKind.NO_MATCH
    assert rolled_back
    print("Kept proof: candidate = candidate")
    print("Old transaction handle: rejected")
    print("Discarded transaction handle: rejected")
    print("Checked out base snapshot: candidate_refl absent")


if __name__ == "__main__":
    main()
