/-
Copyright: none. Author: swarm member m7 (Mathlib-only, no axioms).

# Iwasawa's construction of `p`-adic `L`-functions (Bhattacharya, MSc thesis, April 2024)

This file formalizes, in Lean 4 + Mathlib, the parts of Chapter 3 of

  Shubhrajit Bhattacharya, *On Some Congruences of Zeta and `L`-values at
  Negative Odd Integers*, MSc thesis, UBC, April 2024,
  <https://shubhrajit.com/thesis/chap3>

that can be stated and proved without any new number-theoretic infrastructure:
Theorem E (§3.1), Lemma 3.3, Lemma 3.5, and the algebra of the auxiliary power
series `h(T) = 1 - (1+p)/(1+T)` behind Definition 3.7 / Lemma 3.8.

Numbering `(3.k)` below refers to the equation tags of the PreTeXt edition of the
thesis.

No custom axioms are used.  Statements which need infrastructure that Mathlib
does not have (the Iwasawa algebra as an inverse limit of group rings, the
Coleman/Stickelberger compatibility, the Kubota–Leopoldt `L`-function) are
collected in `IwasawaStatements.lean` and are clearly marked as scaffolding.
-/
import Mathlib

open scoped BigOperators
open PowerSeries

namespace Bhattacharya

/-! ## §1 The Iwasawa algebra `Λ(ℤ_p)` and the auxiliary series `h(T)`

§3.1 defines `Λ(ℤ_p) = lim_n O[Γ_n]` (3.6) and quotes *Theorem E*: `Λ(ℤ_p) ≅ O⟦T⟧`
with `γ ↦ 1 + T`.  The identification of the inverse limit with a power series
ring is Mathlib-level infrastructure that does not exist yet; what exists, and
is all that §3.2 then uses, is the power series ring itself together with the
algebra of the element `h(T) = 1 - (1+p)/(1+T)` of (3.23).  -/

variable (p : ℕ) [hp : Fact p.Prime]

/-- `Λ(ℤ_p)`, presented via Theorem E as the power series ring `ℤ_p⟦T⟧`. -/
abbrev IwasawaAlgebra : Type := ℤ_[p]⟦X⟧

/-- The element `1 + T`, i.e. the image of a topological generator `γ` of
`Γ = 1 + pℤ_p` under the isomorphism of Theorem E (`γ ↦ 1+T`). -/
noncomputable def gamma : IwasawaAlgebra p := 1 + X

theorem gamma_eq : gamma p = 1 + X := rfl

/-- `1 + T` is a unit of `ℤ_p⟦T⟧`: its residue is `1`. -/
theorem gamma_isUnit : IsUnit (gamma p) := by
  rw [PowerSeries.isUnit_iff_constantCoeff]
  simp [gamma]

/-- The element `h(T) = 1 - (1+p)·(1+T)⁻¹` of (3.23). -/
noncomputable def h : IwasawaAlgebra p :=
  1 - C ((1 : ℤ_[p]) + (p : ℤ_[p])) * Ring.inverse (gamma p)

/-- Cleared form of (3.23): `h(T)·(1+T) = T - p`.  This is the equation that
makes the quotient in Definition 3.7 and Lemma 3.8 legitimate: `h` is a
non-zero-divisor, so `f = g/h` below is *determined*, not merely suggested. -/
theorem h_mul_gamma : h p * gamma p = X - C ((p : ℤ_[p])) := by
  have hunit : IsUnit (gamma p) := gamma_isUnit p
  have hinv : Ring.inverse (gamma p) * gamma p = 1 := Ring.inverse_mul_cancel _ hunit
  rw [h, sub_mul, one_mul, mul_assoc, hinv, mul_one, gamma, map_add, map_one]
  ring

theorem h_ne_zero : h p ≠ 0 := by
  intro hzero
  have : X - C ((p : ℤ_[p])) = 0 := by rw [← h_mul_gamma p, hzero, zero_mul]
  have hc := congrArg PowerSeries.constantCoeff this
  simp only [PowerSeries.constantCoeff_X, map_sub, map_zero,
    PowerSeries.constantCoeff_C] at hc
  -- `0 - p = 0` would force `p = 0` in `ℤ_[p]`, which has characteristic zero
  have hp0 : (p : ℤ_[p]) = 0 := by simpa using hc
  exact (Nat.Prime.ne_zero hp.out) (Nat.cast_eq_zero.mp hp0)

/-- `h` is not a zero divisor (`ℤ_p⟦T⟧` is a domain). -/
theorem h_mul_right_cancel {f g : IwasawaAlgebra p} (H : h p * f = h p * g) : f = g := by
  have : h p * (f - g) = 0 := by rw [mul_sub, H, sub_self]
  exact sub_eq_zero.mp ((mul_eq_zero.mp this).resolve_left (h_ne_zero p))

/-- **Definition 3.7 / Lemma 3.8, made precise.**  The element `f(T,θ) = g(T,θ)/h(T)`
is *uniquely determined* by `g` and `h`: any two solutions of `h·f = g` agree. -/
theorem f_unique {g f₁ f₂ : IwasawaAlgebra p} (H₁ : h p * f₁ = g) (H₂ : h p * f₂ = g) :
    f₁ = f₂ :=
  h_mul_right_cancel p (by rw [H₁, H₂])

/-- Existence counterpart of `f_unique`: over `ℤ_p⟦T⟧` the equation `h·f = g`
need not be solvable (this is *exactly* the content of Proposition 3.6: for the
particular `g(T,θ)` coming from `lim η_n(θ)`, the quotient exists because
`θ*` is odd).  We record the solvability predicate here. -/
def Solvable (g : IwasawaAlgebra p) : Prop := ∃ f, h p * f = g

theorem solvable_iff {g : IwasawaAlgebra p} {f : IwasawaAlgebra p} (H : h p * f = g) :
    Solvable p g := ⟨f, H⟩

/-! ## §2 Lemma 3.3: parity of characters of the second kind, and `ω(-1) = -1` -/

section Parity

variable {M : Type*} [Monoid M]

/-- Elementary core of Lemma 3.3(1): an element of order dividing `2` and odd
order is trivial.  Applied to `ψ(-1)` for `ψ` a character of the second kind. -/
theorem eq_one_of_pow_odd_eq_one_of_sq_eq_one {x : M} {m : ℕ} (hm : Odd m)
    (hpow : x ^ m = 1) (h2 : x ^ 2 = 1) : x = 1 := by
  obtain ⟨k, rfl⟩ := hm
  rw [pow_succ, pow_mul, h2, one_pow, one_mul] at hpow
  exact hpow

/-- **Lemma 3.3, first assertion.**  A Dirichlet character `ψ` of the second kind
(i.e. `ψ` is killed by `p^ν`, `p` odd) is even: `ψ(-1) = 1`. -/
theorem char_second_kind_even {G : Type*} [CommGroup G] (ψ : G →* M) {negOne : G}
    (h2 : negOne ^ 2 = 1) {ν : ℕ} (hν : Odd (p ^ ν)) (hpow : ψ negOne ^ p ^ ν = 1) :
    ψ negOne = 1 :=
  eq_one_of_pow_odd_eq_one_of_sq_eq_one hν hpow (by rw [← map_pow, h2, map_one])

end Parity

section Teichmuller

variable {R : Type*} [CommRing R] [IsDomain R] {q : ℕ} [Fact q.Prime]

/-- **Lemma 3.3, second assertion** (abstract form).  Let `q` be an odd prime and
let `ω : (ℤ/q)^× → R^×` be any character whose values are `(q-1)`-st roots of
unity and which reduces to the identity modulo `q`.  Then `ω(-1) = -1`.

