"""Rewrite symbolic expressions directly with Transformation and obtain checked equality evidence."""

from judgment import Session, arrow


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

    # Define twice(x) = f(f(x)) and state an idempotence law for f.
    def_builder = s.definition("twice")
    x = def_builder.var("x", A)
    twice = def_builder.finish(f(f(x)))
    law_builder = s.axiom("f_idem")
    u = law_builder.var("u", A)
    f_idem = law_builder.finish(f(f(u)) == f(u))

    # Session-level Transformation: unfold twice(a), then rewrite f(f(a)) to f(a).
    tr = s.transform(twice(a))
    tr.focus().unfold(twice)
    tr.focus().rw(f_idem)
    eq_step = tr.evidence()
    assert tr.input().same_as(twice(a))
    assert tr.output().same_as(f(a))
    assert eq_step.statement().same_as(twice(a) == f(a))
    print("Input:", tr.input().format())
    print("Output:", tr.output().format())
    print("Checked evidence:", eq_step.statement().format())

    # Proof-level Transformation: rewrite under a local hypothesis and close the goal.
    proof = s.theorem("twice_congr")
    ab = proof.given("ab", a == b)
    proof.goal(twice(a) == f(b))
    ptr = proof.transform(twice(a))
    ptr.focus().unfold(twice)
    ptr.focus().rw(f_idem)
    ptr.at(a).rw(ab)
    proof.exact(ptr.evidence())
    theorem = proof.finish()
    assert len(theorem.axioms()) == 1
    print("Proved theorem:", theorem)


if __name__ == "__main__":
    main()
