/-
Stickelberger system and its exact level correction (Bhattacharya MSc thesis, Prop. 3.6).
Own module of swarm member m3; builds on `Thesis.Stickelberger`.
-/
import Thesis.Stickelberger

open scoped BigOperators

namespace Bhattacharya

namespace M3

set_option maxHeartbeats 1000000

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

/-- The trace ("norm") element `N_n = ∑_b σ_b⁻¹` of `ℚ[(ZMod p^n)ˣ]`. -/
noncomputable def normElem (n : ℕ) : MonoidAlgebra ℚ (ZMod (p ^ n))ˣ :=
  ∑ b : (ZMod (p ^ n))ˣ, MonoidAlgebra.single b⁻¹ (1 : ℚ)

/-- The finite-level Stickelberger element `θ_n = ∑_a (a/p^n)·σ_a⁻¹`. -/
noncomputable def theta (n : ℕ) : MonoidAlgebra ℚ (ZMod (p ^ n))ˣ :=
  ∑ a : (ZMod (p ^ n))ˣ,
    MonoidAlgebra.single a⁻¹ (((a : ZMod (p ^ n)).val : ℚ) / ((p ^ n : ℕ) : ℚ))

/-- The projection/trace pushforward along `(ZMod p^M)ˣ →* (ZMod p^n)ˣ`, `p^n ∣ p^M`. -/
noncomputable def push {n M : ℕ} (h : p ^ n ∣ p ^ M) :
    MonoidAlgebra ℚ (ZMod (p ^ M))ˣ →ₐ[ℚ] MonoidAlgebra ℚ (ZMod (p ^ n))ˣ :=
  MonoidAlgebra.mapDomainAlgHom ℚ ℚ (ZMod.unitsMap h)

lemma unitsMap_trans_apply {n k M : ℕ} (h1 : n ∣ k) (h2 : k ∣ M) (a : (ZMod M)ˣ) :
    ZMod.unitsMap h1 (ZMod.unitsMap h2 a) = ZMod.unitsMap (h1.trans h2) a := by
  have h := congrFun (congrArg DFunLike.coe (ZMod.unitsMap_comp h1 h2)) a
  rw [show h1.trans h2 = dvd_trans h1 h2 from Subsingleton.elim _ _]
  exact h

lemma push_single {n M : ℕ} (h : p ^ n ∣ p ^ M) (a : (ZMod (p ^ M))ˣ) (r : ℚ) :
    push p h (MonoidAlgebra.single a r) = MonoidAlgebra.single (ZMod.unitsMap h a) r := by
  simp [push]

lemma push_comp {n k M : ℕ} (h1 : p ^ n ∣ p ^ k) (h2 : p ^ k ∣ p ^ M) :
    (push p h1).comp (push p h2) = push p (h1.trans h2) := by
  refine AlgHom.ext fun x => ?_
  simp only [AlgHom.comp_apply, push, MonoidAlgebra.mapDomainAlgHom_apply]
  have hfun : (⇑(ZMod.unitsMap (h1.trans h2)) : (ZMod (p ^ M))ˣ → (ZMod (p ^ n))ˣ)
      = ⇑(ZMod.unitsMap h1) ∘ ⇑(ZMod.unitsMap h2) := by
    funext a; exact (unitsMap_trans_apply h1 h2 a).symm
  rw [hfun]
  ext
  simp [Finsupp.mapDomain_comp]

lemma push_comp_apply {n k M : ℕ} (h1 : p ^ n ∣ p ^ k) (h2 : p ^ k ∣ p ^ M)
    (x : MonoidAlgebra ℚ (ZMod (p ^ M))ˣ) :
    push p h1 (push p h2 x) = push p (h1.trans h2) x := by
  rw [← AlgHom.comp_apply, push_comp]

lemma push_self (n : ℕ) (x : MonoidAlgebra ℚ (ZMod (p ^ n))ˣ) :
    push p (dvd_refl (p ^ n)) x = x := by
  show MonoidAlgebra.mapDomainAlgHom ℚ ℚ (ZMod.unitsMap (dvd_refl (p ^ n))) x = x
  rw [ZMod.unitsMap_self, MonoidAlgebra.mapDomainAlgHom_id, AlgHom.id_apply]