This is exactly the thesis's argument: `ω(-1)² = ω(1) = 1` forces
`ω(-1) = ±1`, and `ω(-1) ≡ -1 (mod q)` with `q` odd excludes `+1`. -/
theorem teichmuller_neg_one (ω : (ZMod q)ˣ →* Rˣ) (hω : (ω (-1) : R) ≠ 1)
    (hΩ : ((ω (-1) : Rˣ) : R) ^ 2 = 1) : ((ω (-1) : Rˣ) : R) = -1 := by
  rcases sq_eq_one_iff.mp hΩ with h | h
  · exact absurd h hω
  · exact h

end Teichmuller



section Idempotents
variable {k : Type*} [Field k] [CharZero k] {G : Type*} [CommGroup G] [Fintype G]

/-- (3.18): `ε_χ = |G|⁻¹ ∑_{σ∈G} χ(σ)σ⁻¹`, Definition 3.4 of the thesis. -/
noncomputable def charIdem (χ : G →* kˣ) : MonoidAlgebra k G :=
  ∑ g : G, MonoidAlgebra.single g ((Fintype.card G : k)⁻¹ * (χ (g⁻¹) : k))

/-- Orthogonality: a nontrivial character of a finite group sums to zero. -/
theorem sum_char_eq_zero (χ : G →* kˣ) (hχ : χ ≠ 1) : ∑ g : G, (χ g : k) = 0 := by
  classical
  obtain ⟨g₀, hg₀⟩ : ∃ g₀, χ g₀ ≠ 1 := by
    by_contra h
    push Not at h
    exact hχ (MonoidHom.ext fun g => by simpa using h g)
  have key : (∑ g : G, (χ (g₀ * g) : k)) = ∑ g : G, (χ g : k) :=
    Fintype.sum_equiv (Equiv.mulLeft g₀) (fun g => (χ (g₀ * g) : k)) (fun g => (χ g : k))
      (fun g => rfl)
  have hS : (χ g₀ : k) * ∑ g : G, (χ g : k) = ∑ g : G, (χ g : k) := by
    rw [Finset.mul_sum, ← key]
    exact Finset.sum_congr rfl fun g _ => by rw [map_mul]; push_cast; ring
  have hzero : ((χ g₀ : k) - 1) * (∑ g : G, (χ g : k)) = 0 := by
    rw [sub_mul, one_mul, hS, sub_self]
  have hne : (χ g₀ : k) - 1 ≠ 0 := by
    have : (χ g₀ : k) ≠ 1 := fun h => hg₀ (Units.ext (by simpa using h))
    exact sub_ne_zero.mpr this
  exact (mul_eq_zero.mp hzero).resolve_left hne

variable (χ : G →* kˣ)

/-- Property (i) of Lemma 3.5: `ε_χ · g = χ(g) · ε_χ`. -/
theorem charIdem_mul_of (g : G) :
    charIdem χ * MonoidAlgebra.of k G g
      = algebraMap k (MonoidAlgebra k G) (χ g : k) * charIdem χ := by
  classical
  have hLHS : charIdem χ * MonoidAlgebra.of k G g
      = ∑ t : G, MonoidAlgebra.single (t * g) ((Fintype.card G : k)⁻¹ * (χ (t⁻¹) : k)) := by
    rw [charIdem, MonoidAlgebra.of_apply, Finset.sum_mul]
    exact Finset.sum_congr rfl fun t _ => by
      rw [MonoidAlgebra.single_mul_single, mul_one]
  have hreindex : (∑ t : G, MonoidAlgebra.single (t * g) ((Fintype.card G : k)⁻¹ * (χ (t⁻¹) : k)))
      = ∑ s : G, MonoidAlgebra.single s
          ((Fintype.card G : k)⁻¹ * (χ g : k) * (χ (s⁻¹) : k)) := by
    have key : (∑ t : G, MonoidAlgebra.single (t * g)
          ((Fintype.card G : k)⁻¹ * (χ g : k) * (χ ((t * g)⁻¹) : k)))
        = ∑ s : G, MonoidAlgebra.single s
          ((Fintype.card G : k)⁻¹ * (χ g : k) * (χ (s⁻¹) : k)) :=
      Fintype.sum_equiv (Equiv.mulRight g)
        (fun t => MonoidAlgebra.single (t * g)
          ((Fintype.card G : k)⁻¹ * (χ g : k) * (χ ((t * g)⁻¹) : k)))
        (fun s => MonoidAlgebra.single s ((Fintype.card G : k)⁻¹ * (χ g : k) * (χ (s⁻¹) : k)))
        (fun t => rfl)
    rw [← key]
    have hcoef : ∀ t : G, (χ (t⁻¹) : k) = (χ g : k) * (χ ((t * g)⁻¹) : k) := by
      intro t
      rw [mul_inv_rev, map_mul, map_inv, map_inv, Units.val_mul, Units.val_inv_eq_inv_val,
        Units.val_inv_eq_inv_val, ← mul_assoc, mul_inv_cancel₀ (χ g).isUnit.ne_zero, one_mul]
    exact Finset.sum_congr rfl fun t _ => by
      congr 1
      rw [hcoef t, ← mul_assoc]
  have hRHS : algebraMap k (MonoidAlgebra k G) (χ g : k) * charIdem χ
      = ∑ s : G, MonoidAlgebra.single s
          ((Fintype.card G : k)⁻¹ * (χ g : k) * (χ (s⁻¹) : k)) := by
    rw [charIdem, Finset.mul_sum]
    exact Finset.sum_congr rfl fun s _ => by
      rw [MonoidAlgebra.single_eq_algebraMap_mul_of, MonoidAlgebra.single_eq_algebraMap_mul_of,
        ← mul_assoc, ← map_mul]
      rw [show (χ g : k) * ((Fintype.card G : k)⁻¹ * (χ (s⁻¹) : k))
        = (Fintype.card G : k)⁻¹ * (χ g : k) * (χ (s⁻¹) : k) from by ring]
  rw [hLHS, hreindex, hRHS]

/-- Master computation behind both identities of Lemma 3.5: for any coefficient
function `a : G → k`, `ε_χ · (∑ a(s)·s) = (∑ a(s)·χ(s)) · ε_χ`. -/
theorem charIdem_mul_sum (χ : G →* kˣ) (a : G → k) :
    charIdem χ * (∑ s : G, MonoidAlgebra.single s (a s))
      = algebraMap k (MonoidAlgebra k G) (∑ s : G, a s * (χ s : k)) * charIdem χ := by
  rw [Finset.mul_sum]
  have hterm : ∀ s : G, charIdem χ * MonoidAlgebra.single s (a s)
      = algebraMap k (MonoidAlgebra k G) (a s * (χ s : k)) * charIdem χ := by
    intro s
    rw [MonoidAlgebra.single_eq_algebraMap_mul_of, ← mul_assoc, ← Algebra.commutes (a s),
      mul_assoc, charIdem_mul_of, ← mul_assoc, ← map_mul]
  rw [Finset.sum_congr rfl fun s _ => hterm s, ← Finset.sum_mul, ← map_sum]

/-- Lemma 3.5, second identity: `ε_χ · ε_ψ = 0` for `χ ≠ ψ`. -/
theorem charIdem_mul_charIdem (ψ : G →* kˣ) :
    charIdem χ * charIdem ψ
      = algebraMap k (MonoidAlgebra k G)
          (∑ s : G, ((Fintype.card G : k)⁻¹ * (ψ (s⁻¹) : k)) * (χ s : k)) * charIdem χ := by
  classical
  have hsum : charIdem χ * charIdem ψ
      = ∑ s : G, algebraMap k (MonoidAlgebra k G)
          (((Fintype.card G : k)⁻¹ * (ψ (s⁻¹) : k)) * (χ s : k)) * charIdem χ := by
    rw [show charIdem ψ
        = ∑ s : G, MonoidAlgebra.single s ((Fintype.card G : k)⁻¹ * (ψ (s⁻¹) : k)) from rfl,
      charIdem_mul_sum χ (fun s => (Fintype.card G : k)⁻¹ * (ψ (s⁻¹) : k))]
    rw [← Finset.sum_mul, ← map_sum]
  rw [hsum, ← Finset.sum_mul, ← map_sum]

