"""Reusable square proofs from supplied operations and law evidence."""

from judgment import Expr, Fact, Session, TypeExpr


@fieldwise_init
struct SquareLemmas(Copyable):
    """Checked facts; collecting cross terms still requires commutation."""

    var expand: Fact
    var double_product: Fact
    var collect_of_commute: Fact


def right_distributivity(
    mut s: Session,
    kind: TypeExpr,
    mul_comm: Fact,
    left_distrib: Fact,
    name: String = "right_distrib",
) raises -> Fact:
    """Derive right distributivity when multiplication is commutative."""
    var proof = s.theorem(name)
    var abc = proof.vars("a b c", kind)
    var a, b, c = abc[0], abc[1], abc[2]
    proof.goal((a + b) * c == a * c + b * c)
    _ = proof.lhs().rw(mul_comm)
    _ = proof.lhs().rw(left_distrib)
    _ = proof.lhs().at(c * a).rw(mul_comm)
    _ = proof.lhs().at(c * b).rw(mul_comm)
    proof.rfl()
    return proof.finish()


def square_lemmas(
    mut s: Session,
    kind: TypeExpr,
    one: Expr,
    add_assoc: Fact,
    mul_one: Fact,
    left_distrib: Fact,
    right_distrib: Fact,
    prefix: String = "",
) raises -> SquareLemmas:
    """Prove square steps using the carrier's already-bound arithmetic notation.

    The supplied facts may be axioms or proved lemmas. Their actual dependencies
    flow through each kernel-checked rewrite. No law is assumed by this module.
    """
    var names = prefix
    if names.byte_length() != 0:
        names += "."

    var expand = s.theorem(names + "expand_square_product")
    var ab = expand.vars("a b", kind)
    var a, b = ab[0], ab[1]
    expand.goal((a + b) * (a + b) == a**2 + a * b + b * a + b**2)
    _ = expand.lhs().rw(right_distrib)
    _ = expand.lhs().at(a * (a + b)).rw(left_distrib)
    _ = expand.lhs().at(b * (a + b)).rw(left_distrib)
    _ = expand.lhs().rw(add_assoc, reverse=True)
    expand.rfl()
    var expanded = expand.finish()

    var double = s.theorem(names + "double_product")
    ab = double.vars("a b", kind)
    a, b = ab[0], ab[1]
    double.goal(a * b + a * b == 2 * a * b)
    # Inference does not split the numeral 2 into its defining sum of ones.
    _ = double.rhs().at(2 * a).rw(double.use(right_distrib, terms=[one, one, a]))
    _ = double.rhs().at(one * a, occurrence=1).rw(mul_one)
    _ = double.rhs().at(one * a).rw(mul_one)
    _ = double.rhs().rw(right_distrib)
    double.rfl()
    var doubled = double.finish()

    var collect = s.theorem(names + "collect_cross_terms_of_commute")
    ab = collect.vars("a b", kind)
    a, b = ab[0], ab[1]
    var commute = collect.given("commute", a * b == b * a)
    collect.goal(a**2 + a * b + b * a + b**2 == a**2 + 2 * a * b + b**2)
    _ = collect.lhs().at(b * a).rw(commute, reverse=True)
    _ = collect.lhs().at(a**2 + a * b + a * b).rw(add_assoc)
    _ = collect.lhs().at(a * b + a * b).rw(doubled)
    collect.rfl()
    return SquareLemmas(expanded, doubled, collect.finish())
