"""Account for work budgets, isolate speculative proof forks, and cancel attempts with StopSignal."""

from judgment import Session, StopSignal, implies


def main():
    s = Session(work=200_000)
    P = s.prop("P")
    Q = s.prop("Q")

    # 1. Inspect, charge, and top up session work allowances.
    before = s.work_remaining()
    s.spend(1_000)
    assert s.work_remaining() == before - 1_000
    s.add_work(5_000)
    assert s.work_remaining() == before + 4_000
    print("Budget accounting: spend and add_work exact")

    # 2. Fork a proof draft to explore an isolated branch without mutating the parent draft.
    proof = s.theorem("swap", implies(P & Q, Q & P))
    h = proof.intro("h")
    assert proof.fork_cost() > 0
    branch = proof.fork(40_000)
    bh = branch.fact("h")
    branch.exact(branch.conjoin(branch.right(bh), branch.left(bh)))
    assert len(branch.obligations()) == 0
    assert len(proof.obligations()) == 1
    print("Proof fork solved independently; parent obligations:", len(proof.obligations()))

    # 3. Cancel a forked proof cleanly with StopSignal.
    stop = StopSignal()
    assert not stop.requested()
    canceled = proof.fork(40_000, stop)
    stop.request()
    assert stop.requested()
    ct = canceled.tactics()
    report = canceled.by(ct.split())
    assert report.status() == "resource_exhausted"
    assert not report.changed()
    print("Signaled fork status:", report.status(), "| changed:", report.changed())

    # The original proof draft remains intact and finishes cleanly.
    proof.exact(proof.conjoin(proof.right(h), proof.left(h)))
    print("Parent finished:", proof.finish())


if __name__ == "__main__":
    main()