/-- Lemma 3.5, first identity: `ε_χ` is idempotent. -/
theorem charIdem_idem : charIdem χ * charIdem χ = charIdem χ := by
  have hcard : (Fintype.card G : k) ≠ 0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero
  rw [charIdem_mul_charIdem]
  have hcoef : (∑ s : G, ((Fintype.card G : k)⁻¹ * (χ (s⁻¹) : k)) * (χ s : k)) = 1 := by
    have hterm : ∀ s : G, ((Fintype.card G : k)⁻¹ * (χ (s⁻¹) : k)) * (χ s : k)
        = (Fintype.card G : k)⁻¹ := by
      intro s
      have h1 : (χ (s⁻¹) : k) = ((χ s : k))⁻¹ := by
        rw [map_inv]; simp
      rw [h1, mul_assoc, inv_mul_cancel₀, mul_one]
      exact (χ s).isUnit.ne_zero
    rw [Finset.sum_congr rfl fun s _ => hterm s, Finset.sum_const, Finset.card_univ,
      nsmul_eq_mul]
    exact mul_inv_cancel₀ hcard
  rw [hcoef, map_one, one_mul]

/-- Lemma 3.5, second identity: `ε_χ · ε_ψ = 0` for `χ ≠ ψ`. -/
theorem charIdem_mul_eq_zero {ψ : G →* kˣ} (h : χ ≠ ψ) : charIdem χ * charIdem ψ = 0 := by
  have hcard : (Fintype.card G : k) ≠ 0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero
  rw [charIdem_mul_charIdem]
  have hcoef : (∑ s : G, ((Fintype.card G : k)⁻¹ * (ψ (s⁻¹) : k)) * (χ s : k)) = 0 := by
    have hterm : ∀ s : G, ((Fintype.card G : k)⁻¹ * (ψ (s⁻¹) : k)) * (χ s : k)
        = (Fintype.card G : k)⁻¹ * ((χ * ψ⁻¹) s : k) := by
      intro s
      have h1 : (ψ (s⁻¹) : k) = ((ψ s : k))⁻¹ := by rw [map_inv]; simp
      have h2 : ((χ * ψ⁻¹) s : k) = (χ s : k) * ((ψ s : k))⁻¹ := by
        rw [show ((χ * ψ⁻¹) s : kˣ) = (χ s) * (ψ s)⁻¹ from rfl, Units.val_mul,
          Units.val_inv_eq_inv_val]
      rw [h1, h2]
      ring
    have hne : χ * ψ⁻¹ ≠ 1 := by
      intro hh
      apply h
      rw [← mul_one χ, ← inv_mul_cancel ψ, ← mul_assoc, hh]
      simp
    rw [Finset.sum_congr rfl fun s _ => hterm s, ← Finset.mul_sum, sum_char_eq_zero _ hne,
      mul_zero]
  rw [hcoef, map_zero, zero_mul]

end Idempotents

/-! ## §3 (`ZMod`-model check) The group ring of `Γ_n = ℤ/p^n` -/

section GammaN

/-- `Γ_n = Γ/Γ^{p^n} ≅ ℤ/p^n` (3.11), modelled additively as `ZMod (p^n)`; `γ_n` is
the image of a topological generator `γ` of `Γ = 1+pℤ_p`. -/
noncomputable abbrev gammaN (p n : ℕ) [Fact p.Prime] : MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n))) :=
  MonoidAlgebra.of ℤ_[p] (Multiplicative (ZMod (p ^ n))) (Multiplicative.ofAdd 1)

/-- The relation `γ_n^{p^n} = 1`, i.e. `ℤ_p[Γ_n]` is a quotient of `ℤ_p[T]` by a
divisor of `(1+T)^{p^n} - 1`, which is what (3.28) uses when it reduces `g(T,θ)`
modulo `(1+T)^{p^n} - 1`. -/
theorem gammaN_pow (p n : ℕ) [Fact p.Prime] : gammaN p n ^ (p ^ n) = 1 := by
  rw [← map_pow]
  have h : (Multiplicative.ofAdd (1 : ZMod (p ^ n))) ^ (p ^ n) = 1 := by
    show Multiplicative.ofAdd ((p ^ n) • (1 : ZMod (p ^ n))) = Multiplicative.ofAdd 0
    rw [show (p ^ n) • (1 : ZMod (p ^ n)) = ((p ^ n : ℕ) : ZMod (p ^ n)) by
      simp [nsmul_eq_mul], ZMod.natCast_self]
  rw [h, map_one]

end GammaN

/-! ## §4 Statement layer for §3.2 — SCAFFOLDING ONLY

Only statements that are (a) true and (b) typeable with today's Mathlib are written
down here; each carries the list of missing bricks that blocks its proof.
Proposition 3.6 and Theorem 3.9 are *not* stated in Lean: their types mention the
Kubota–Leopoldt function `L_p(s,χ)` on `{s ∈ ℂ_p : |s|_p < p^{1-1/(p-1)}}`, the
generalized Bernoulli numbers `B_{n,χ}`, the Teichmüller character `ω` and the
Stickelberger limit `lim_n η_n(θ) ∈ lim_n ℤ_p[Γ_n]`, none of which exists in Mathlib;
writing them over free parameters would be vacuous and is therefore avoided.
Their exact statements (with equation tags) are in `Ch3-inventory.md`, which also
lists, node by node, the bricks that must be built first.
-/

/-- Powers of the additive generator of `ZMod n`. -/
theorem ofAdd_one_pow (n k : ℕ) :
    (Multiplicative.ofAdd (1 : ZMod n)) ^ k = Multiplicative.ofAdd ((k : ZMod n)) := by
  induction k with
  | zero => simp
  | succ k ih =>
    rw [pow_succ, ih, ← ofAdd_add]
    push_cast
    rfl


theorem pow_pos_p (n : ℕ) : 0 < p ^ n :=
  pow_pos (by have := hp.out.two_le; omega) n

/-! ## §2  The distinguished polynomial `g(T) = (1+T)^{p^n} - 1` -/

/-- `g(T) = (1+T)^{p^n} - 1`, as a polynomial. -/
noncomputable def gPoly (n : ℕ) : Polynomial ℤ_[p] :=
  (1 + Polynomial.X) ^ (p ^ n) - 1

/-- `g` as a power series. -/
noncomputable def gSeries (n : ℕ) : PowerSeries ℤ_[p] :=
  (1 + PowerSeries.X) ^ (p ^ n) - 1

theorem coe_gPoly (n : ℕ) :
    ((gPoly p n : Polynomial ℤ_[p]) : PowerSeries ℤ_[p]) = gSeries p n := by
  rw [gPoly, gSeries]
  push_cast
  ring

/-- The coefficient of `T^k` in `(1+T)^N`. -/
theorem coeff_one_add_X_pow (N k : ℕ) :
    ((1 + Polynomial.X : Polynomial ℤ_[p]) ^ N).coeff k = ((N.choose k : ℕ) : ℤ_[p]) := by
  have h : (1 + Polynomial.X : Polynomial ℤ_[p]) = Polynomial.X + Polynomial.C (1 : ℤ_[p]) := by
    rw [Polynomial.C_1, add_comm]
  rw [h, Polynomial.coeff_X_add_C_pow]
  simp