lemma push_theta {n M : ℕ} (h : p ^ n ∣ p ^ M) :
    push p h (theta p M) = ∑ a : (ZMod (p ^ M))ˣ,
      MonoidAlgebra.single (ZMod.unitsMap h a)⁻¹
        (((a : ZMod (p ^ M)).val : ℚ) / ((p ^ M : ℕ) : ℚ)) := by
  simp only [theta, map_sum]
  refine Finset.sum_congr rfl fun a _ => ?_
  rw [push_single, map_inv]

/-- A scalar multiple of the norm element, in coordinates. -/
lemma smul_normElem (n : ℕ) (c : ℚ) :
    c • normElem p n = ∑ b : (ZMod (p ^ n))ˣ, MonoidAlgebra.single b⁻¹ c := by
  rw [normElem, Finset.smul_sum]
  refine Finset.sum_congr rfl fun b _ => ?_
  rw [MonoidAlgebra.smul_single']
  simp

/-- **Equation (3.17), one level.** The projection of `θ_{n+1}` differs from `θ_n` by
the norm element times `(p-1)/2` — the nonzero level correction of Proposition 3.6. -/
theorem push_theta_succ (n : ℕ) (hn : 1 ≤ n) :
    push p (pow_dvd_pow_succ p n) (theta p (n + 1)) =
      theta p n + (((p : ℚ) - 1) / 2) • normElem p n := by
  have hmain := stickelberger_level_compatibility p n hn
  simp only [levelProj] at hmain
  have hα : ((p : ℚ) - 1) / 2 = (((p - 1 : ℕ)) : ℚ) / 2 := by
    rw [Nat.cast_sub (Fact.out : p.Prime).one_lt.le]; norm_num
  rw [push_theta, hmain, smul_normElem, hα, theta]

/-- The trace of the norm element: `π_*(N_{n+1}) = p·N_n`. -/
theorem push_normElem_succ (n : ℕ) (hn : 1 ≤ n) :
    push p (pow_dvd_pow_succ p n) (normElem p (n + 1)) = (p : ℚ) • normElem p n := by
  have hmain := levelProj_sum_units p n hn
  simp only [levelProj] at hmain
  simp only [normElem, map_sum, push_single, map_inv]
  exact hmain

/-- The trace of the norm element across `M - n` levels: `π_*(N_M) = p^(M-n)·N_n`. -/
theorem push_normElem_le (n : ℕ) (hn : 1 ≤ n) : ∀ (M : ℕ), n ≤ M → ∀ (h : p ^ n ∣ p ^ M),
    push p h (normElem p M) = (p : ℚ) ^ (M - n) • normElem p n := by
  intro M hM
  induction M, hM using Nat.le_induction with
  | base =>
      intro h
      rw [show h = dvd_refl (p ^ n) from Subsingleton.elim _ _, push_self, Nat.sub_self,
        pow_zero, one_smul]
  | succ M hM ih =>
      intro h
      have h2 : p ^ M ∣ p ^ (M + 1) := pow_dvd_pow_succ p M
      have h1 : p ^ n ∣ p ^ M := pow_dvd_pow p hM
      rw [show h = h1.trans h2 from Subsingleton.elim _ _, ← push_comp_apply p h1 h2,
        push_normElem_succ p M (by omega), map_smul,
        ih h1, smul_smul, ← pow_succ', Nat.succ_sub hM]

/-- **The level correction for arbitrary level gaps.**  For `n ≤ M` the projection of the
level-`M` Stickelberger element to level `n` equals `θ_n` plus
`((p-1)/2)·(1 + p + ⋯ + p^(M-n-1))` times the norm element `N_n`. -/
theorem push_theta_le (n : ℕ) (hn : 1 ≤ n) : ∀ (M : ℕ), n ≤ M → ∀ (h : p ^ n ∣ p ^ M),
    push p h (theta p M) =
      theta p n
        + ((((p : ℚ) - 1) / 2) * ∑ k ∈ Finset.range (M - n), (p : ℚ) ^ k) • normElem p n := by
  intro M hM
  induction M, hM using Nat.le_induction with
  | base =>
      intro h
      rw [show h = dvd_refl (p ^ n) from Subsingleton.elim _ _, push_self, Nat.sub_self]
      simp
  | succ M hM ih =>
      intro h
      have h2 : p ^ M ∣ p ^ (M + 1) := pow_dvd_pow_succ p M
      have h1 : p ^ n ∣ p ^ M := pow_dvd_pow p hM
      rw [show h = h1.trans h2 from Subsingleton.elim _ _, ← push_comp_apply p h1 h2,
        push_theta_succ p M (by omega), map_add, map_smul,
        push_normElem_le p n hn M hM h1, ih h1, smul_smul, Nat.succ_sub hM,
        Finset.sum_range_succ, mul_add, add_smul]
      abel

/-! ## §3 The level correction is nonzero: `θ_n` is not an element of the inverse system -/

/-- The augmentation `ℚ[G] →+* ℚ`, `σ_g ↦ 1`. -/
noncomputable def aug {G : Type*} [Monoid G] : MonoidAlgebra ℚ G →+* ℚ :=
  MonoidAlgebra.liftNCRingHom (RingHom.id ℚ) (1 : G →* ℚ) (fun _ _ => Commute.all _ _)

lemma aug_normElem (n : ℕ) : aug (normElem p n) = (Fintype.card (ZMod (p ^ n))ˣ : ℚ) := by
  simp only [normElem, map_sum, nsmul_eq_mul, mul_one]
  congr 1
  simp [aug, MonoidAlgebra.liftNCRingHom]

lemma normElem_ne_zero (n : ℕ) : normElem p n ≠ 0 := by
  intro h
  have h1 := aug_normElem p n
  rw [h, map_zero] at h1
  haveI : Nonempty (ZMod (p ^ n))ˣ := ⟨1⟩
  have h2 : (0:ℚ) < (Fintype.card (ZMod (p ^ n))ˣ : ℚ) := by
    have := Fintype.card_pos (α := (ZMod (p ^ n))ˣ)
    exact_mod_cast this
  linarith

/-- The correction coefficient of level gap one, `(p-1)/2`, is positive. -/
lemma alpha_pos (hp : 1 < p) : (0 : ℚ) < ((p : ℚ) - 1) / 2 := by
  have h1 : (1 : ℚ) < p := by exact_mod_cast hp
  linarith

lemma alpha_ne_zero (hp : 1 < p) : ((p : ℚ) - 1) / 2 ≠ 0 :=
  ne_of_gt (alpha_pos p hp)

/-- **Naive compatibility fails.**  For every level `n ≥ 1` the projection of `θ_{n+1}` is
*not* `θ_n`; the defect is the norm element times `(p-1)/2 ≠ 0`. -/
theorem theta_not_compatible (n : ℕ) (hn : 1 ≤ n) :
    push p (pow_dvd_pow_succ p n) (theta p (n + 1)) ≠ theta p n := by
  intro h
  have h2 := push_theta_succ p n hn
  rw [h] at h2
  have h3 : (((p : ℚ) - 1) / 2) • normElem p n = 0 := by
    have h4 : theta p n + (((p : ℚ) - 1) / 2) • normElem p n = theta p n + 0 := by
      rw [← h2, add_zero]
    exact add_left_cancel h4
  rcases (smul_eq_zero.mp h3) with h5 | h5
  · exact alpha_ne_zero p (Fact.out : p.Prime).one_lt h5
  · exact normElem_ne_zero p n h5

/-- The correction coefficients of level gap `d ≥ 1` are nonzero. -/
lemma alpha_mul_sum_ne_zero (hp : 1 < p) (d : ℕ) (hd : 1 ≤ d) :
    (((p : ℚ) - 1) / 2) * ∑ k ∈ Finset.range d, (p : ℚ) ^ k ≠ 0 := by
  have hpos : 0 < ∑ k ∈ Finset.range d, (p : ℚ) ^ k := by
    refine Finset.sum_pos' (fun k _ => ?_) ⟨0, Finset.mem_range.mpr (by omega), by simp⟩
    positivity
  have h1 := alpha_pos p hp
  positivity

/-- **Incompatibility at every level gap.**  For `n < M` the projection of `θ_M` to level
`n` is never `θ_n`: the finite-level Stickelberger elements do not form an element of the
inverse system `lim_n ℚ[(ZMod p^n)ˣ]`. -/
theorem theta_not_compatible_gap {n M : ℕ} (hn : 1 ≤ n) (hM : n < M) :
    push p (pow_dvd_pow p hM.le) (theta p M) ≠ theta p n := by
  intro h
  have h2 := push_theta_le p n hn M hM.le (pow_dvd_pow p hM.le)
  rw [h] at h2
  have h3 : ((((p : ℚ) - 1) / 2) * ∑ k ∈ Finset.range (M - n), (p : ℚ) ^ k)
      • normElem p n = 0 := by
    have h4 : theta p n + ((((p : ℚ) - 1) / 2) * ∑ k ∈ Finset.range (M - n), (p : ℚ) ^ k)
        • normElem p n = theta p n + 0 := by
      rw [← h2, add_zero]
    exact add_left_cancel h4
  rcases (smul_eq_zero.mp h3) with h5 | h5
  · exact alpha_mul_sum_ne_zero p (Fact.out : p.Prime).one_lt (M - n) (by omega) h5
  · exact normElem_ne_zero p n h5

/-! ## §4 The exact repair: the corrected system is compatible iff the scalar
satisfies `p·c(n+1) - c n = -(p-1)/2`, whose solutions are `D/p^(n-1) - 1/2`. -/

/-- The corrected Stickelberger element `θ_n + c n • N_n`. -/
noncomputable def corrected (c : ℕ → ℚ) (n : ℕ) : MonoidAlgebra ℚ (ZMod (p ^ n))ˣ :=
  theta p n + c n • normElem p n

/-- `Compatible c` says that the corrected family `θ_n + c n • N_n` is an element of the
inverse limit of the `ℚ[(ZMod p^n)ˣ]` (concrete form: equal under every one-step
projection). -/
def Compatible (c : ℕ → ℚ) : Prop :=
  ∀ n : ℕ, 1 ≤ n → push p (pow_dvd_pow_succ p n) (corrected p c (n + 1)) = corrected p c n

/-- **The exact compatibility recursion.**  A scalar correction makes the Stickelberger
system compatible exactly when `p·c(n+1) - c n = -(p-1)/2` for all `n ≥ 1`. -/
theorem compatible_iff (c : ℕ → ℚ) :
    Compatible p c ↔ ∀ n : ℕ, 1 ≤ n → (p : ℚ) * c (n + 1) - c n = -(((p : ℚ) - 1) / 2) := by
  constructor
  · intro h n hn
    have h2 := h n hn
    simp only [corrected, map_add, map_smul, push_theta_succ p n hn,
      push_normElem_succ p n hn] at h2
    rw [smul_smul] at h2
    rw [add_assoc, ← add_smul] at h2
    have h4 : ((((p : ℚ) - 1) / 2) + c (n + 1) * p) • normElem p n
        = (c n) • normElem p n := add_left_cancel h2
    have h3 : ((((p : ℚ) - 1) / 2) + c (n + 1) * p - c n) • normElem p n = 0 := by
      rw [sub_smul, h4, sub_self]
    rcases (smul_eq_zero.mp h3) with h5 | h5
    · linarith
    · exact absurd h5 (normElem_ne_zero p n)
  · intro h n hn
    have hs : ((p : ℚ) - 1) / 2 + (p : ℚ) * c (n + 1) = c n := by
      have hh := h n hn
      linarith
    simp only [corrected, map_add, map_smul, push_theta_succ p n hn,
      push_normElem_succ p n hn]
    rw [smul_smul]
    rw [show c (n + 1) * (p : ℚ) = (p : ℚ) * c (n + 1) from mul_comm _ _]
    rw [add_assoc, ← add_smul, hs]

end M3

end Bhattacharya

section Audit

#print axioms Bhattacharya.M3.push_theta_succ
#print axioms Bhattacharya.M3.push_normElem_succ
#print axioms Bhattacharya.M3.push_normElem_le
#print axioms Bhattacharya.M3.push_theta_le
#print axioms Bhattacharya.M3.normElem_ne_zero
#print axioms Bhattacharya.M3.theta_not_compatible
#print axioms Bhattacharya.M3.theta_not_compatible_gap
#print axioms Bhattacharya.M3.compatible_iff

end Audit
