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

from std.testing import assert_equal, assert_false, assert_true
from judgment import Session, StopSignal, implies


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

    # 1. Inspect, charge, and top up session work allowances.
    var before = s.work_remaining()
    s.spend(1_000)
    assert_equal(s.work_remaining(), before - 1_000)
    s.add_work(5_000)
    assert_equal(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.
    var proof = s.theorem("swap", implies(P & Q, Q & P))
    var h = proof.intro("h")
    assert_true(proof.fork_cost() > 0)
    var branch = proof.fork(40_000)
    var bh = branch.fact("h")
    branch.exact(branch.conjoin(branch.right(bh), branch.left(bh)))
    assert_equal(len(branch.obligations()), 0)
    assert_equal(len(proof.obligations()), 1)
    print("Proof fork solved independently; parent obligations:", len(proof.obligations()))

    # 3. Cancel a forked proof cleanly with StopSignal.
    var stop = StopSignal()
    assert_false(stop.requested())
    var canceled = proof.fork(40_000, stop)
    stop.request()
    assert_true(stop.requested())
    var ct = canceled.tactics()
    var report = canceled.by(ct.split())
    assert_equal(report.status(), "resource_exhausted")
    assert_false(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())