theorem coeff_gPoly (n k : ℕ) :
    (gPoly p n).coeff k = ((p ^ n).choose k : ℤ_[p]) - (if k = 0 then 1 else 0) := by
  rw [gPoly, Polynomial.coeff_sub, coeff_one_add_X_pow p, Polynomial.coeff_one]

theorem natDegree_gPoly (n : ℕ) : (gPoly p n).natDegree = p ^ n := by
  refine Polynomial.natDegree_eq_of_le_of_coeff_ne_zero ?_ ?_
  · rw [Polynomial.natDegree_le_iff_coeff_eq_zero]
    intro k hk
    rw [coeff_gPoly]
    rw [Nat.choose_eq_zero_of_lt hk]
    have : k ≠ 0 := by omega
    simp [this]
  · rw [coeff_gPoly, Nat.choose_self]
    have h0 : p ^ n ≠ 0 := (pow_pos_p p n).ne'
    rw [if_neg h0, sub_zero]
    norm_num

theorem monic_gPoly (n : ℕ) : (gPoly p n).Monic := by
  rw [Polynomial.Monic, Polynomial.leadingCoeff, natDegree_gPoly p n]
  have h0 : p ^ n ≠ 0 := (pow_pos_p p n).ne'
  rw [coeff_gPoly, Nat.choose_self, if_neg h0, sub_zero]
  norm_num

theorem isWeaklyEisensteinAt_gPoly (n : ℕ) :
    (gPoly p n).IsWeaklyEisensteinAt (IsLocalRing.maximalIdeal ℤ_[p]) := by
  rw [Polynomial.isWeaklyEisensteinAt_iff]
  intro k hk
  rw [natDegree_gPoly p n] at hk
  rw [coeff_gPoly, PadicInt.maximalIdeal_eq_span_p, Ideal.mem_span_singleton]
  by_cases hk0 : k = 0
  · subst hk0
    simp
  · simp only [hk0, if_false, sub_zero]
    obtain ⟨m, hm⟩ := Nat.Prime.dvd_choose_pow hp.out hk0 (show k ≠ p ^ n by omega)
    rw [hm]
    push_cast
    exact dvd_mul_right _ _

/-- **`g` is distinguished at `(p)`.** -/
theorem isDistinguished_gPoly (n : ℕ) :
    Polynomial.IsDistinguishedAt (gPoly p n) (IsLocalRing.maximalIdeal ℤ_[p]) :=
  ⟨isWeaklyEisensteinAt_gPoly p n, monic_gPoly p n⟩

section Iso

/-! ## §3  The two algebraic isomorphisms

We prove `ℤ_p⟦T⟧/((1+T)^{p^n}-1) ≃ ℤ_p[Γ_n]` in two steps: first
`ℤ_p[T]/(g) ≃ ℤ_p⟦T⟧/(g)` (Weierstrass division, `g` being distinguished),
then `ℤ_p[Γ_n] ≃ ℤ_p[T]/(g)` via `T ↦ γ_n - 1`. -/

/-- The quotient `ℤ_p[T]/(g)`. -/
noncomputable abbrev Qpoly (n : ℕ) : Type :=
  Polynomial ℤ_[p] ⧸ Ideal.span {gPoly p n}

/-- The quotient `ℤ_p⟦T⟧/(g)`. -/
noncomputable abbrev Qseries (n : ℕ) : Type :=
  PowerSeries ℤ_[p] ⧸ Ideal.span {gSeries p n}


/-- The class of `1 + T` in `ℤ_p[T]/(g)`. -/
noncomputable def clsX (n : ℕ) : Qpoly p n :=
  Ideal.Quotient.mk (Ideal.span {gPoly p n}) (1 + Polynomial.X)

theorem clsX_pow (n : ℕ) : clsX p n ^ (p ^ n) = 1 := by
  have hg : (1 + Polynomial.X : Polynomial ℤ_[p]) ^ (p ^ n) = gPoly p n + 1 := by
    rw [gPoly]; ring
  have hmem : Ideal.Quotient.mk (Ideal.span {gPoly p n}) (gPoly p n) = 0 := by
    rw [Ideal.Quotient.eq_zero_iff_mem]
    exact Ideal.subset_span (Set.mem_singleton _)
  rw [clsX, ← map_pow, hg, map_add, hmem, zero_add, map_one]

/-- The unit `1 + T` of `ℤ_p[T]/(g)`; its `p^n`-th power is `1`. -/
noncomputable def unitX (n : ℕ) : (Qpoly p n)ˣ where
  val := clsX p n
  inv := clsX p n ^ (p ^ n - 1)
  val_inv := by
    rw [mul_comm, ← pow_succ, Nat.sub_add_cancel (pow_pos_p p n), clsX_pow]
  inv_val := by
    rw [← pow_succ, Nat.sub_add_cancel (pow_pos_p p n), clsX_pow]

theorem unitX_val (n : ℕ) : ((unitX p n : (Qpoly p n)ˣ) : Qpoly p n) = clsX p n := rfl

theorem unitX_pow (n : ℕ) : unitX p n ^ (p ^ n) = 1 := by
  apply Units.ext
  rw [Units.val_pow_eq_pow_val, unitX_val, clsX_pow, Units.val_one]

/-- `ℤ ∋ z ↦ u^z`, as an additive hom into the additive group of the unit group. -/
noncomputable def zpowAddHom (n : ℕ) : ℤ →+ Additive (Qpoly p n)ˣ where
  toFun z := Additive.ofMul (unitX p n ^ z)
  map_zero' := by simp
  map_add' := by
    intro a b
    simp [zpow_add]

theorem zpowAddHom_apply (n : ℕ) (z : ℤ) :
    zpowAddHom p n z = Additive.ofMul (unitX p n ^ z) := rfl

/-- The additive hom `ZMod (p^n) → (ℤ_p[T]/(g))ˣ` sending `1` to `1+T`. -/
noncomputable def zmodAddHom (n : ℕ) : ZMod (p ^ n) →+ Additive (Qpoly p n)ˣ :=
  ZMod.lift (p ^ n) ⟨zpowAddHom p n, by
    show Additive.ofMul (unitX p n ^ (((p ^ n : ℕ)) : ℤ)) = 0
    rw [zpow_natCast, unitX_pow]
    rfl⟩

theorem zmodAddHom_apply (n : ℕ) (x : ZMod (p ^ n)) :
    zmodAddHom p n x = ZMod.lift (p ^ n) ⟨zpowAddHom p n, by
      show Additive.ofMul (unitX p n ^ (((p ^ n : ℕ)) : ℤ)) = 0
      rw [zpow_natCast, unitX_pow]
      rfl⟩ x := rfl

/-- The multiplicative hom `Γ_n → (ℤ_p[T]/(g))ˣ`, `γ_n ↦ 1 + T`. -/
noncomputable def grpHom (n : ℕ) : Multiplicative (ZMod (p ^ n)) →* (Qpoly p n)ˣ where
  toFun m := (zmodAddHom p n m.toAdd).toMul
  map_one' := by
    show (zmodAddHom p n (Multiplicative.toAdd 1)).toMul = 1
    rw [show Multiplicative.toAdd (1 : Multiplicative (ZMod (p ^ n))) = 0 from rfl, map_zero]
    rfl
  map_mul' := by
    intro a b
    show (zmodAddHom p n (Multiplicative.toAdd (a * b))).toMul =
      (zmodAddHom p n a.toAdd).toMul * (zmodAddHom p n b.toAdd).toMul
    rw [toAdd_mul, map_add, toMul_add]

