"""Keep a long square expansion readable with local names and explicit laws."""

from std.testing import assert_equal
from judgment import Session
from arithmetic_setup import arithmetic_setup


def main() raises:
    var s = Session()
    var algebra = arithmetic_setup(s)
    var proof = s.theorem("long_sum_squared")
    var values = proof.vars("a b c d e f g h", algebra.kind)
    var a, b, c, d = values[0], values[1], values[2], values[3]
    var e, f, g, h = values[4], values[5], values[6], values[7]
    var first = (a + b) * (c + d)
    var second = (e + f) * (g + h)
    var target = (first + second)**2 == first**2 + 2 * first * second + second**2
    proof.goal(target)

    # These are proof-local names with checked defining equations.
    var u = proof.define("u", first)
    var v = proof.define("v", second)
    _ = proof.focus().fold(u, all=True).fold(v, all=True)
    print("Let", proof.defining_eq(u).statement().format())
    print("Let", proof.defining_eq(v).statement().format())
    print("Abbreviated goal:", proof.current_goal().target().format())

    # Record the calculation, then prove its substantive steps explicitly.
    var chain = proof.calc((u + v)**2)
    chain.change((u + v) * (u + v), label="square")
    chain.eq(
        u * (u + v) + v * (u + v),
        using=s.fact("right_distrib"),
        label="right_distrib",
    )
    _ = chain.step("distribute", to=u**2 + u * v + v * u + v**2)
    _ = chain.step("collect", to=u**2 + 2 * u * v + v**2)
    assert_equal(len(chain.obligations()), 2)
    print(chain.format())

    # Check the later equality first. Every rewrite names its mathematical law.
    var collect = chain.select("collect")
    _ = collect.lhs().at(v * u).rw(s.fact("mul_comm"))
    _ = collect.lhs().at(u**2 + u * v + u * v).rw(s.fact("add_assoc"))
    _ = collect.lhs().at(u * v + u * v).rw(s.fact("double_product"))
    collect.rfl()

    var expand = chain.select("distribute")
    _ = expand.lhs().at(u * (u + v)).rw(s.fact("left_distrib"))
    _ = expand.lhs().at(v * (u + v)).rw(s.fact("left_distrib"))
    _ = expand.lhs().rw(s.fact("add_assoc"), reverse=True)
    expand.rfl()

    proof.exact(chain.finish())
    var theorem = proof.finish()
    assert_equal(len(theorem.axioms()), 4)
    assert_equal(theorem.axioms()[1], "mul_comm")
    assert_equal(len(theorem.admissions()), 0)
    print(theorem)
