"""Use repeat, or_else, and all_goals tactic combinators alongside deferred targeted rewrites."""

from judgment import Session, arrow, implies


def main():
    s = Session()
    A = s.declare_type("A")
    f = s.symbol("f", arrow(A, A))

    # 1. Combine repeat, or_else, and all_goals to discharge heterogeneous subgoals at once.
    mixed = s.theorem("mixed_goals")
    x = mixed.var("x", A)
    P = mixed.prop("P")
    mixed.goal(implies(P, (x == x) & (P & (f(x) == f(x)))))
    t = mixed.tactics()
    close_leaf = t.rfl().or_else(t.assumption())
    step = t.split().or_else(close_leaf).all_goals()
    pipeline = t.intro("hp").then(step.repeat()).require_closed()
    report = mixed.by(pipeline)
    assert report.status() == "solved"
    print("Combinator pipeline:", report.status(), "|", mixed.finish())

    # 2. Deferred targeted rewrites: outline the rewrite plan now, prove each equality later.
    chain = s.theorem("deferred_congr")
    a, b, c = chain.vars("a b c", A)
    ab = chain.given("ab", a == b)
    bc = chain.given("bc", b == c)
    chain.goal(f(a) == f(c))

    step1 = chain.rewrite("a_to_b", at=chain.lhs().at(a), to=b)
    step2 = chain.rewrite("b_to_c", at=chain.lhs().at(b), to=c)
    chain.rfl()
    assert len(chain.obligations()) == 2
    print("Pending equality obligations:", len(chain.obligations()))

    step1.exact(ab)
    step2.exact(bc)
    theorem = chain.finish()
    assert len(theorem.axioms()) == 0
    print("Deferred rewrites proved:", theorem)


if __name__ == "__main__":
    main()