theorem grpHom_ofAdd (n k : ℕ) :
    grpHom p n (Multiplicative.ofAdd ((k : ZMod (p ^ n)))) = unitX p n ^ k := by
  have hcast : ((k : ℕ) : ZMod (p ^ n)) = ((k : ℤ) : ZMod (p ^ n)) := by push_cast; ring
  rw [hcast]
  show (zmodAddHom p n ((k : ℤ) : ZMod (p ^ n))).toMul = _
  rw [zmodAddHom_apply, ZMod.lift_coe, zpowAddHom_apply, zpow_natCast]
  rfl

/-! ### The algebra map `ℤ_p[Γ_n] → ℤ_p[T]/(g)`, `γ_n ↦ 1 + T` -/

/-- The inverse isomorphism `ℤ_p[Γ_n] → ℤ_p[T]/(g)` of (4.6): `γ_n ↦ 1 + T`. -/
noncomputable def psi (n : ℕ) :
    MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n))) →ₐ[ℤ_[p]] Qpoly p n :=
  (MonoidAlgebra.lift ℤ_[p] (Qpoly p n) (Multiplicative (ZMod (p ^ n))))
    ((Units.coeHom (Qpoly p n)).comp (grpHom p n))

theorem psi_gammaN (n : ℕ) : psi p n (gammaN p n) = clsX p n := by
  have h1 : (1 : ZMod (p ^ n)) = ((1 : ℕ) : ZMod (p ^ n)) := by norm_num
  rw [psi, gammaN, MonoidAlgebra.lift_of]
  rw [show (Multiplicative.ofAdd (1 : ZMod (p ^ n)))
      = Multiplicative.ofAdd ((1 : ℕ) : ZMod (p ^ n)) from by rw [← h1]]
  rw [MonoidHom.comp_apply, Units.coeHom_apply, grpHom_ofAdd, pow_one, unitX_val]

/-! ### The algebra map `ℤ_p[T]/(g) → ℤ_p[Γ_n]`, `T ↦ γ_n - 1` -/

theorem aeval_gPoly (n : ℕ) : Polynomial.aeval (gammaN p n - 1) (gPoly p n) = 0 := by
  have h1 : Polynomial.aeval (gammaN p n - 1) (1 + Polynomial.X : Polynomial ℤ_[p])
      = gammaN p n := by
    rw [map_add, map_one, Polynomial.aeval_X]
    ring
  have hone : Polynomial.aeval (gammaN p n - 1) (1 : Polynomial ℤ_[p]) = 1 := map_one _
  rw [gPoly, map_sub, map_pow, h1, hone, gammaN_pow, sub_self]

/-- The isomorphism `ℤ_p[T]/(g) → ℤ_p[Γ_n]` of (4.6): `T ↦ γ_n - 1`. -/
noncomputable def phi (n : ℕ) :
    Qpoly p n →ₐ[ℤ_[p]] MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n))) :=
  Ideal.Quotient.liftₐ (Ideal.span {gPoly p n}) (Polynomial.aeval (gammaN p n - 1))
    (by
      intro a ha
      rw [Ideal.mem_span_singleton] at ha
      obtain ⟨b, hb⟩ := ha
      rw [hb, map_mul, aeval_gPoly, zero_mul])

theorem phi_mk (n : ℕ) (a : Polynomial ℤ_[p]) :
    phi p n (Ideal.Quotient.mk (Ideal.span {gPoly p n}) a)
      = Polynomial.aeval (gammaN p n - 1) a := rfl

theorem phi_clsX (n : ℕ) : phi p n (clsX p n) = gammaN p n := by
  have h1 : Polynomial.aeval (gammaN p n - 1) (1 + Polynomial.X : Polynomial ℤ_[p])
      = gammaN p n := by
    rw [map_add, map_one, Polynomial.aeval_X]
    ring
  rw [clsX, phi_mk, h1]

theorem phi_unitX (n : ℕ) : phi p n (unitX p n : Qpoly p n) = gammaN p n := by
  rw [unitX_val, phi_clsX]

/-! ### The two composites are the identity -/

theorem psi_phi (n : ℕ) : (psi p n).comp (phi p n) = AlgHom.id ℤ_[p] (Qpoly p n) := by
  have hone : (psi p n) (1 : MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n)))) = 1 :=
    map_one _
  have hone' : (phi p n) (1 : Qpoly p n) = 1 := map_one _
  have h1 : ((psi p n).comp (phi p n)) (clsX p n - 1) = clsX p n - 1 := by
    rw [AlgHom.comp_apply, map_sub, phi_clsX, map_sub, hone', hone, psi_gammaN]
  have hX : ((psi p n).comp (phi p n))
      ((Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n})) Polynomial.X)
      = (Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n})) Polynomial.X := by
    have hcls : (Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n})) Polynomial.X
        = clsX p n - 1 := by
      rw [Ideal.Quotient.mkₐ_eq_mk, clsX]
      have hpol : (Polynomial.X : Polynomial ℤ_[p]) = (1 + Polynomial.X) - 1 := by ring
      rw [hpol]
      simp
    rw [hcls]
    exact h1
  have h : ((psi p n).comp (phi p n)).comp
        (Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n}))
      = (AlgHom.id ℤ_[p] (Qpoly p n)).comp
        (Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n})) :=
    Polynomial.algHom_ext hX
  refine AlgHom.ext fun y => ?_
  obtain ⟨a, rfl⟩ := Ideal.Quotient.mk_surjective y
  exact congr($h a)

theorem phi_psi (n : ℕ) :
    (phi p n).comp (psi p n)
      = AlgHom.id ℤ_[p] (MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n)))) := by
  have key : ∀ m : Multiplicative (ZMod (p ^ n)),
      phi p n (psi p n (MonoidAlgebra.of ℤ_[p] (Multiplicative (ZMod (p ^ n))) m))
        = MonoidAlgebra.of ℤ_[p] (Multiplicative (ZMod (p ^ n))) m := by
    intro m
    have : NeZero (p ^ n) := ⟨(pow_pos_p p n).ne'⟩
    have hm : (Multiplicative.ofAdd ((m.toAdd).val : ZMod (p ^ n))) = m := by
      rw [ZMod.natCast_zmod_val, ofAdd_toAdd]
    rw [psi, MonoidAlgebra.lift_of, MonoidHom.comp_apply, Units.coeHom_apply, ← hm,
      grpHom_ofAdd, Units.val_pow_eq_pow_val, map_pow, phi_unitX, gammaN, ← map_pow,
      ofAdd_one_pow]
  rw [MonoidAlgebra.lift_unique' ((phi p n).comp (psi p n)),
    MonoidAlgebra.lift_unique' (AlgHom.id ℤ_[p] _)]
  congr 1
  refine MonoidHom.ext fun m => ?_
  simpa using key m

/-! ### The distinguished quotient isomorphism -/

theorem span_coe_gPoly (n : ℕ) :
    Ideal.span {((gPoly p n : Polynomial ℤ_[p]) : PowerSeries ℤ_[p])}
      = Ideal.span {gSeries p n} := by
  rw [coe_gPoly]

noncomputable def polySeriesEquiv (n : ℕ) :
    Qpoly p n ≃ₐ[ℤ_[p]] Qseries p n :=
  (Polynomial.IsDistinguishedAt.algEquivQuotient (isDistinguished_gPoly p n)).trans
    (Ideal.quotientEquivAlgOfEq ℤ_[p] (span_coe_gPoly p n))

theorem polySeriesEquiv_mk (n : ℕ) (f : Polynomial ℤ_[p]) :
    polySeriesEquiv p n (Ideal.Quotient.mk (Ideal.span {gPoly p n}) f)
      = Ideal.Quotient.mk (Ideal.span {gSeries p n}) ((f : PowerSeries ℤ_[p])) := by
  rw [polySeriesEquiv, AlgEquiv.trans_apply]
  simp [Polynomial.IsDistinguishedAt.algEquivQuotient_apply, Ideal.quotientEquivAlgOfEq_mk]

end Iso

section Final

/-- The `ℤ_p`-algebra surjection `ℤ_p⟦T⟧ ↠ ℤ_p[Γ_n]` of Theorem E: reduce modulo
`(1+T)^{p^n} - 1` and then apply `T ↦ γ_n - 1`. -/
noncomputable def Phi (n : ℕ) :
    PowerSeries ℤ_[p] →+* MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n))) :=
  ((phi p n).toRingHom.comp (polySeriesEquiv p n).symm.toRingHom).comp
    (Ideal.Quotient.mk (Ideal.span {gSeries p n}))

