"""Replace a premise loop with one atomic, explicitly chosen tactic sequence."""

from judgment import Session, implies


def main() raises:
    var s = Session()
    var source = s.theorem("join")
    var Left = source.prop("Left")
    var Right = source.prop("Right")
    var left = source.given("left", Left)
    var right = source.given("right", Right)
    source.goal(Left & Right)
    source.exact(source.conjoin(left, right))
    var join = source.finish()

    var P = s.prop("P")
    var Q = s.prop("Q")
    var goal = implies(P, implies(Q, P & Q))

    # Direct application returns premises for an explicit loop.
    var direct = s.theorem("direct", goal)
    _ = direct.intro("p")
    _ = direct.intro("q")
    var premises = direct.apply(join)
    for i in range(len(premises)):
        premises[i].assumption()
    print(direct.finish())

    # Composition makes application and every premise proof one atomic attempt.
    var proof = s.theorem("composed", goal)
    _ = proof.intro("p")
    _ = proof.intro("q")
    var t = proof.tactics()
    var solve = t.apply(join).then(t.assumption()).require_closed()
    print("Composed:", proof.by(solve).status())
    print(proof.finish())

    # The same program cannot prove Q without evidence; even its first premise
    # solution rolls back, so the caller retains the complete original goal.
    var partial = s.theorem("partial", implies(P, P & Q))
    _ = partial.intro("p")
    var before = partial.format()
    print("Missing premise:", partial.by(solve).status())
    print("Draft unchanged:", partial.format() == before)
