"""Restore an exploratory rewrite and retry at a different occurrence."""

from judgment import Session, implies


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    R = s.prop("R")
    start = (P & R) | (P & R)
    wanted = (P & R) | (Q & R)
    statement = implies(P == Q, start == wanted)
    proof = s.theorem("retry_rewrite", statement)
    equal = proof.intro("equal")
    saved = proof.checkpoint()
    t = proof.tactics()

    # This checked rewrite succeeds, but reflexivity cannot finish this route.
    _ = proof.lhs().at(P, occurrence=1).rw(equal)
    trial = proof.by(t.rfl())
    assert trial.status() == "no_match" and not trial.changed()
    assert proof.target().same_as(((Q & R) | (P & R)) == wanted)
    print("First occurrence:", trial.status())

    # Undo the earlier direct rewrite; by only stages its own tactic program.
    proof.restore(saved)
    assert proof.target().same_as(start == wanted)
    print("Restored original goal:", proof.target().same_as(start == wanted))

    # Restoration invalidates old foci, so select the occurrence afresh.
    _ = proof.lhs().at(P, occurrence=2).rw(equal)
    proof.rfl()
    theorem = proof.finish()
    assert theorem.statement().same_as(statement)
    assert len(theorem.axioms()) == 0 and len(theorem.admissions()) == 0
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))


if __name__ == "__main__":
    main()