theorem coe_one_add_X :
    ((1 + Polynomial.X : Polynomial ℤ_[p]) : PowerSeries ℤ_[p]) = 1 + PowerSeries.X := by
  push_cast
  ring

theorem eqv_symm_apply_cls (n : ℕ) :
    (polySeriesEquiv p n).symm
        (Ideal.Quotient.mk (Ideal.span {gSeries p n}) (1 + PowerSeries.X))
      = Ideal.Quotient.mk (Ideal.span {gPoly p n}) (1 + Polynomial.X) := by
  rw [← coe_one_add_X, ← polySeriesEquiv_mk p n (1 + Polynomial.X)]
  exact (polySeriesEquiv p n).symm_apply_apply _

theorem Phi_one_add_X (n : ℕ) : Phi p n (1 + PowerSeries.X) = gammaN p n := by
  rw [Phi, RingHom.comp_apply, RingHom.comp_apply]
  show (phi p n) ((polySeriesEquiv p n).symm
    (Ideal.Quotient.mk (Ideal.span {gSeries p n}) (1 + PowerSeries.X))) = gammaN p n
  rw [eqv_symm_apply_cls]
  exact phi_clsX p n

theorem phi_injective (n : ℕ) : Function.Injective (phi p n) := by
  intro a b hab
  have h : (psi p n).comp (phi p n) = AlgHom.id ℤ_[p] (Qpoly p n) := psi_phi p n
  have h1 : ((psi p n).comp (phi p n)) a = ((psi p n).comp (phi p n)) b :=
    congrArg (fun y => (psi p n) y) hab
  rw [h] at h1
  simpa using h1

theorem comp_ringHom_injective (n : ℕ) :
    Function.Injective
      ((phi p n).toRingHom.comp (polySeriesEquiv p n).symm.toRingHom) :=
  (phi_injective p n).comp (AlgEquiv.injective (polySeriesEquiv p n).symm)

theorem Phi_ker (n : ℕ) :
    RingHom.ker (Phi p n) = Ideal.span {gSeries p n} := by
  rw [Phi, RingHom.ker_comp_of_injective _ (comp_ringHom_injective p n),
    Ideal.mk_ker]

end Final

/-! ## §5  The tower of group rings, its inverse limit, and the cone

The level-`n` maps `Φ_n` are compatible with the projections of the tower, hence they
assemble into a ring homomorphism `ℤ_p⟦T⟧ → lim_n ℤ_p[Γ_n]`.  Theorem E of the thesis is
the statement that this map is an isomorphism; the two halves are the finite-level kernel
theorem and the lifting of compatible families, both stated at the end of this section. -/

/-! ### The tower of group rings and its projections -/

noncomputable def castZMod (n m : ℕ) (hmn : m ≤ n) : ZMod (p ^ n) →+* ZMod (p ^ m) :=
  ZMod.castHom (pow_dvd_pow p hmn) (ZMod (p ^ m))

noncomputable def projAlg (n m : ℕ) (hmn : m ≤ n) :
    MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n))) →ₐ[ℤ_[p]]
      MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ m))) :=
  (MonoidAlgebra.lift ℤ_[p] _ _)
    ((MonoidAlgebra.of ℤ_[p] _).comp
      ((AddMonoidHom.toMultiplicative) (castZMod (p := p) n m hmn).toAddMonoidHom))

theorem projAlg_gammaN (n m : ℕ) (hmn : m ≤ n) :
    projAlg p n m hmn (gammaN p n) = gammaN p m := by
  rw [projAlg, MonoidAlgebra.lift_of, MonoidHom.comp_apply, gammaN]
  congr 1
  have h1 : (ZMod.cast (1 : ZMod (p ^ n)) : ZMod (p ^ m)) = 1 :=
    ZMod.cast_one (pow_dvd_pow p hmn)
  show Multiplicative.ofAdd (ZMod.cast (1 : ZMod (p ^ n)) : ZMod (p ^ m))
      = Multiplicative.ofAdd 1
  rw [h1]

/-! ### Divisibility of the level polynomials -/

theorem gPoly_dvd {n m : ℕ} (hmn : m ≤ n) : gPoly p m ∣ gPoly p n := by
  obtain ⟨k, rfl⟩ : ∃ k, n = m + k := ⟨n - m, by omega⟩
  have h : (1 + Polynomial.X : Polynomial ℤ_[p]) ^ (p ^ (m + k))
      = ((1 + Polynomial.X) ^ (p ^ m)) ^ (p ^ k) := by
    rw [pow_add, pow_mul]
  rw [gPoly, gPoly, h]
  have := sub_dvd_pow_sub_pow ((1 + Polynomial.X : Polynomial ℤ_[p]) ^ (p ^ m)) 1 (p ^ k)
  simpa using this

theorem gSeries_dvd {n m : ℕ} (hmn : m ≤ n) : gSeries p m ∣ gSeries p n := by
  obtain ⟨k, rfl⟩ : ∃ k, n = m + k := ⟨n - m, by omega⟩
  have h : (1 + PowerSeries.X : PowerSeries ℤ_[p]) ^ (p ^ (m + k))
      = ((1 + PowerSeries.X) ^ (p ^ m)) ^ (p ^ k) := by
    rw [pow_add, pow_mul]
  rw [gSeries, gSeries, h]
  have := sub_dvd_pow_sub_pow ((1 + PowerSeries.X : PowerSeries ℤ_[p]) ^ (p ^ m)) 1 (p ^ k)
  simpa using this

/-! ### Quotient maps induced by the tower -/

theorem mk_gPoly_eq_zero (n : ℕ) :
    Ideal.Quotient.mk (Ideal.span {gPoly p n}) (gPoly p n) = 0 := by
  rw [Ideal.Quotient.eq_zero_iff_mem]
  exact Ideal.subset_span (Set.mem_singleton _)

theorem mk_gSeries_eq_zero (n : ℕ) :
    Ideal.Quotient.mk (Ideal.span {gSeries p n}) (gSeries p n) = 0 := by
  rw [Ideal.Quotient.eq_zero_iff_mem]
  exact Ideal.subset_span (Set.mem_singleton _)

noncomputable def quotPoly (n m : ℕ) (hmn : m ≤ n) :
    Qpoly p n →ₐ[ℤ_[p]] Qpoly p m :=
  Ideal.Quotient.liftₐ (Ideal.span {gPoly p n}) (Ideal.Quotient.mkₐ ℤ_[p] _)
    (by
      intro a ha
      rw [Ideal.mem_span_singleton] at ha
      obtain ⟨b, hb⟩ := ha
      rw [hb, map_mul, Ideal.Quotient.mkₐ_eq_mk]
      have hz : Ideal.Quotient.mk (Ideal.span {gPoly p m}) (gPoly p n) = 0 := by
        rw [Ideal.Quotient.eq_zero_iff_mem, Ideal.mem_span_singleton]
        exact gPoly_dvd (p := p) hmn
      rw [hz, zero_mul])

@[simp] theorem quotPoly_mk (n m : ℕ) (hmn : m ≤ n) (a : Polynomial ℤ_[p]) :
    quotPoly p n m hmn (Ideal.Quotient.mk (Ideal.span {gPoly p n}) a)
      = Ideal.Quotient.mk (Ideal.span {gPoly p m}) a := rfl

