"""Select nested branches by stable names and literal path components."""

from judgment import LibErrorKind, Session, implies, JudgmentError


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    target = implies(P & Q, (Q & P) & (P & Q))
    proof = s.theorem("nested_pairs", target)
    pair = proof.intro("pair")
    _ = proof.split()
    left = proof.select("left")
    right = proof.select("right")
    _ = left.split()
    _ = right.split()

    # Both halves now contain a left goal. An ambiguous short name is refused.
    ambiguous = False
    try:
        _ = proof.select("left")
    except JudgmentError as error:
        ambiguous = error.kind == LibErrorKind.SHAPE
    assert ambiguous
    print("Ambiguous short name refused:", ambiguous)

    last = proof.select(["right", "right"])
    last.sorry()
    part = proof.select(["left", "left"])
    part.exact(part.right(pair))
    part = proof.select(["left", "right"])
    part.exact(part.left(pair))
    part = proof.select(["right", "left"])
    part.exact(part.left(pair))

    remaining = proof.obligations()[0]
    path = remaining.path()
    print("Remaining branch:", path[0], "/", path[1])
    last = proof.select(remaining.path())
    last.resume()
    last.exact(last.right(pair))
    theorem = proof.finish()
    assert theorem.statement().same_as(target)
    assert len(theorem.axioms()) == 0
    print(theorem)


if __name__ == "__main__":
    main()