noncomputable def quotSeries (n m : ℕ) (hmn : m ≤ n) :
    Qseries p n →ₐ[ℤ_[p]] Qseries p m :=
  Ideal.Quotient.liftₐ (Ideal.span {gSeries p n}) (Ideal.Quotient.mkₐ ℤ_[p] _)
    (by
      intro a ha
      rw [Ideal.mem_span_singleton] at ha
      obtain ⟨b, hb⟩ := ha
      rw [hb, map_mul, Ideal.Quotient.mkₐ_eq_mk]
      have hz : Ideal.Quotient.mk (Ideal.span {gSeries p m}) (gSeries p n) = 0 := by
        rw [Ideal.Quotient.eq_zero_iff_mem, Ideal.mem_span_singleton]
        exact gSeries_dvd (p := p) hmn
      rw [hz, zero_mul])

@[simp] theorem quotSeries_mk (n m : ℕ) (hmn : m ≤ n) (a : PowerSeries ℤ_[p]) :
    quotSeries p n m hmn (Ideal.Quotient.mk (Ideal.span {gSeries p n}) a)
      = Ideal.Quotient.mk (Ideal.span {gSeries p m}) a := rfl

/-! ### The class of `X` in the two quotients -/

@[simp] theorem mk_X_eq (n : ℕ) :
    (Ideal.Quotient.mk (Ideal.span {gPoly p n}) Polynomial.X) = clsX p n - 1 := by
  rw [clsX]
  have hpol : (Polynomial.X : Polynomial ℤ_[p]) = (1 + Polynomial.X) - 1 := by ring
  rw [hpol]
  simp

@[simp] theorem eqv_symm_mkS_X (n : ℕ) :
    (polySeriesEquiv p n).symm (Ideal.Quotient.mk (Ideal.span {gSeries p n}) PowerSeries.X)
      = Ideal.Quotient.mk (Ideal.span {gPoly p n}) Polynomial.X := by
  rw [AlgEquiv.symm_apply_eq, ← Polynomial.coe_X]
  exact (polySeriesEquiv_mk p n Polynomial.X).symm

@[simp] theorem eqv_mkPoly_X (n : ℕ) :
    (polySeriesEquiv p n) (Ideal.Quotient.mk (Ideal.span {gPoly p n}) Polynomial.X)
      = Ideal.Quotient.mk (Ideal.span {gSeries p n}) PowerSeries.X := by
  rw [← Polynomial.coe_X]
  exact polySeriesEquiv_mk p n Polynomial.X

@[simp] theorem eqv_toAlgHom_mkPoly_X (n : ℕ) :
    (polySeriesEquiv p n).toAlgHom
        ((Ideal.Quotient.mk (Ideal.span {gPoly p n})) Polynomial.X)
      = (Ideal.Quotient.mk (Ideal.span {gSeries p n})) PowerSeries.X :=
  eqv_mkPoly_X p n

@[simp] theorem eqv_symm_toAlgHom_mkS_X (n : ℕ) :
    (polySeriesEquiv p n).symm.toAlgHom
        ((Ideal.Quotient.mk (Ideal.span {gSeries p n})) PowerSeries.X)
      = (Ideal.Quotient.mk (Ideal.span {gPoly p n})) Polynomial.X :=
  eqv_symm_mkS_X p n

/-! ### Extensionality for algebra maps out of `Qseries` -/

theorem algHom_ext_series {n m : ℕ} {f g : Qseries p n →ₐ[ℤ_[p]] Qseries p m}
    (h : f (Ideal.Quotient.mk (Ideal.span {gSeries p n}) PowerSeries.X)
        = g (Ideal.Quotient.mk (Ideal.span {gSeries p n}) PowerSeries.X)) : f = g := by
  have hX : ((f.comp (polySeriesEquiv p n).toAlgHom).comp
        (Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n}))) Polynomial.X
      = ((g.comp (polySeriesEquiv p n).toAlgHom).comp
        (Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n}))) Polynomial.X := by
    simpa only [AlgHom.comp_apply, Ideal.Quotient.mkₐ_eq_mk, eqv_toAlgHom_mkPoly_X] using h
  have h' := Polynomial.algHom_ext hX
  have h2 : f.comp (polySeriesEquiv p n).toAlgHom = g.comp (polySeriesEquiv p n).toAlgHom := by
    refine AlgHom.ext fun y => ?_
    obtain ⟨a, rfl⟩ := Ideal.Quotient.mk_surjective y
    exact congr($h' a)
  refine AlgHom.ext fun x => ?_
  have h3 := congr($h2 ((polySeriesEquiv p n).symm x))
  simpa using h3

/-! ### The cone: `projAlg` is compatible with `Φ` -/

theorem projAlg_phi (n m : ℕ) (hmn : m ≤ n) :
    (projAlg p n m hmn).comp (phi p n)
      = (phi p m).comp (quotPoly p n m hmn) := by
  have hone : (projAlg p n m hmn) (1 : MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n))))
      = 1 := map_one _
  have hone' : (phi p m) (1 : Qpoly p m) = 1 := map_one _
  have hone'' : (phi p n) (1 : Qpoly p n) = 1 := map_one _
  have hL : ((projAlg p n m hmn).comp (phi p n))
        ((Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n})) Polynomial.X) = gammaN p m - 1 := by
    rw [AlgHom.comp_apply, Ideal.Quotient.mkₐ_eq_mk, mk_X_eq, map_sub, phi_clsX, map_sub,
      hone'', hone, projAlg_gammaN]
  have hR : ((phi p m).comp (quotPoly p n m hmn))
        ((Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n})) Polynomial.X) = gammaN p m - 1 := by
    rw [AlgHom.comp_apply, Ideal.Quotient.mkₐ_eq_mk, quotPoly_mk, mk_X_eq, map_sub, phi_clsX,
      hone']
  have hX : ((projAlg p n m hmn).comp (phi p n))
        ((Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n})) Polynomial.X)
      = ((phi p m).comp (quotPoly p n m hmn))
        ((Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n})) Polynomial.X) := by
    rw [hL, hR]
  have h : ((projAlg p n m hmn).comp (phi p n)).comp
        (Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n}))
      = ((phi p m).comp (quotPoly p n m hmn)).comp
        (Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gPoly p n})) :=
    Polynomial.algHom_ext hX
  refine AlgHom.ext fun y => ?_
  obtain ⟨a, rfl⟩ := Ideal.Quotient.mk_surjective y
  exact congr($h a)

theorem eqv_quotPoly (n m : ℕ) (hmn : m ≤ n) (x : Qseries p n) :
    (polySeriesEquiv p m) (quotPoly p n m hmn ((polySeriesEquiv p n).symm x))
      = quotSeries p n m hmn x := by
  have key : (polySeriesEquiv p m).toAlgHom.comp
        ((quotPoly p n m hmn).comp (polySeriesEquiv p n).symm.toAlgHom)
      = quotSeries p n m hmn := by
    apply algHom_ext_series
    simp only [AlgHom.comp_apply, eqv_symm_toAlgHom_mkS_X, quotPoly_mk, eqv_toAlgHom_mkPoly_X,
      quotSeries_mk]
  exact congr($key x)

theorem projAlg_Phi (n m : ℕ) (hmn : m ≤ n) (g : ℤ_[p]⟦X⟧) :
    projAlg p n m hmn (Phi p n g) = Phi p m g := by
  have h1 : Phi p n g = phi p n ((polySeriesEquiv p n).symm
      (Ideal.Quotient.mk (Ideal.span {gSeries p n}) g)) := rfl
  have h2 : Phi p m g = phi p m ((polySeriesEquiv p m).symm
      (Ideal.Quotient.mk (Ideal.span {gSeries p m}) g)) := rfl
  have hx : projAlg p n m hmn (phi p n ((polySeriesEquiv p n).symm
      (Ideal.Quotient.mk (Ideal.span {gSeries p n}) g)))
      = phi p m (quotPoly p n m hmn ((polySeriesEquiv p n).symm
        (Ideal.Quotient.mk (Ideal.span {gSeries p n}) g))) :=
    congr($(projAlg_phi p n m hmn) ((polySeriesEquiv p n).symm
      (Ideal.Quotient.mk (Ideal.span {gSeries p n}) g)))
  have hstep : quotPoly p n m hmn ((polySeriesEquiv p n).symm
        (Ideal.Quotient.mk (Ideal.span {gSeries p n}) g))
      = (polySeriesEquiv p m).symm (Ideal.Quotient.mk (Ideal.span {gSeries p m}) g) := by
    have hy := eqv_quotPoly p n m hmn (Ideal.Quotient.mk (Ideal.span {gSeries p n}) g)
    rw [quotSeries_mk] at hy
    rw [AlgEquiv.eq_symm_apply]
    exact hy
  rw [h1, h2, hx, hstep]

/-! ### The inverse limit of the tower and the canonical map -/

/-- The inverse limit `lim_n ℤ_p[Γ_n]` of the tower of group rings, as the subring of the
product consisting of the compatible families.  This is `Λ(ℤ_p)` of (3.6) before
Theorem E identifies it with `ℤ_p⟦T⟧`. -/
def IwasawaLimit :
    Subring (∀ n : ℕ, MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n)))) where
  carrier := {f | ∀ ⦃m n : ℕ⦄ (hmn : m ≤ n), projAlg p n m hmn (f n) = f m}
  mul_mem' := by
    intro f g hf hg m n hmn
    simp only [Pi.mul_apply, map_mul, hf hmn, hg hmn]
  one_mem' := by
    intro m n hmn
    simp only [Pi.one_apply, map_one]
  add_mem' := by
    intro f g hf hg m n hmn
    simp only [Pi.add_apply, map_add, hf hmn, hg hmn]
  zero_mem' := by
    intro m n hmn
    simp only [Pi.zero_apply, map_zero]
  neg_mem' := by
    intro f hf m n hmn
    simp only [Pi.neg_apply, map_neg, hf hmn]

/-- The canonical ring homomorphism `ℤ_p⟦T⟧ → lim_n ℤ_p[Γ_n]`, `T ↦ (γ_n - 1)_n`.
Theorem E says it is a ring isomorphism. -/
noncomputable def limitMap : ℤ_[p]⟦X⟧ →+* IwasawaLimit p :=
  RingHom.codRestrict (RingHom.pi fun n => Phi p n) (IwasawaLimit p)
    (by
      intro g m n hmn
      simp only [RingHom.pi_apply]
      exact projAlg_Phi p n m hmn g)

@[simp]
theorem limitMap_apply (g : ℤ_[p]⟦X⟧) (n : ℕ) :
    ((limitMap p g : IwasawaLimit p) : ∀ n : ℕ,
      MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n)))) n = Phi p n g := rfl

/-- Theorem E, reduced to its two halves: the canonical map `ℤ_p⟦T⟧ → lim_n ℤ_p[Γ_n]` is
injective (the finite-level kernel theorem: `⋂_n ((1+T)^{p^n}-1) = 0`) and surjective
(every compatible family of level-`n` Stickelberger-type elements comes from one series). -/
theorem theoremE_iff :
    Function.Bijective (limitMap p) ↔
      (Function.Injective (limitMap p) ∧ Function.Surjective (limitMap p)) :=
  Iff.rfl



section Scaffolding

/-- *Theorem E* (§3.1, [47, Theorem 7.1]), level-`n` form.

For each `n` there is a surjective `ℤ_p`-algebra homomorphism
`ℤ_p⟦T⟧ ↠ ℤ_p[Γ_n]` sending `1+T ↦ γ_n`, with kernel the ideal `((1+T)^{p^n}-1)`.

This is the composite `ℤ_p⟦T⟧ → ℤ_p⟦T⟧/((1+T)^{p^n}-1) ≅ ℤ_p[T]/((1+T)^{p^n}-1) ≅ ℤ_p[Γ_n]`;
the middle step is Weierstrass division by the monic polynomial `(1+T)^{p^n}-1`.
The proof uses Weierstrass division for the distinguished polynomial
`(1+T)^(p^n)-1`, explicit mutually inverse group-ring maps, and shows both the
surjectivity and the full `ℤ_p`-algebra structure below. -/
theorem exists_reduction (p : ℕ) [Fact p.Prime] (n : ℕ) :
    ∃ Φ : ℤ_[p]⟦X⟧ →+* MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n))),
      Φ (1 + X) = gammaN p n ∧
      RingHom.ker Φ = Ideal.span {((1 + X) ^ (p ^ n) - 1 : ℤ_[p]⟦X⟧)} :=
  ⟨Phi p n, Phi_one_add_X p n, Phi_ker p n⟩

/-- The finite-level quotient map with its actual `ℤ_p`-algebra structure displayed. -/
noncomputable def PhiAlgHom (n : ℕ) :
    PowerSeries ℤ_[p] →ₐ[ℤ_[p]] MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n))) :=
  ((phi p n).comp (polySeriesEquiv p n).symm.toAlgHom).comp
    (Ideal.Quotient.mkₐ ℤ_[p] (Ideal.span {gSeries p n}))

theorem PhiAlgHom_toRingHom (n : ℕ) : (PhiAlgHom p n).toRingHom = Phi p n := rfl

/-- The stronger form of the source's finite-level assertion: an algebra surjection with
an explicitly computed kernel, rather than merely a ring homomorphism of that form. -/
theorem exists_reduction_algHom_surjective (p : ℕ) [Fact p.Prime] (n : ℕ) :
    ∃ Φ : PowerSeries ℤ_[p] →ₐ[ℤ_[p]] MonoidAlgebra ℤ_[p] (Multiplicative (ZMod (p ^ n))),
      Function.Surjective Φ ∧
      Φ (1 + PowerSeries.X) = gammaN p n ∧
      RingHom.ker Φ.toRingHom = Ideal.span {((1 + PowerSeries.X) ^ (p ^ n) - 1 : ℤ_[p]⟦X⟧)} := by
  refine ⟨PhiAlgHom p n, ?_, Phi_one_add_X p n, Phi_ker p n⟩
  intro y
  obtain ⟨c, hc⟩ := Ideal.Quotient.mk_surjective ((polySeriesEquiv p n) (psi p n y))
  refine ⟨c, ?_⟩
  change phi p n ((polySeriesEquiv p n).symm ((Ideal.Quotient.mk (Ideal.span {gSeries p n})) c)) = y
  rw [hc, AlgEquiv.symm_apply_apply]
  exact congr($(phi_psi p n) y)


end Scaffolding

end Bhattacharya

section Audit
#print axioms Bhattacharya.exists_reduction
#print axioms Bhattacharya.projAlg_Phi
#print axioms Bhattacharya.limitMap
#print axioms Bhattacharya.h_mul_gamma
#print axioms Bhattacharya.f_unique
#print axioms Bhattacharya.char_second_kind_even
#print axioms Bhattacharya.teichmuller_neg_one
#print axioms Bhattacharya.sum_char_eq_zero
#print axioms Bhattacharya.charIdem_mul_of
#print axioms Bhattacharya.charIdem_idem
#print axioms Bhattacharya.charIdem_mul_eq_zero
#print axioms Bhattacharya.gammaN_pow
#print axioms Bhattacharya.exists_reduction
end Audit
