Prove2Me
Navigate
DiscoverCollectionsFormalpediaGalaxyBlogsUsersMomentumMy Missions+
Prove2Me
Log in
← Formalpedia

Ramanujan-Petersson curve library, flat edition, file 021 of 70

Definition
RPLib_F2_021

by Nickrobbins95 · Nov 19, 2026 · Mathlib 0df444a (Lean v4.33.1)

algebraic-geometryfinite-fieldsnumber-theory

File 021 of 70 of the flat curve library: declarations re-hosted from the following library modules, in dependency order.

  • S4.Def_RP_CdOne_Lc: S4-PD (3), group layer part 1: locally constant cochains and the index lemma
  • S4.Def_RP_CdOne_Grp: S4-PD (3), group layer part 2: Sylow reduction and ℤ/l coefficients
  • S4.Def_RP_CdOne_Dev: S4-PD (3), group layer part 3: dévissage and H²(P, A) = 0
  • S4.Def_RP_CdOne_Wrap: S4-PD (3), group layer part 4: wrappers for cd_l ≤ 1
  • S4.Def_RP_PerfectCx_Z1Ex: S4-PD (5), E2.1: locally constant 1-cocycles are exact under H² = 0
  • S4.Def_RP_HattoriStallings_Core: Hattori–Stallings traces over R[G] (unit S4-HattoriStallings, part A: core)
  • S4.Def_RP_PerfectCx_CxAlg: S4-PD (5), E3 algebra: products, coinvariants of products, and the right regular module
  • S4.Def_RP_PerfectCx_Alg: S4-PD (5), E2 set-up and E2(a): the cocycle module E = Z¹(Γ; Λ[Gf]) is Λ-free
  • S4.Def_RP_PerfectCx_Tensor: S4-PD (5), E2(c) part 1: the evaluation map (E ⊗ M)_{Gf} → Z¹(Γ; M)
  • S4.Def_RP_PerfectCx_TensorIso: S4-PD (5), E2(c) part 2: (E ⊗ M)_{Gf} ≃ Z¹(Γ; M)
  • S4.Def_RP_PerfectCx_Cx: S4-PD (5), E3: the cone complex and its free Λ[Gf] model
  • S4.Def_RP_PerfectCx_Frob: S4-PD (5), E3: the Frobenius chain map on the cone complex
  • S4.Def_RP_TameInertia_Newton: Tame inertia, part Newton: the Abhyankar trinomial has exactly one small root (S4-PD item (2), T6)
  • S4.Def_RP_CdOne_Emb: S4-PD (3b): the central embedding problem with kernel μ_l
  • S4.Def_RP_CdOne_Field: S4-PD (3), field layer: HypL for Gal(Ω/E₀) from Tsen + Kummer
  • S4.Def_RP_CdOne_Trans: S4-PD (3)(iii), part T: transport of HypL to π₁^geo
  • S4.Def_RP_CdOne_KumMain: S4-PD (3)(iii)(K), main: the Kummer-closure property of K_U / E₀ from the divisibility of Pic(V̄)
  • S4.Def_RP_CdOne_C1: S4-PD (3)(iii), part C: the field E₀ generated by the constants is C1 (Tsen)

Formalization note. One file of the flat edition of a library formalizing Poincaré duality for constant coefficients on an affine curve over a finite field and the Lefschetz trace formula for its Frobenius. The declarations of each library module are re-hosted verbatim (with that module's own namespace / open / variable lines) inside one section ... end per module, in dependency order; declarations no later result uses are left out. They are definitions together with proved lemmas (no sorry; where divisibility facts about Picard groups are used they are explicit hypotheses), so that later files and solution files can import them.

Definition code
import Mathlib
import Definitions.Def_RPLib_F2_020

/-!
# Ramanujan-Petersson curve library (flat edition), file 021 of 70

Declarations of the formalization of Poincaré duality for constant coefficients on an affine curve over a
finite field and of the Lefschetz trace formula for its Frobenius, re-hosted declaration by declaration from
the library modules below. Each module contributes the declarations assigned to this file, copied verbatim with
the module's own `namespace` / `open` / `variable` lines, inside its own `section` ... `end`:

* `S4.Def_RP_CdOne_Lc`: S4-PD (3), group layer part 1: locally constant cochains and the index lemma
* `S4.Def_RP_CdOne_Grp`: S4-PD (3), group layer part 2: Sylow reduction and `ℤ/l` coefficients
* `S4.Def_RP_CdOne_Dev`: S4-PD (3), group layer part 3: dévissage and `H²(P, A) = 0`
* `S4.Def_RP_CdOne_Wrap`: S4-PD (3), group layer part 4: wrappers for `cd_l ≤ 1`
* `S4.Def_RP_PerfectCx_Z1Ex`: S4-PD (5), E2.1: locally constant 1-cocycles are exact under `H² = 0`
* `S4.Def_RP_HattoriStallings_Core`: Hattori–Stallings traces over `R[G]` (unit S4-HattoriStallings, part A: core)
* `S4.Def_RP_PerfectCx_CxAlg`: S4-PD (5), E3 algebra: products, coinvariants of products, and the right regular module
* `S4.Def_RP_PerfectCx_Alg`: S4-PD (5), E2 set-up and E2(a): the cocycle module `E = Z¹(Γ; Λ[Gf])` is `Λ`-free
* `S4.Def_RP_PerfectCx_Tensor`: S4-PD (5), E2(c) part 1: the evaluation map `(E ⊗ M)_{Gf} → Z¹(Γ; M)`
* `S4.Def_RP_PerfectCx_TensorIso`: S4-PD (5), E2(c) part 2: `(E ⊗ M)_{Gf} ≃ Z¹(Γ; M)`
* `S4.Def_RP_PerfectCx_Cx`: S4-PD (5), E3: the cone complex and its free `Λ[Gf]` model
* `S4.Def_RP_PerfectCx_Frob`: S4-PD (5), E3: the Frobenius chain map on the cone complex
* `S4.Def_RP_TameInertia_Newton`: Tame inertia, part Newton: the Abhyankar trinomial has exactly one small root (S4-PD item (2), T6)
* `S4.Def_RP_CdOne_Emb`: S4-PD (3b): the central embedding problem with kernel `μ_l`
* `S4.Def_RP_CdOne_Field`: S4-PD (3), field layer: `HypL` for `Gal(Ω/E₀)` from Tsen + Kummer
* `S4.Def_RP_CdOne_Trans`: S4-PD (3)(iii), part T: transport of `HypL` to `π₁^geo`
* `S4.Def_RP_CdOne_KumMain`: S4-PD (3)(iii)(K), main: the Kummer-closure property of `K_U / E₀` from the divisibility of `Pic(V̄)`
* `S4.Def_RP_CdOne_C1`: S4-PD (3)(iii), part C: the field `E₀` generated by the constants is C1 (Tsen)
-/

set_option autoImplicit false

-- ===== S4.Def_RP_CdOne_Lc =====
section

/-!
# S4-PD (3), group layer part 1: locally constant cochains and the index lemma

For a compact topological group `P` acting on `A` (locally constant action, `LcAct`):
* `lc_dite`, `lc_sum`, `lc_d₁`: closure properties of locally constant cochains;
* `exists_open_inv`: a locally constant function on `P × P` is invariant under right multiplication by an open
  subgroup in each variable (finite level); `exists_openNormal_le`, `actKer`, `isOpen_actKer`;
* `index_lemma`: for an open subgroup `H` whose index is invertible on `A`, a locally constant 2-cocycle whose
  restriction to `H × H` is the coboundary of a locally constant cochain is a locally constant coboundary on `P`
  (normalise to `f(g, n) = 0` for `n ∈ H`, then average over the left cosets `P ⧸ H`).
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson.CdOne

open groupCohomology Filter Topology

section LcBasic

variable {X : Type*} [TopologicalSpace X]

end LcBasic

variable {P : Type*} [Group P] [TopologicalSpace P] [IsTopologicalGroup P]
  {A : Type*} [AddCommGroup A] [DistribMulAction P A]

/-- Finite level: a locally constant function on `P × P` (`P` compact) is invariant under right multiplication
by an open subgroup in each variable. -/
theorem exists_open_inv [CompactSpace P] {X : Type*} {f : P × P → X} (hf : IsLocallyConstant f) :
    ∃ W : Subgroup P, IsOpen (W : Set P) ∧
      ∀ x ∈ W, ∀ g h : P, f (g * x, h) = f (g, h) ∧ f (g, h * x) = f (g, h) := by
  let W : Subgroup P :=
    { carrier := {x | ∀ g h : P, f (g * x, h) = f (g, h) ∧ f (g, h * x) = f (g, h)}
      one_mem' := by intro g h; simp
      mul_mem' := fun {x y} hx hy g h => by
        refine ⟨?_, ?_⟩
        · rw [← mul_assoc, (hy (g * x) h).1, (hx g h).1]
        · rw [← mul_assoc, (hy g (h * x)).2, (hx g h).2]
      inv_mem' := fun {x} hx g h => by
        refine ⟨?_, ?_⟩
        · have := (hx (g * x⁻¹) h).1
          rw [inv_mul_cancel_right] at this
          exact this.symm
        · have := (hx g (h * x⁻¹)).2
          rw [inv_mul_cancel_right] at this
          exact this.symm }
  refine ⟨W, W.isOpen_of_mem_nhds (g := 1) ?_, fun x hx => hx⟩
  have hK := (isCompact_univ : IsCompact (Set.univ : Set (P × P))).eventually_forall_of_forall_eventually
    (x₀ := (1 : P)) (P := fun x y => f (y.1 * x, y.2) = f y ∧ f (y.1, y.2 * x) = f y) ?_
  · filter_upwards [hK] with x hx
    exact fun g h => hx (g, h) (Set.mem_univ _)
  · rintro ⟨g, h⟩ -
    have hf' := (IsLocallyConstant.iff_eventually_eq f).1 hf (g, h)
    have c1 : Continuous fun z : P × (P × P) => (z.2.1 * z.1, z.2.2) := by fun_prop
    have c2 : Continuous fun z : P × (P × P) => (z.2.1, z.2.2 * z.1) := by fun_prop
    have e1 := (c1.tendsto' ((1 : P), (g, h)) (g, h) (by simp)).eventually hf'
    have e2 := (c2.tendsto' ((1 : P), (g, h)) (g, h) (by simp)).eventually hf'
    have e0 := (continuous_snd.tendsto' ((1 : P), (g, h)) (g, h) rfl).eventually hf'
    filter_upwards [e1, e2, e0] with z h1 h2 h0
    exact ⟨h1.trans h0.symm, h2.trans h0.symm⟩

theorem isOpen_actKer [Finite A] (hact : LcAct P A) : IsOpen (actKer P A : Set P) := by
  refine (actKer P A).isOpen_of_mem_nhds (g := 1) ?_
  have : ∀ᶠ x in 𝓝 (1 : P), ∀ a : A, x • a = a := Filter.eventually_all.2 fun a => by
    filter_upwards [(IsLocallyConstant.iff_eventually_eq _).1 (hact a) 1] with x hx
    rw [hx, one_smul]
  exact this

/-! ## Coset representatives for a (not necessarily normal) subgroup -/

theorem crep_eq_of_mem (H : Subgroup P) {g g' : P} (h : g⁻¹ * g' ∈ H) : crep H g = crep H g' := by
  unfold crep; rw [QuotientGroup.eq.mpr h]

theorem crep_mul_mem (H : Subgroup P) (g : P) {n : P} (hn : n ∈ H) : crep H (g * n) = crep H g :=
  crep_eq_of_mem H (by simpa [mul_assoc] using H.inv_mem hn)

theorem crep_mem_of_mem (H : Subgroup P) {n : P} (hn : n ∈ H) : crep H n ∈ H := by
  have h := H.mul_mem (crep_inv_mul_mem H n) (H.inv_mem hn)
  rw [mul_inv_cancel_right] at h
  simpa using H.inv_mem h

theorem lc_mk {H : Subgroup P} (hH : IsOpen (H : Set P)) :
    IsLocallyConstant (QuotientGroup.mk : P → P ⧸ H) := by
  rw [IsLocallyConstant.iff_eventually_eq]
  intro g
  have hc : Continuous fun y : P => g⁻¹ * y := continuous_const.mul continuous_id
  have : ∀ᶠ y in 𝓝 g, g⁻¹ * y ∈ H :=
    hc.continuousAt.eventually_mem (by rw [inv_mul_cancel]; exact hH.mem_nhds H.one_mem)
  filter_upwards [this] with y hy
  exact (QuotientGroup.eq.mpr hy).symm

theorem lc_crep {H : Subgroup P} (hH : IsOpen (H : Set P)) : IsLocallyConstant (crep H) :=
  (lc_mk hH).comp (fun q : P ⧸ H => q.out)

/-! ## The index lemma -/

theorem zero_right_aux (H : Subgroup P) {f : P × P → A} (hf : IsCocycle₂ f)
    (h0 : ∀ n ∈ H, ∀ n' ∈ H, f (n, n') = 0) :
    ∀ g, ∀ n ∈ H, (f - d₁ (fun g => -f (crep H g, (crep H g)⁻¹ * g))) (g, n) = 0 := by
  intro g n hn
  have hbn : f (crep H n, (crep H n)⁻¹ * n) = 0 :=
    h0 _ (crep_mem_of_mem H hn) _ (crep_inv_mul_mem H n)
  have hgn : crep H (g * n) = crep H g := crep_mul_mem H g hn
  have hc := hf (crep H g) ((crep H g)⁻¹ * g) n
  rw [mul_inv_cancel_left, h0 _ (crep_inv_mul_mem H g) _ hn, smul_zero, zero_add,
    mul_assoc ((crep H g)⁻¹) g n] at hc
  simp only [Pi.sub_apply, d₁_apply, hgn, hbn, neg_zero, smul_zero]
  rw [← hc]; abel

theorem right_inv (H : Subgroup P) {F : P × P → A} (hF : IsCocycle₂ F) (h0 : ∀ g, ∀ n ∈ H, F (g, n) = 0)
    (g x : P) {n : P} (hn : n ∈ H) : F (g, x * n) = F (g, x) := by
  have := hF g x n
  have e1 := h0 (g * x) n hn
  have e2 := h0 x n hn
  rw [e1, e2, smul_zero, zero_add, zero_add] at this
  exact this.symm

/-- **Index lemma.** `H` open of index invertible on `A`; if `f|H×H = d₁ β` with `β` locally constant, then `f` is
a locally constant coboundary on `P`. -/
theorem index_lemma [CompactSpace P] (hact : LcAct P A) (H : Subgroup P) (hH : IsOpen (H : Set P))
    (x : ℤ) (hx : ∀ a : A, (x * (H.index : ℤ)) • a = a)
    {f : P × P → A} (hf : IsLocallyConstant f) (hc : IsCocycle₂ f)
    (β : P → A) (hβ : IsLocallyConstant β) (hβH : ∀ h ∈ H, ∀ h' ∈ H, f (h, h') = d₁ β (h, h')) :
    IsLcCob f := by
  classical
  have : Finite (P ⧸ H) := H.quotient_finite_of_isOpen hH
  let _ : Fintype (P ⧸ H) := Fintype.ofFinite _
  obtain ⟨f₁, hf₁⟩ : ∃ f₁, f₁ = f - d₁ β := ⟨_, rfl⟩
  have hc₁ : IsCocycle₂ f₁ := by rw [hf₁]; exact isCocycle₂_sub_d₁ hc β
  have hl₁ : IsLocallyConstant f₁ := by rw [hf₁]; exact hf.sub (lc_d₁ hact hβ)
  have h0₁ : ∀ n ∈ H, ∀ n' ∈ H, f₁ (n, n') = 0 := fun n hn n' hn' => by
    rw [hf₁, Pi.sub_apply, hβH n hn n' hn', sub_self]
  obtain ⟨b₁, hb₁⟩ : ∃ b₁ : P → A, b₁ = fun g => -f₁ (crep H g, (crep H g)⁻¹ * g) := ⟨_, rfl⟩
  have hlb₁ : IsLocallyConstant b₁ := by
    rw [hb₁]
    have hcont : Continuous fun g : P => (crep H g, (crep H g)⁻¹ * g) :=
      (lc_crep hH).continuous.prodMk ((lc_crep hH).continuous.inv.mul continuous_id)
    exact (hl₁.comp_continuous hcont).comp (fun a => -a)
  obtain ⟨f₂, hf₂⟩ : ∃ f₂, f₂ = f₁ - d₁ b₁ := ⟨_, rfl⟩
  have hc₂ : IsCocycle₂ f₂ := by rw [hf₂]; exact isCocycle₂_sub_d₁ hc₁ b₁
  have h0₂ : ∀ g, ∀ n ∈ H, f₂ (g, n) = 0 := by rw [hf₂, hb₁]; exact zero_right_aux H hc₁ h0₁
  have hl₂ : IsLocallyConstant f₂ := by rw [hf₂]; exact hl₁.sub (lc_d₁ hact hlb₁)
  obtain ⟨F, hF⟩ : ∃ F : P → A, F = fun g => ∑ y : P ⧸ H, f₂ (g, y.out) := ⟨_, rfl⟩
  have hFg : ∀ g, ∑ y : P ⧸ H, f₂ (g, y.out) = F g := fun g => by rw [hF]
  have hlF : IsLocallyConstant F := by
    rw [hF]
    exact lc_sum (fun (y : P ⧸ H) (g : P) => f₂ (g, y.out))
      (fun y => hl₂.comp_continuous (continuous_id.prodMk continuous_const))
  have hperm : ∀ g h : P, ∑ y : P ⧸ H, f₂ (g, h * y.out) = F g := by
    intro g h
    rw [← hFg]
    have hstep : ∀ y : P ⧸ H, f₂ (g, h * y.out) = f₂ (g, (h • y).out) := by
      intro y
      have e : (QuotientGroup.mk (h * y.out) : P ⧸ H) = QuotientGroup.mk ((h • y).out) := by
        rw [QuotientGroup.out_eq', ← smul_eq_mul, ← MulAction.Quotient.smul_mk, QuotientGroup.out_eq']
      have hm := QuotientGroup.eq.mp e
      have := right_inv H hc₂ h0₂ g (h * y.out) hm
      rw [mul_inv_cancel_left] at this
      exact this.symm
    rw [Finset.sum_congr rfl (fun y _ => hstep y)]
    exact Fintype.sum_equiv (MulAction.toPerm h) _ _ (fun y => rfl)
  have key : ∀ g h : P, (H.index : ℤ) • f₂ (g, h) = g • F h - F (g * h) + F g := by
    intro g h
    have hs := Finset.sum_congr (rfl : (Finset.univ : Finset (P ⧸ H)) = Finset.univ)
      (fun y _ => hc₂ g h y.out)
    rw [Finset.sum_add_distrib, Finset.sum_add_distrib, ← Finset.smul_sum, Finset.sum_const,
      Finset.card_univ, hperm, hFg, hFg] at hs
    rw [H.index_eq_card, Nat.card_eq_fintype_card, natCast_zsmul]
    exact eq_of_sub_eq hs (by abel)
  refine ⟨β + b₁ + x • F, ?_, fun g h => ?_⟩
  · have h3 : IsLocallyConstant (x • F) := hlF.comp (fun a : A => x • a)
    exact (hβ.add hlb₁).add h3
  · have e1 : f (g, h) = f₁ (g, h) + d₁ β (g, h) := by rw [hf₁, Pi.sub_apply, sub_add_cancel]
    have e2 : f₁ (g, h) = f₂ (g, h) + d₁ b₁ (g, h) := by rw [hf₂, Pi.sub_apply, sub_add_cancel]
    have e3 : f₂ (g, h) = x • (g • F h - F (g * h) + F g) := by
      rw [← key, ← mul_smul, hx]
    rw [e1, e2, e3, d₁_add, d₁_add]
    simp only [Pi.add_apply, d₁_apply, Pi.smul_apply, smul_add, smul_sub, smul_zsmul']
    abel

end RamanujanPetersson.CdOne


end

-- ===== S4.Def_RP_CdOne_Grp =====
section

/-!
# S4-PD (3), group layer part 2: Sylow reduction and `ℤ/l` coefficients

* `exists_inv_index`: an index prime to `l` is invertible on an `l`-primary module;
* `exists_sylow_open`: the preimage `H` of an `l`-Sylow of the finite quotient `P ⧸ N`;
* `HypL l P`: the hypothesis (Hl) supplied by the field layer (central embedding problems): `ℤ/l`-valued 2-cocycles
  with trivial action on an open subgroup `Q`, factoring through an `l`-group quotient `Q/N`, are locally constant
  coboundaries on `Q`;
* `trivial_coeff`: under `HypL`, every locally constant `ℤ/l`-valued 2-cocycle (trivial action) on `P` is a locally
  constant coboundary (finite level, Sylow, `index_lemma`);
* `hypL_subgroup`: `HypL` passes to open subgroups.
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson.CdOne

open groupCohomology Filter Topology

theorem exists_inv_index {A : Type*} [AddCommGroup A] {l e m : ℕ} (hl : l.Prime) (hm : ¬ l ∣ m)
    (hA : ∀ a : A, (l ^ e) • a = 0) : ∃ x : ℤ, ∀ a : A, (x * m) • a = a := by
  have hcop : Nat.Coprime m (l ^ e) :=
    Nat.Coprime.pow_right e (Nat.coprime_comm.mp ((Nat.Prime.coprime_iff_not_dvd hl).mpr hm))
  obtain ⟨u, v, huv⟩ := Nat.Coprime.isCoprime hcop
  refine ⟨u, fun a => ?_⟩
  have h1 : (u * m : ℤ) = 1 - v * ((l ^ e : ℕ) : ℤ) := by rw [← huv]; ring
  rw [h1, sub_smul, one_smul, mul_smul, natCast_zsmul, hA, smul_zero, sub_zero]

/-- The trivial action (used only as a local instance). -/
def trivAct (P B : Type*) [Monoid P] [AddMonoid B] : DistribMulAction P B where
  smul _ a := a
  one_smul _ := rfl
  mul_smul _ _ _ := rfl
  smul_zero _ := rfl
  smul_add _ _ _ := rfl

variable {P : Type*} [Group P] [TopologicalSpace P] [IsTopologicalGroup P]

/-- The preimage of an `l`-Sylow subgroup of the finite quotient `P ⧸ N`. -/
theorem exists_sylow_open [CompactSpace P] (l : ℕ) [Fact l.Prime] (N : Subgroup P) [N.Normal]
    (hN : IsOpen (N : Set P)) :
    ∃ H : Subgroup P, N ≤ H ∧ IsOpen (H : Set P) ∧ ¬ l ∣ H.index ∧ ∀ q ∈ H, ∃ k : ℕ, q ^ (l ^ k) ∈ N := by
  have : Finite (P ⧸ N) := N.quotient_finite_of_isOpen hN
  obtain ⟨S⟩ := (Sylow.nonempty : Nonempty (Sylow l (P ⧸ N)))
  have hNH : N ≤ (S : Subgroup (P ⧸ N)).comap (QuotientGroup.mk' N) := by
    intro n hn
    rw [Subgroup.mem_comap, QuotientGroup.mk'_apply, (QuotientGroup.eq_one_iff n).mpr hn]
    exact one_mem _
  refine ⟨_, hNH, Subgroup.isOpen_mono hNH hN, ?_, ?_⟩
  · rw [Subgroup.index_comap_of_surjective _ (QuotientGroup.mk'_surjective N)]
    exact S.not_dvd_index
  · intro q hq
    obtain ⟨k, hk⟩ := S.isPGroup' ⟨_, hq⟩
    refine ⟨k, (QuotientGroup.eq_one_iff _).mp ?_⟩
    have := congrArg Subtype.val hk
    simpa using this

/-- **(Hl)**: `ℤ/l`-valued 2-cocycles (trivial action) on an open subgroup `Q` that factor through an `l`-group
quotient `Q/N` are locally constant coboundaries on `Q`. Supplied by the field layer (Kummer theory over a C1 field). -/
def HypL (l : ℕ) (P : Type*) [Group P] [TopologicalSpace P] : Prop :=
  ∀ Q N : Subgroup P, IsOpen (Q : Set P) → IsOpen (N : Set P) → N ≤ Q →
    (∀ q ∈ Q, ∀ n ∈ N, q * n * q⁻¹ ∈ N) → (∀ q ∈ Q, ∃ k : ℕ, q ^ (l ^ k) ∈ N) →
    ∀ f : P × P → ZMod l, IsLocallyConstant f →
    (∀ g ∈ Q, ∀ h ∈ Q, ∀ j ∈ Q, f (g * h, j) + f (g, h) = f (h, j) + f (g, h * j)) →
    (∀ g ∈ Q, ∀ h ∈ Q, ∀ n ∈ N, ∀ n' ∈ N, f (g * n, h * n') = f (g, h)) →
    ∃ γ : P → ZMod l, IsLocallyConstant γ ∧ ∀ g ∈ Q, ∀ h ∈ Q, f (g, h) = γ h - γ (g * h) + γ g

/-- Under `HypL`, every locally constant `ℤ/l`-valued 2-cocycle with trivial action is a locally constant
coboundary. -/
theorem trivial_coeff [CompactSpace P] (l : ℕ) [hl : Fact l.Prime] (hL : HypL l P) {f : P × P → ZMod l}
    (hf : IsLocallyConstant f) (hc : ∀ g h j : P, f (g * h, j) + f (g, h) = f (h, j) + f (g, h * j)) :
    ∃ γ : P → ZMod l, IsLocallyConstant γ ∧ ∀ g h : P, f (g, h) = γ h - γ (g * h) + γ g := by
  obtain ⟨W, hWo, hW⟩ := exists_open_inv hf
  obtain ⟨N, hNn, hNo, hNW⟩ := exists_openNormal_le W hWo
  have := hNn
  obtain ⟨H, hNH, hHo, hl', hH⟩ := exists_sylow_open l N hNo
  obtain ⟨γ, hγ, hγH⟩ := hL H N hHo hNo hNH (fun q _ n hn => hNn.conj_mem n hn q) hH f hf
    (fun g _ h _ j _ => hc g h j)
    (fun g _ h _ n hn n' hn' => by rw [(hW n (hNW hn) g (h * n')).1, (hW n' (hNW hn') g h).2])
  letI : DistribMulAction P (ZMod l) := trivAct P (ZMod l)
  obtain ⟨x, hx⟩ := exists_inv_index (A := ZMod l) (e := 1) hl.out hl' (fun a => by simp)
  obtain ⟨b, hb, hfb⟩ := index_lemma (fun a => IsLocallyConstant.const a) H hHo x hx hf
    (fun g h j => hc g h j) γ hγ (fun h hh h' hh' => hγH h hh h' hh')
  exact ⟨b, hb, fun g h => hfb g h⟩

/-- `HypL` passes to open subgroups. -/
theorem hypL_subgroup (l : ℕ) (hL : HypL l P) (H : Subgroup P) (hH : IsOpen (H : Set P)) : HypL l H := by
  classical
  intro Q₁ N₁ hQ₁ hN₁ hNQ₁ hnorm hlg f₁ hf₁ hc₁ hinv₁
  have hemb := hH.isOpenEmbedding_subtypeVal
  have hopen : ∀ K : Subgroup H, IsOpen (K : Set H) → IsOpen ((K.map H.subtype : Subgroup P) : Set P) := by
    intro K hK
    rw [Subgroup.coe_map]
    exact hemb.isOpenMap _ hK
  let f : P × P → ZMod l := fun p =>
    if hp : p ∈ (H : Set P) ×ˢ (H : Set P) then f₁ (⟨p.1, hp.1⟩, ⟨p.2, hp.2⟩) else 0
  have hfv : ∀ a b : H, f ((a : P), (b : P)) = f₁ (a, b) := fun a b => by
    simp only [f, dif_pos (Set.mk_mem_prod a.2 b.2)]
  have hlf : IsLocallyConstant f := by
    have hc : IsClopen (H : Set P) := ⟨H.isClosed_of_isOpen hH, hH⟩
    refine lc_dite (hc.prod hc) (fun p => f₁ (⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩)) ?_
    exact hf₁.comp_continuous
      (((continuous_fst.comp continuous_subtype_val).subtype_mk _).prodMk
        ((continuous_snd.comp continuous_subtype_val).subtype_mk _))
  have hnorm' : ∀ q ∈ Q₁.map H.subtype, ∀ n ∈ N₁.map H.subtype, q * n * q⁻¹ ∈ N₁.map H.subtype := by
    rintro _ ⟨q, hq, rfl⟩ _ ⟨n, hn, rfl⟩
    exact ⟨q * n * q⁻¹, hnorm q hq n hn, by simp⟩
  have hlg' : ∀ q ∈ Q₁.map H.subtype, ∃ k : ℕ, q ^ (l ^ k) ∈ N₁.map H.subtype := by
    rintro _ ⟨q, hq, rfl⟩
    obtain ⟨k, hk⟩ := hlg q hq
    exact ⟨k, ⟨_, hk, by simp⟩⟩
  have hcoc : ∀ g ∈ Q₁.map H.subtype, ∀ h ∈ Q₁.map H.subtype, ∀ j ∈ Q₁.map H.subtype,
      f (g * h, j) + f (g, h) = f (h, j) + f (g, h * j) := by
    rintro _ ⟨g, hg, rfl⟩ _ ⟨h, hh, rfl⟩ _ ⟨j, hj, rfl⟩
    simp only [Subgroup.coe_subtype]
    rw [← Subgroup.coe_mul, ← Subgroup.coe_mul, hfv, hfv, hfv, hfv]
    exact hc₁ g hg h hh j hj
  have hinv : ∀ g ∈ Q₁.map H.subtype, ∀ h ∈ Q₁.map H.subtype, ∀ n ∈ N₁.map H.subtype,
      ∀ n' ∈ N₁.map H.subtype, f (g * n, h * n') = f (g, h) := by
    rintro _ ⟨g, hg, rfl⟩ _ ⟨h, hh, rfl⟩ _ ⟨n, hn, rfl⟩ _ ⟨n', hn', rfl⟩
    simp only [Subgroup.coe_subtype]
    rw [← Subgroup.coe_mul, ← Subgroup.coe_mul, hfv, hfv]
    exact hinv₁ g hg h hh n hn n' hn'
  obtain ⟨γ, hγ, hγQ⟩ := hL (Q₁.map H.subtype) (N₁.map H.subtype) (hopen Q₁ hQ₁) (hopen N₁ hN₁)
    (Subgroup.map_mono hNQ₁) hnorm' hlg' f hlf hcoc hinv
  refine ⟨γ ∘ Subtype.val, hγ.comp_continuous continuous_subtype_val, fun g hg h hh => ?_⟩
  have := hγQ g ⟨g, hg, rfl⟩ h ⟨h, hh, rfl⟩
  rw [hfv] at this
  exact this

end RamanujanPetersson.CdOne


end

-- ===== S4.Def_RP_CdOne_Dev =====
section

/-!
# S4-PD (3), group layer part 3: dévissage and `H²(P, A) = 0`

* `exists_fixed_order_l`: an `l`-group action on a finite module of order divisible by `l` fixes an element of
  order `l` (fixed points of the image in `Perm A`, an `l`-group);
* `quotAct`: the action on `A ⧸ M` for a stable subgroup `M`;
* `lgroup_case`: under `HypL`, if `P` acts on `A` (`|A| = lᵉ`) through an `l`-group, every locally constant
  2-cocycle is a locally constant coboundary (induction on `e`, `trivial_coeff` on `⟨m⟩ ≅ ℤ/l`);
* `cd_le_one`: the same for any finite module of order `lᵉ` with locally constant action (Sylow + `index_lemma`).
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

universe u

namespace RamanujanPetersson.CdOne

open groupCohomology

variable {P : Type*} [Group P] [TopologicalSpace P] [IsTopologicalGroup P]

section Fixed

variable {A : Type*} [AddCommGroup A] [DistribMulAction P A]

/-- The `P`-fixed vectors. -/
def fixAdd (P A : Type*) [Group P] [AddCommGroup A] [DistribMulAction P A] : AddSubgroup A where
  carrier := {a | ∀ g : P, g • a = a}
  zero_mem' := fun g => smul_zero g
  add_mem' := fun {a b} ha hb g => by rw [smul_add, ha g, hb g]
  neg_mem' := fun {a} ha g => by rw [smul_neg, ha g]

theorem exists_fixed_order_l [Finite A] (l : ℕ) [hl : Fact l.Prime] (hdvd : l ∣ Nat.card A)
    (hp : ∀ g : P, ∃ k : ℕ, ∀ a : A, g ^ (l ^ k) • a = a) :
    ∃ m : A, addOrderOf m = l ∧ ∀ g : P, g • m = m := by
  classical
  let G := (MulAction.toPermHom P A).range
  have hG : IsPGroup l G := by
    rintro ⟨_, g, rfl⟩
    obtain ⟨k, hk⟩ := hp g
    refine ⟨k, Subtype.ext ?_⟩
    simp only [SubgroupClass.coe_pow, OneMemClass.coe_one]
    rw [← map_pow]
    ext a
    simp [hk]
  have hmod := hG.card_modEq_card_fixedPoints A
  have hset : MulAction.fixedPoints G A = (fixAdd P A : Set A) := by
    ext a
    constructor
    · intro h g
      exact h ⟨MulAction.toPermHom P A g, g, rfl⟩
    · rintro h ⟨_, g, rfl⟩
      exact h g
  have hcard : l ∣ Nat.card (fixAdd P A) := by
    have h1 : Nat.card (MulAction.fixedPoints G A) = Nat.card (fixAdd P A) := by
      rw [hset]; rfl
    rw [← h1]
    exact Nat.modEq_zero_iff_dvd.mp (hmod.symm.trans (Nat.modEq_zero_iff_dvd.mpr hdvd))
  let _ : Fintype (fixAdd P A) := Fintype.ofFinite _
  rw [Nat.card_eq_fintype_card] at hcard
  obtain ⟨m, hm⟩ := exists_prime_addOrderOf_dvd_card l hcard
  exact ⟨m, by rw [AddSubgroup.addOrderOf_coe, hm], m.2⟩

end Fixed

section Quot

variable {A : Type*} [AddCommGroup A] [DistribMulAction P A] (M : AddSubgroup A)
  (hM : ∀ g : P, ∀ a ∈ M, g • a ∈ M)

/-- `g` acting on `A ⧸ M`. -/
def qsmul (g : P) : A ⧸ M →+ A ⧸ M :=
  QuotientAddGroup.map M M (DistribSMul.toAddMonoidHom A g) (fun a ha => hM g a ha)

theorem qsmul_mk (g : P) (a : A) : qsmul M hM g (a : A ⧸ M) = ((g • a : A) : A ⧸ M) := rfl

/-- The action on `A ⧸ M` (local instance). -/
def quotAct : DistribMulAction P (A ⧸ M) where
  smul g q := qsmul M hM g q
  one_smul q := by
    obtain ⟨a, rfl⟩ := QuotientAddGroup.mk_surjective q
    exact (qsmul_mk M hM 1 a).trans (congrArg (fun x : A => (x : A ⧸ M)) (one_smul P a))
  mul_smul g h q := by
    obtain ⟨a, rfl⟩ := QuotientAddGroup.mk_surjective q
    exact (qsmul_mk M hM _ a).trans (congrArg (fun x : A => (x : A ⧸ M)) (mul_smul g h a))
  smul_zero g := map_zero (qsmul M hM g)
  smul_add g := map_add (qsmul M hM g)

end Quot

/-- Under `HypL`: actions through an `l`-group on modules of order `lᵉ` have no locally constant `H²`. -/
theorem lgroup_case [CompactSpace P] (l : ℕ) [hl : Fact l.Prime] (hL : HypL l P) (e : ℕ) :
    ∀ (A : Type u) [AddCommGroup A] [DistribMulAction P A] [Finite A], Nat.card A = l ^ e → LcAct P A →
    (∀ g : P, ∃ k : ℕ, ∀ a : A, g ^ (l ^ k) • a = a) →
    ∀ f : P × P → A, IsLocallyConstant f → IsCocycle₂ f → IsLcCob f := by
  induction e with
  | zero =>
    intro A _ _ _ hcard _ _ f _ _
    have : Subsingleton A := Finite.card_le_one_iff_subsingleton.mp (by rw [hcard, pow_zero])
    exact ⟨0, IsLocallyConstant.const 0, fun g h => Subsingleton.elim _ _⟩
  | succ e ih =>
    intro A _ _ _ hcard hact hp f hf hc
    obtain ⟨m, hm, hmfix⟩ :=
      exists_fixed_order_l l (by rw [hcard]; exact dvd_pow_self l (Nat.succ_ne_zero e)) hp
    have hMfix : ∀ a ∈ AddSubgroup.zmultiples m, ∀ g : P, g • a = a := by
      intro a ha g
      obtain ⟨z, rfl⟩ := AddSubgroup.mem_zmultiples_iff.mp ha
      rw [smul_zsmul', hmfix g]
    have hM : ∀ g : P, ∀ a ∈ AddSubgroup.zmultiples m, g • a ∈ AddSubgroup.zmultiples m :=
      fun g a ha => by rw [hMfix a ha g]; exact ha
    letI : DistribMulAction P (A ⧸ AddSubgroup.zmultiples m) := quotAct _ hM
    have hcard' : Nat.card (A ⧸ AddSubgroup.zmultiples m) = l ^ e := by
      have h1 := AddSubgroup.card_eq_card_quotient_mul_card_addSubgroup (AddSubgroup.zmultiples m)
      rw [Nat.card_zmultiples, hm, hcard, pow_succ] at h1
      exact (Nat.eq_of_mul_eq_mul_right hl.out.pos h1).symm
    have hactq : LcAct P (A ⧸ AddSubgroup.zmultiples m) := by
      intro q
      obtain ⟨a, rfl⟩ := QuotientAddGroup.mk_surjective q
      exact (hact a).comp (fun x : A => (x : A ⧸ AddSubgroup.zmultiples m))
    have hpq : ∀ g : P, ∃ k : ℕ, ∀ q : A ⧸ AddSubgroup.zmultiples m, g ^ (l ^ k) • q = q := by
      intro g
      obtain ⟨k, hk⟩ := hp g
      refine ⟨k, fun q => ?_⟩
      obtain ⟨a, rfl⟩ := QuotientAddGroup.mk_surjective q
      exact congrArg (fun x : A => (x : A ⧸ AddSubgroup.zmultiples m)) (hk a)
    have hcq : IsCocycle₂ (fun p => (f p : A ⧸ AddSubgroup.zmultiples m)) := by
      intro g h j
      have := congrArg (fun x : A => (x : A ⧸ AddSubgroup.zmultiples m)) (hc g h j)
      rw [QuotientAddGroup.mk_add, QuotientAddGroup.mk_add] at this
      exact this
    obtain ⟨b'', hb'', hfb''⟩ := ih (A ⧸ AddSubgroup.zmultiples m) hcard' hactq hpq _
      (hf.comp (fun x : A => (x : A ⧸ AddSubgroup.zmultiples m))) hcq
    obtain ⟨b, hb⟩ : ∃ b : P → A, b = fun g => (b'' g).out := ⟨_, rfl⟩
    have hlb : IsLocallyConstant b := by rw [hb]; exact hb''.comp _
    have e1 : ∀ x : P, ((b x : A) : A ⧸ AddSubgroup.zmultiples m) = b'' x := fun x => by
      rw [hb]; exact QuotientAddGroup.out_eq' _
    have hFM : ∀ g h : P, (f - d₁ b) (g, h) ∈ AddSubgroup.zmultiples m := by
      intro g h
      rw [← QuotientAddGroup.eq_zero_iff]
      have hq : ((f (g, h) : A) : A ⧸ AddSubgroup.zmultiples m) = d₁ b'' (g, h) := hfb'' g h
      have e2 : ((g • b h : A) : A ⧸ AddSubgroup.zmultiples m) = g • b'' h :=
        (qsmul_mk _ hM g (b h)).symm.trans (congrArg (qsmul _ hM g) (e1 h))
      rw [Pi.sub_apply, QuotientAddGroup.mk_sub, hq, d₁_apply, d₁_apply, QuotientAddGroup.mk_add,
        QuotientAddGroup.mk_sub, e2, e1, e1, sub_self]
    have hml : (l : ℤ) • m = 0 := by rw [natCast_zsmul, ← hm]; exact addOrderOf_nsmul_eq_zero m
    let E : ZMod l →+ A := ZMod.lift l ⟨zmultiplesHom A m, by simpa using hml⟩
    have hE : ∀ z : ℤ, E (z : ZMod l) = z • m := fun z => by
      simp only [E, ZMod.lift_coe, zmultiplesHom_apply]
    have hEinj : Function.Injective E := by
      rw [injective_iff_map_eq_zero]
      intro k hk
      obtain ⟨z, rfl⟩ := ZMod.intCast_surjective k
      rw [hE, ← addOrderOf_dvd_iff_zsmul_eq_zero, hm] at hk
      exact (ZMod.intCast_zmod_eq_zero_iff_dvd z l).mpr hk
    have hEmem : ∀ k : ZMod l, E k ∈ AddSubgroup.zmultiples m := fun k => by
      obtain ⟨z, rfl⟩ := ZMod.intCast_surjective k
      rw [hE]
      exact AddSubgroup.mem_zmultiples_iff.mpr ⟨z, rfl⟩
    have hErange : ∀ a ∈ AddSubgroup.zmultiples m, ∃ k, E k = a := by
      intro a ha
      obtain ⟨z, rfl⟩ := AddSubgroup.mem_zmultiples_iff.mp ha
      exact ⟨z, hE z⟩
    obtain ⟨c, hcdef⟩ : ∃ c : P × P → ZMod l, c = fun p => Function.invFun E ((f - d₁ b) p) :=
      ⟨_, rfl⟩
    have hEc : ∀ p, E (c p) = (f - d₁ b) p := fun p => by
      rw [hcdef]
      obtain ⟨k, hk⟩ := hErange _ (hFM p.1 p.2)
      exact Function.invFun_eq ⟨k, hk⟩
    have hlF : IsLocallyConstant (f - d₁ b) := hf.sub (lc_d₁ hact hlb)
    have hlc : IsLocallyConstant c := by rw [hcdef]; exact hlF.comp (Function.invFun E)
    have hcF : IsCocycle₂ (f - d₁ b) := isCocycle₂_sub_d₁ hc b
    have hcc : ∀ g h j : P, c (g * h, j) + c (g, h) = c (h, j) + c (g, h * j) := by
      intro g h j
      apply hEinj
      rw [map_add, map_add, hEc, hEc, hEc, hEc, hcF g h j, hMfix _ (hFM h j) g]
    obtain ⟨γ, hγ, hcγ⟩ := trivial_coeff l hL hlc hcc
    refine ⟨b + E ∘ γ, hlb.add (hγ.comp E), fun g h => ?_⟩
    have h1 : f (g, h) = (f - d₁ b) (g, h) + d₁ b (g, h) := by rw [Pi.sub_apply, sub_add_cancel]
    rw [h1, ← hEc, hcγ g h, d₁_add]
    simp only [Pi.add_apply, d₁_apply, Function.comp_apply, map_add, map_sub]
    rw [hMfix _ (hEmem (γ h)) g]
    abel

/-- **`cd_l ≤ 1`, group form.** Under `HypL`, for a compact group `P` and a finite module `A` of order `lᵉ` with
locally constant action, every locally constant 2-cocycle is a locally constant coboundary. -/
theorem cd_le_one [CompactSpace P] (l : ℕ) [hl : Fact l.Prime] (hL : HypL l P) (e : ℕ) (A : Type u)
    [AddCommGroup A] [DistribMulAction P A] [Finite A] (hcard : Nat.card A = l ^ e) (hact : LcAct P A)
    {f : P × P → A} (hf : IsLocallyConstant f) (hc : IsCocycle₂ f) : IsLcCob f := by
  classical
  obtain ⟨N, hNn, hNo, hNK⟩ := exists_openNormal_le (actKer P A) (isOpen_actKer hact)
  have := hNn
  obtain ⟨H, hNH, hHo, hl', hH⟩ := exists_sylow_open l N hNo
  have : CompactSpace H := isCompact_iff_compactSpace.mp (H.isClosed_of_isOpen hHo).isCompact
  have hLH : HypL l H := hypL_subgroup l hL H hHo
  have hactH : LcAct H A := fun a => (hact a).comp_continuous continuous_subtype_val
  have hpH : ∀ g : H, ∃ k : ℕ, ∀ a : A, g ^ (l ^ k) • a = a := by
    intro g
    obtain ⟨k, hk⟩ := hH g g.2
    exact ⟨k, fun a => (mem_actKer.mp (hNK hk)) a⟩
  obtain ⟨β₀, hβ₀, hfβ₀⟩ := lgroup_case l hLH e A hcard hactH hpH (fun p : H × H => f (p.1, p.2))
    (hf.comp_continuous (continuous_subtype_val.prodMap continuous_subtype_val)) (fun g h j => hc g h j)
  obtain ⟨x, hx⟩ := exists_inv_index (A := A) (e := e) hl.out hl'
    (fun a => by rw [← hcard]; exact card_nsmul_eq_zero')
  refine index_lemma hact H hHo x hx hf hc (fun g => if h : g ∈ H then β₀ ⟨g, h⟩ else 0)
    (lc_dite (S := (H : Set P)) ⟨H.isClosed_of_isOpen hHo, hHo⟩ β₀ hβ₀) (fun h hh h' hh' => ?_)
  simp only [d₁_apply, dif_pos hh, dif_pos hh', dif_pos (H.mul_mem hh hh')]
  exact hfβ₀ ⟨h, hh⟩ ⟨h', hh'⟩

end RamanujanPetersson.CdOne


end

-- ===== S4.Def_RP_CdOne_Wrap =====
section

/-!
# S4-PD (3), group layer part 4: wrappers for `cd_l ≤ 1`

* `card_eq_pow_of_nsmul`: a finite abelian group killed by `lⁿ` has order a power of `l` (Cauchy);
* `cd_le_one_of_nsmul`: `cd_le_one` for modules killed by `lⁿ`;
* `repAct`, `h2_eq_zero`: the statement for a closed (compact) subgroup `Γ` of a topological group `G` acting on
  `M` through a representation `ρ` with open kernel (the `S4-CurveCoh` convention: cochains on `Γ`).
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

universe u

namespace RamanujanPetersson.CdOne

open groupCohomology Topology

/-- A finite abelian group killed by `lⁿ` has order a power of `l`. -/
theorem card_eq_pow_of_nsmul (A : Type*) [AddCommGroup A] [Finite A] (l : ℕ) [hl : Fact l.Prime] (n : ℕ)
    (hA : ∀ a : A, (l ^ n) • a = 0) : ∃ e : ℕ, Nat.card A = l ^ e := by
  refine ⟨_, Nat.eq_prime_pow_of_unique_prime_dvd Nat.card_pos.ne' (fun {d} hd hdvd => ?_)⟩
  have := Fact.mk hd
  obtain ⟨a, ha⟩ := exists_prime_addOrderOf_dvd_card' d hdvd
  have h1 : addOrderOf a ∣ l ^ n := addOrderOf_dvd_of_nsmul_eq_zero (hA a)
  rw [ha] at h1
  exact (Nat.prime_dvd_prime_iff_eq hd hl.out).mp (hd.dvd_of_dvd_pow h1)

/-- **`cd_l ≤ 1`** for finite modules killed by `lⁿ` with locally constant action. -/
theorem cd_le_one_of_nsmul {P : Type*} [Group P] [TopologicalSpace P] [IsTopologicalGroup P] [CompactSpace P]
    (l : ℕ) [Fact l.Prime] (hL : HypL l P) (n : ℕ) (A : Type u) [AddCommGroup A] [DistribMulAction P A]
    [Finite A] (hA : ∀ a : A, (l ^ n) • a = 0) (hact : LcAct P A) {f : P × P → A} (hf : IsLocallyConstant f)
    (hc : IsCocycle₂ f) : IsLcCob f := by
  obtain ⟨e, he⟩ := card_eq_pow_of_nsmul A l n hA
  exact cd_le_one l hL e A he hact hf hc

section Rep

variable {k : Type*} [CommRing k] {G : Type*} [Group G] [TopologicalSpace G] [IsTopologicalGroup G]
  {M : Type u} [AddCommGroup M] [Module k M]

/-- The action of a subgroup `Γ` on `M` through `ρ`. -/
def repAct (ρ : Representation k G M) (Γ : Subgroup G) : DistribMulAction Γ M where
  smul g m := ρ g m
  one_smul m := by
    show ρ ((1 : Γ) : G) m = m
    simp
  mul_smul g h m := by
    show ρ ((g * h : Γ) : G) m = ρ g (ρ h m)
    simp
  smul_zero g := map_zero (ρ g)
  smul_add g a b := map_add (ρ g) a b

theorem repAct_lc (ρ : Representation k G M) (Γ : Subgroup G) (hρ : IsOpen (ρ.ker : Set G)) (m : M) :
    IsLocallyConstant fun g : Γ => ρ g m := by
  have hH : IsOpen (((ρ.ker).comap Γ.subtype : Subgroup Γ) : Set Γ) := hρ.preimage continuous_subtype_val
  rw [IsLocallyConstant.iff_eventually_eq]
  intro g
  have h1 : (((ρ.ker).comap Γ.subtype : Subgroup Γ) : Set Γ) ∈ 𝓝 (1 : Γ) :=
    hH.mem_nhds (Subgroup.one_mem _)
  have h2 : Filter.Tendsto (fun x : Γ => g⁻¹ * x) (𝓝 g) (𝓝 1) := by
    have := (continuous_mul_left g⁻¹).tendsto g
    rwa [inv_mul_cancel] at this
  filter_upwards [h2 h1] with x hx
  have hx' : ρ ((g⁻¹ * x : Γ) : G) = 1 := MonoidHom.mem_ker.mp (Subgroup.mem_comap.mp hx)
  have hxg : x = g * (g⁻¹ * x) := (mul_inv_cancel_left g x).symm
  calc ρ (x : G) m = ρ ((g * (g⁻¹ * x) : Γ) : G) m := by rw [← hxg]
    _ = ρ g (ρ ((g⁻¹ * x : Γ) : G) m) := by simp only [Subgroup.coe_mul, map_mul, Module.End.mul_apply]
    _ = ρ g m := by rw [hx']; rfl

/-- **`H²(Γ, M) = 0`** (locally constant cochains on `Γ`, action through `ρ`), for a compact subgroup `Γ`
satisfying `HypL`, a finite `M` killed by `lⁿ` and `ρ` with open kernel. -/
theorem h2_eq_zero (ρ : Representation k G M) (Γ : Subgroup G) [CompactSpace Γ] (l : ℕ) [Fact l.Prime]
    (hL : HypL l Γ) (n : ℕ) [Finite M] (hM : ∀ m : M, (l ^ n) • m = 0) (hρ : IsOpen (ρ.ker : Set G))
    {f : Γ × Γ → M} (hf : IsLocallyConstant f)
    (hc : ∀ g h j : Γ, f (g * h, j) + f (g, h) = ρ g (f (h, j)) + f (g, h * j)) :
    ∃ b : Γ → M, IsLocallyConstant b ∧ ∀ g h : Γ, f (g, h) = ρ g (b h) - b (g * h) + b g := by
  letI := repAct ρ Γ
  obtain ⟨b, hb, hfb⟩ := cd_le_one_of_nsmul l hL n M hM (fun m => repAct_lc ρ Γ hρ m) hf
    (fun g h j => hc g h j)
  exact ⟨b, hb, fun g h => hfb g h⟩

end Rep

end RamanujanPetersson.CdOne


end

-- ===== S4.Def_RP_PerfectCx_Z1Ex =====
section

/-!
# S4-PD (5), E2.1: locally constant 1-cocycles are exact under `H² = 0`

For a subgroup `Γ` of a topological group `G` and representations `ρ`, `σ` of `G`, an equivariant linear map
`q : M → N` induces `z1Map : Z¹(Γ, M) → Z¹(Γ, N)` (locally constant cocycles, the `S4-CurveCoh` convention).

* `H2Van ρ Γ K`: locally constant 2-cocycles with values in the submodule `K` are coboundaries of locally constant
  `K`-valued cochains (cochains on `Γ`, the `h2_eq_zero` shape);
* `z1Map_surjective`: if `q` is surjective and `H2Van` holds for `ker q`, then `z1Map` is surjective
  (lift a cocycle along a set-theoretic section, its coboundary lies in `ker q`, correct by a `ker q`-valued cochain);
* `H2All k G Γ l n`: `H² = 0` for every finite `lⁿ`-torsion representation with open kernel (the output shape of
  `h2_pi1geo_eq_zero` / `h2_closed_eq_zero`); `h2Van_of_all` passes it to subrepresentations, and
  `z1Map_surjective_of_all` is the exactness statement used for `E_Γ = Z¹(Γ; A)` and `E_s = Z¹(I_s; A)`.
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson
namespace PerfectCx

open CurveCoh

noncomputable section

variable {k : Type} [CommRing k] {G : Type} [Group G] [TopologicalSpace G] [IsTopologicalGroup G]
  {M : Type} [AddCommGroup M] [Module k M] {N : Type} [AddCommGroup N] [Module k N]
  (ρ : Representation k G M) (σ : Representation k G N) (Γ : Subgroup G)

theorem lcRep_of_isOpen (hρ : IsOpen (ρ.ker : Set G)) : LcRep ρ Γ :=
  fun m => CdOne.repAct_lc ρ Γ hρ m

theorem lc_act_comp (hact : LcRep ρ Γ) {c : Γ → M} (hc : IsLocallyConstant c) :
    IsLocallyConstant fun p : Γ × Γ => ρ p.1 (c p.2) := by
  rw [IsLocallyConstant.iff_eventually_eq]
  rintro ⟨g, h⟩
  have h1 := (IsLocallyConstant.iff_eventually_eq _).1 (hact (c h)) g
  have h2 := (IsLocallyConstant.iff_eventually_eq _).1 hc h
  rw [nhds_prod_eq]
  filter_upwards [h1.prod_mk h2] with p hp
  rw [hp.2, hp.1]

/-- The coboundary of a locally constant 1-cochain is locally constant. -/
theorem lc_cob (hact : LcRep ρ Γ) {c : Γ → M} (hc : IsLocallyConstant c) :
    IsLocallyConstant fun p : Γ × Γ => ρ p.1 (c p.2) - c (p.1 * p.2) + c p.1 :=
  ((lc_act_comp ρ Γ hact hc).sub (hc.comp_continuous continuous_mul)).add
    (hc.comp_continuous continuous_fst)

/-- The map on locally constant 1-cocycles induced by an equivariant linear map. -/
def z1Map (q : M →ₗ[k] N) (hq : ∀ (g : G) (m : M), q (ρ g m) = σ g (q m)) : Z1 ρ Γ →ₗ[k] Z1 σ Γ where
  toFun c := ⟨q ∘ c, (mem_Z1 σ Γ _).2 ⟨((mem_Z1 ρ Γ _).1 c.2).1.comp q, fun g h => by
    simp only [Function.comp_apply, ((mem_Z1 ρ Γ _).1 c.2).2 g h, map_add, hq]⟩⟩
  map_add' c d := by
    refine Subtype.ext (funext fun g => ?_)
    simp
  map_smul' a c := by
    refine Subtype.ext (funext fun g => ?_)
    simp

theorem z1Map_apply (q : M →ₗ[k] N) (hq : ∀ (g : G) (m : M), q (ρ g m) = σ g (q m)) (c : Z1 ρ Γ) (g : Γ) :
    (z1Map ρ σ Γ q hq c : Γ → N) g = q ((c : Γ → M) g) := rfl

/-- **Exactness of `Z¹(Γ; -)`**: if `H²(Γ, ker q) = 0`, cocycles lift along a surjective equivariant `q`. -/
theorem z1Map_surjective (hact : LcRep ρ Γ) (q : M →ₗ[k] N) (hq : ∀ (g : G) (m : M), q (ρ g m) = σ g (q m))
    (hsurj : Function.Surjective q) (hH2 : H2Van ρ Γ (LinearMap.ker q)) :
    Function.Surjective (z1Map ρ σ Γ q hq) := by
  rintro ⟨c'', hc''⟩
  obtain ⟨hlc'', hco''⟩ := (mem_Z1 σ Γ c'').1 hc''
  have hqs : ∀ y, q (Function.surjInv hsurj y) = y := Function.surjInv_eq hsurj
  obtain ⟨c, hcdef⟩ : ∃ c : Γ → M, c = Function.surjInv hsurj ∘ c'' := ⟨_, rfl⟩
  have hc : IsLocallyConstant c := by
    rw [hcdef]
    exact hlc''.comp _
  have hqc : ∀ g, q (c g) = c'' g := fun g => by
    rw [hcdef, Function.comp_apply, hqs]
  obtain ⟨b, hb, hbK, hfb⟩ := hH2 (fun p => ρ p.1 (c p.2) - c (p.1 * p.2) + c p.1) (lc_cob ρ Γ hact hc)
    (fun p => by
      rw [LinearMap.mem_ker]
      simp only [map_add, map_sub, hq, hqc]
      rw [hco'']
      abel)
    (fun g h j => by
      dsimp only
      simp only [Subgroup.coe_mul, map_mul, Module.End.mul_apply, map_sub, map_add, mul_assoc]
      abel)
  refine ⟨⟨c - b, (mem_Z1 ρ Γ _).2 ⟨hc.sub hb, fun g h => ?_⟩⟩, ?_⟩
  · have e := hfb g h
    dsimp only at e
    have e' : c (g * h) = ρ g (c h) + c g - (ρ g (b h) - b (g * h) + b g) := by
      rw [← e]
      abel
    simp only [Pi.sub_apply, map_sub]
    rw [e']
    abel
  · refine Subtype.ext (funext fun g => ?_)
    show q (c g - b g) = c'' g
    rw [map_sub, LinearMap.mem_ker.1 (hbK g), sub_zero, hqc]

/-- `H²(Γ, -) = 0` for all finite `lⁿ`-torsion representations of `G` over `k` with open kernel. -/
def H2All (k G : Type) [CommRing k] [Group G] [TopologicalSpace G] (Γ : Subgroup G) (l n : ℕ) : Prop :=
  ∀ (M : Type) [AddCommGroup M] [Module k M] (ρ : Representation k G M) [Finite M],
    (∀ m : M, (l ^ n) • m = 0) → IsOpen (ρ.ker : Set G) → ∀ f : Γ × Γ → M, IsLocallyConstant f →
    (∀ g h j : Γ, f (g * h, j) + f (g, h) = ρ g (f (h, j)) + f (g, h * j)) →
    ∃ b : Γ → M, IsLocallyConstant b ∧ ∀ g h : Γ, f (g, h) = ρ g (b h) - b (g * h) + b g

theorem h2Van_of_all {l n : ℕ} (hall : H2All k G Γ l n) [Finite M] (hM : ∀ m : M, (l ^ n) • m = 0)
    (hρ : IsOpen (ρ.ker : Set G)) (K : Subrepresentation ρ) : H2Van ρ Γ K.toSubmodule := by
  intro f hf hfK hc
  have hker : ρ.ker ≤ K.toRepresentation.ker := fun g hg => by
    rw [MonoidHom.mem_ker] at hg ⊢
    refine LinearMap.ext fun v => Subtype.ext ?_
    show ρ g v = v
    rw [hg]
    rfl
  obtain ⟨b, hb, hfb⟩ := hall K.toSubmodule K.toRepresentation
    (fun m => Subtype.ext (by simp [hM])) (Subgroup.isOpen_mono hker hρ)
    (fun x => ⟨f x, hfK x⟩) (IsLocallyConstant.desc _ Subtype.val hf Subtype.val_injective)
    (fun g h j => Subtype.ext (by simpa [toRep_val] using hc g h j))
  refine ⟨fun g => b g, hb.comp Subtype.val, fun g => (b g).2, fun g h => ?_⟩
  have := congrArg Subtype.val (hfb g h)
  simpa [toRep_val] using this

/-- **Exactness of `Z¹(Γ; -)` on finite `lⁿ`-torsion modules** given `H2All` (e.g. `Γ = π₁^geo` or a closed
subgroup of it). -/
theorem z1Map_surjective_of_all {l n : ℕ} (hall : H2All k G Γ l n) [Finite M] (hM : ∀ m : M, (l ^ n) • m = 0)
    (hρ : IsOpen (ρ.ker : Set G)) (q : M →ₗ[k] N) (hq : ∀ (g : G) (m : M), q (ρ g m) = σ g (q m))
    (hsurj : Function.Surjective q) : Function.Surjective (z1Map ρ σ Γ q hq) :=
  z1Map_surjective ρ σ Γ (lcRep_of_isOpen ρ Γ hρ) q hq hsurj
    (h2Van_of_all ρ Γ hall hM hρ (kerRep ρ σ q hq))

end

end PerfectCx
end RamanujanPetersson


end

-- ===== S4.Def_RP_HattoriStallings_Core =====
section

/-!
# Hattori–Stallings traces over `R[G]` (unit S4-HattoriStallings, part A: core)

A `R[G]`-module is a representation `ρ : Representation R G P` on a free finite `R`-module `P`.
Projectivity over `R[G]` is expressed by Higman's criterion (`IsHigman ρ E`:
`∑ h, ρ h ∘ E ∘ ρ h⁻¹ = id`). The Hattori–Stallings trace of an equivariant `φ` is the class function
`hs ρ φ c = ∑_{g ∈ c} Tr_R (ρ g⁻¹ ∘ φ ∘ E)`; it is independent of `E` and is the vector of class-sum
coordinates of the classical HS trace in `R[G]/[R[G], R[G]]`.
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson.HattoriStallings

open LinearMap

section ClassSum

variable {R : Type*} [CommRing R] {G : Type*} [Group G] [Fintype G]

end ClassSum

section Higman

variable {R : Type*} [CommRing R] {G : Type*} [Group G] [Fintype G]
variable {P : Type*} [AddCommGroup P] [Module R P] {Q : Type*} [AddCommGroup Q] [Module R Q]
variable {T : Type*} [AddCommGroup T] [Module R T]

/-- Higman datum: `∑ h, ρ h ∘ E ∘ ρ h⁻¹ = id`. -/
def IsHigman (ρ : Representation R G P) (E : P →ₗ[R] P) : Prop :=
  ∑ h : G, ρ h ∘ₗ E ∘ₗ ρ h⁻¹ = LinearMap.id

/-- `G`-equivariant linear maps. -/
def IsEquivariant (ρ : Representation R G P) (σ : Representation R G Q) (f : P →ₗ[R] Q) : Prop :=
  ∀ g : G, f ∘ₗ ρ g = σ g ∘ₗ f

variable {ρ : Representation R G P} {σ : Representation R G Q} {τ : Representation R G T}

variable [Module.Free R P] [Module.Finite R P] [Module.Free R Q] [Module.Finite R Q]

end Higman

end RamanujanPetersson.HattoriStallings


end

-- ===== S4.Def_RP_PerfectCx_CxAlg =====
section

/-!
# S4-PD (5), E3 algebra: products, coinvariants of products, and the right regular module

* `repPi`: the pointwise representation on a dependent product; `isProj_prod`, `isProj_pi`;
* `coinvProd`, `coinvPi`: `((P × Q) ⊗ M)_G ≃ (P ⊗ M)_G × (Q ⊗ M)_G` and the same for finite products;
* `rRep`: `Gf` acting on `k[Gf]` by right multiplication by `h⁻¹`; `isProj_rRep`; balancedness `mk_mul_tmul`;
  `coinvA : (k[Gf] ⊗ M)_{Gf} ≃ M`, `⟦a ⊗ m⟧ ↦ a · m`.
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson
namespace PerfectCx

open MonoidAlgebra TensorProduct HattoriStallings Representation

noncomputable section

section Gen

variable {k : Type} [CommRing k] {Gf : Type} [Group Gf]

/-- The pointwise representation on a dependent product. -/
def repPi {ι : Type} {V : ι → Type} [∀ i, AddCommGroup (V i)] [∀ i, Module k (V i)]
    (σ : ∀ i, Representation k Gf (V i)) : Representation k Gf (∀ i, V i) where
  toFun g := LinearMap.piMap fun i => σ i g
  map_one' := by
    refine LinearMap.ext fun f => funext fun i => ?_
    show σ i 1 (f i) = f i
    rw [map_one, Module.End.one_apply]
  map_mul' x y := by
    refine LinearMap.ext fun f => funext fun i => ?_
    show σ i (x * y) (f i) = σ i x (σ i y (f i))
    rw [map_mul, Module.End.mul_apply]

theorem repPi_apply {ι : Type} {V : ι → Type} [∀ i, AddCommGroup (V i)] [∀ i, Module k (V i)]
    (σ : ∀ i, Representation k Gf (V i)) (g : Gf) (f : ∀ i, V i) (i : ι) :
    repPi σ g f i = σ i g (f i) := rfl

variable {M : Type} [AddCommGroup M] [Module k M] (τ : Representation k Gf M)

section Prod

variable {P Q : Type} [AddCommGroup P] [Module k P] [AddCommGroup Q] [Module k Q]
  (ρ : Representation k Gf P) (σ : Representation k Gf Q)

theorem inl_apply' (x : P) : IntertwiningMap.inl k ρ σ x = (x, 0) := rfl

theorem inr_apply' (y : Q) : IntertwiningMap.inr k ρ σ y = (0, y) := rfl

/-- `((P × Q) ⊗ M)_G ≃ (P ⊗ M)_G × (Q ⊗ M)_G`. -/
def coinvProd : Coinvariants ((ρ.prod σ).tprod τ) ≃ₗ[k] Coinvariants (ρ.tprod τ) × Coinvariants (σ.tprod τ) :=
  LinearEquiv.ofLinearMap
    ((Coinvariants.map _ _ ((IntertwiningMap.fst k ρ σ).rTensor τ)).prod
      (Coinvariants.map _ _ ((IntertwiningMap.snd k ρ σ).rTensor τ)))
    ((Coinvariants.map _ _ ((IntertwiningMap.inl k ρ σ).rTensor τ)).coprod
      (Coinvariants.map _ _ ((IntertwiningMap.inr k ρ σ).rTensor τ)))
    (LinearMap.prod_ext
      (Coinvariants.hom_ext (TensorProduct.ext' fun x m => by
        simp only [LinearMap.comp_apply, LinearMap.inl_apply, LinearMap.coprod_apply, map_zero, add_zero,
          LinearMap.prod_apply, Function.prod_apply, Coinvariants.map_mk, IntertwiningMap.rTensor_apply, inl_apply',
          IntertwiningMap.fst_apply, IntertwiningMap.snd_apply, zero_tmul, LinearMap.id_apply]))
      (Coinvariants.hom_ext (TensorProduct.ext' fun x m => by
        simp only [LinearMap.comp_apply, LinearMap.inr_apply, LinearMap.coprod_apply, map_zero, zero_add,
          LinearMap.prod_apply, Function.prod_apply, Coinvariants.map_mk, IntertwiningMap.rTensor_apply, inr_apply',
          IntertwiningMap.fst_apply, IntertwiningMap.snd_apply, zero_tmul, LinearMap.id_apply])))
    (Coinvariants.hom_ext (TensorProduct.ext' fun x m => by
      simp only [LinearMap.comp_apply, LinearMap.coprod_apply, LinearMap.prod_apply, Function.prod_apply, Coinvariants.map_mk,
        IntertwiningMap.rTensor_apply, IntertwiningMap.fst_apply, IntertwiningMap.snd_apply, inl_apply',
        inr_apply', LinearMap.id_apply]
      rw [← map_add, ← add_tmul, Prod.mk_add_mk, add_zero, zero_add]))

theorem coinvProd_mk_tmul (x : P × Q) (m : M) :
    coinvProd τ ρ σ (Coinvariants.mk _ (x ⊗ₜ m)) =
      (Coinvariants.mk _ (x.1 ⊗ₜ m), Coinvariants.mk _ (x.2 ⊗ₜ m)) := rfl

end Prod

section Pi

variable {ι : Type} [Fintype ι] [DecidableEq ι] {V : ι → Type} [∀ i, AddCommGroup (V i)] [∀ i, Module k (V i)]
  (σ : ∀ i, Representation k Gf (V i))

/-- The `i`-th projection as an intertwining map. -/
def projI (i : ι) : IntertwiningMap (repPi σ) (σ i) :=
  ⟨LinearMap.proj i, fun _ => LinearMap.ext fun _ => rfl⟩

/-- The `i`-th inclusion as an intertwining map. -/
def singleI (i : ι) : IntertwiningMap (σ i) (repPi σ) :=
  ⟨LinearMap.single k V i, fun g => LinearMap.ext fun v => funext fun j => by
    by_cases h : j = i
    · subst h
      simp [repPi_apply]
    · simp [repPi_apply, Pi.single_eq_of_ne h]⟩

theorem projI_apply (i : ι) (f : ∀ i, V i) : projI σ i f = f i := rfl

theorem singleI_apply (i : ι) (v : V i) : singleI σ i v = Pi.single i v := rfl

/-- Forward map of `coinvPi`. -/
def piFwd : Coinvariants ((repPi σ).tprod τ) →ₗ[k] ∀ i, Coinvariants ((σ i).tprod τ) :=
  LinearMap.pi fun i => Coinvariants.map _ _ ((projI σ i).rTensor τ)

/-- Inverse map of `coinvPi`. -/
def piInv : (∀ i, Coinvariants ((σ i).tprod τ)) →ₗ[k] Coinvariants ((repPi σ).tprod τ) :=
  ∑ i, Coinvariants.map _ _ ((singleI σ i).rTensor τ) ∘ₗ LinearMap.proj i

theorem piFwd_mk (x : ∀ i, V i) (m : M) (j : ι) :
    piFwd τ σ (Coinvariants.mk _ (x ⊗ₜ m)) j = Coinvariants.mk _ (x j ⊗ₜ m) := rfl

theorem piInv_apply (y : ∀ i, Coinvariants ((σ i).tprod τ)) :
    piInv τ σ y = ∑ i, Coinvariants.map _ _ ((singleI σ i).rTensor τ) (y i) := by
  simp only [piInv, LinearMap.sum_apply, LinearMap.comp_apply, LinearMap.proj_apply]

theorem piInv_single (i : ι) (y : Coinvariants ((σ i).tprod τ)) :
    piInv τ σ (Pi.single i y) = Coinvariants.map _ _ ((singleI σ i).rTensor τ) y := by
  rw [piInv_apply, Finset.sum_eq_single i (fun l _ hl => by rw [Pi.single_eq_of_ne hl, map_zero])
    (fun hi => absurd (Finset.mem_univ i) hi), Pi.single_eq_same]

/-- `((Π_i V_i) ⊗ M)_G ≃ Π_i (V_i ⊗ M)_G` for finite `ι`. -/
def coinvPi : Coinvariants ((repPi σ).tprod τ) ≃ₗ[k] ∀ i, Coinvariants ((σ i).tprod τ) :=
  LinearEquiv.ofLinearMap (piFwd τ σ) (piInv τ σ)
    (LinearMap.pi_ext' fun i => Coinvariants.hom_ext (TensorProduct.ext' fun v m => funext fun j => by
      show piFwd τ σ (piInv τ σ (Pi.single i (Coinvariants.mk _ (v ⊗ₜ m)))) j =
        Pi.single (M := fun i => Coinvariants ((σ i).tprod τ)) i (Coinvariants.mk _ (v ⊗ₜ m)) j
      rw [piInv_single, Coinvariants.map_mk, IntertwiningMap.rTensor_apply, singleI_apply, piFwd_mk]
      by_cases h : j = i
      · subst h
        rw [Pi.single_eq_same, Pi.single_eq_same]
      · rw [Pi.single_eq_of_ne h, Pi.single_eq_of_ne h, zero_tmul, map_zero]))
    (Coinvariants.hom_ext (TensorProduct.ext' fun x m => by
      show piInv τ σ (piFwd τ σ (Coinvariants.mk _ (x ⊗ₜ m))) = Coinvariants.mk _ (x ⊗ₜ m)
      rw [piInv_apply]
      simp only [piFwd_mk, Coinvariants.map_mk, IntertwiningMap.rTensor_apply, singleI_apply]
      rw [← map_sum, ← TensorProduct.sum_tmul, Finset.univ_sum_single]))

theorem coinvPi_mk_tmul (x : ∀ i, V i) (m : M) (i : ι) :
    coinvPi τ σ (Coinvariants.mk _ (x ⊗ₜ m)) i = Coinvariants.mk _ (x i ⊗ₜ m) := rfl

end Pi

end Gen

section Right

variable (k : Type) [CommRing k] (Gf : Type) [Group Gf]

/-- `Gf` acting on `k[Gf]` by right multiplication by `h⁻¹`. -/
def rRep : Representation k Gf (MonoidAlgebra k Gf) where
  toFun h := LinearMap.mulRight k (single h⁻¹ 1)
  map_one' := by
    refine LinearMap.ext fun a => ?_
    show a * single 1⁻¹ 1 = a
    rw [inv_one, ← one_def, mul_one]
  map_mul' x y := by
    refine LinearMap.ext fun a => ?_
    show a * single (x * y)⁻¹ 1 = a * single y⁻¹ 1 * single x⁻¹ 1
    rw [mul_assoc, single_mul_single, mul_inv_rev, one_mul]

variable {k Gf}

theorem rRep_apply (h : Gf) (a : MonoidAlgebra k Gf) : rRep k Gf h a = a * single h⁻¹ 1 := rfl

variable {M : Type} [AddCommGroup M] [Module k M] (τ : Representation k Gf M)

/-- Balancedness: `⟦(b a) ⊗ m⟧ = ⟦b ⊗ (a · m)⟧` in `(k[Gf] ⊗ M)_{Gf}`. -/
theorem mk_mul_tmul (b a : MonoidAlgebra k Gf) (m : M) :
    Coinvariants.mk ((rRep k Gf).tprod τ) ((b * a) ⊗ₜ m) =
      Coinvariants.mk ((rRep k Gf).tprod τ) (b ⊗ₜ τ.asAlgebraHom a m) := by
  induction a using MonoidAlgebra.induction_on with
  | of x =>
    rw [Representation.asAlgebraHom_of, of_apply]
    have hb : b * single x 1 = rRep k Gf x⁻¹ b := by rw [rRep_apply, inv_inv]
    rw [hb, Coinvariants.mk_inv_tmul]
  | add a a' ha ha' => simp only [mul_add, add_tmul, map_add, ha, ha', LinearMap.add_apply, tmul_add]
  | smul r a ha => simp only [mul_smul_comm, ← smul_tmul', map_smul, ha, LinearMap.smul_apply, tmul_smul]

theorem lift_rRep_inv (h : Gf) :
    TensorProduct.lift τ.asAlgebraHom.toLinearMap ∘ₗ ((rRep k Gf).tprod τ) h =
      TensorProduct.lift τ.asAlgebraHom.toLinearMap := by
  refine TensorProduct.ext' fun a m => ?_
  have hinv : τ h⁻¹ (τ h m) = m := by
    rw [← Module.End.mul_apply, ← map_mul, inv_mul_cancel, map_one, Module.End.one_apply]
  rw [LinearMap.comp_apply, Representation.tprod_apply, TensorProduct.map_tmul, TensorProduct.lift.tmul,
    TensorProduct.lift.tmul, AlgHom.toLinearMap_apply, AlgHom.toLinearMap_apply, rRep_apply, map_mul,
    Module.End.mul_apply, Representation.asAlgebraHom_single_one, hinv]

/-- `(k[Gf] ⊗ M)_{Gf} ≃ M`, `⟦a ⊗ m⟧ ↦ a · m`. -/
def coinvA : Coinvariants ((rRep k Gf).tprod τ) ≃ₗ[k] M :=
  LinearEquiv.ofLinearMap
    (Coinvariants.lift _ (TensorProduct.lift τ.asAlgebraHom.toLinearMap) (lift_rRep_inv τ))
    (Coinvariants.mk _ ∘ₗ TensorProduct.mk k (MonoidAlgebra k Gf) M 1)
    (LinearMap.ext fun m => by
      show τ.asAlgebraHom 1 m = m
      rw [map_one, Module.End.one_apply])
    (Coinvariants.hom_ext (TensorProduct.ext' fun a m => by
      show Coinvariants.mk _ ((1 : MonoidAlgebra k Gf) ⊗ₜ τ.asAlgebraHom a m) = Coinvariants.mk _ (a ⊗ₜ m)
      rw [← mk_mul_tmul, one_mul]))

theorem coinvA_symm_apply (m : M) :
    (coinvA τ).symm m = Coinvariants.mk _ ((1 : MonoidAlgebra k Gf) ⊗ₜ m) := rfl

end Right

end

end PerfectCx
end RamanujanPetersson


end

-- ===== S4.Def_RP_PerfectCx_Alg =====
section

/-!
# S4-PD (5), E2 set-up and E2(a): the cocycle module `E = Z¹(Γ; Λ[Gf])` is `Λ`-free

`π : G →* Gf` (open kernel, `Gf` finite), `A = Λ[Gf]` (`MonoidAlgebra`) with `G` acting by left multiplication
through `π` (`regRep`), `E = Z¹(Γ; A)` (locally constant cocycles, `S4-CurveCoh`), and `Gf` acting on `E` by right
multiplication by `h⁻¹` on values (`eRep`; the convention of the `S4-HattoriStallings` coinvariants
`(E ⊗ M)_{Gf} = Coinvariants (tprod eRep τ)`).

* `lift_of_values`: under `H2All`, a cocycle with values in a subrepresentation `W` lifts along any equivariant `q`
  onto `W`;
* `free_E`: over a local `Λ` with `𝔪 = (ϖ)`, `ϖⁿ = 0`, `ϖᵐ ≠ 0` (`m < n`), `E` is free (if finite), via
  `free_of_torsion` and the lift along `ϖ • : A → ϖA`.
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson
namespace PerfectCx

open CurveCoh MonoidAlgebra IsLocalRing

noncomputable section

section Regular

variable (Λ : Type) [CommRing Λ] (Gf : Type) [Group Gf]

/-- `Λ[Gf]` with `Gf` acting by left multiplication. -/
def leftRep : Representation Λ Gf (MonoidAlgebra Λ Gf) where
  toFun x := LinearMap.mulLeft Λ (single x 1)
  map_one' := by
    refine LinearMap.ext fun a => ?_
    show single 1 1 * a = a
    rw [← one_def, one_mul]
  map_mul' x y := by
    refine LinearMap.ext fun a => ?_
    show single (x * y) 1 * a = single x 1 * (single y 1 * a)
    rw [← mul_assoc, single_mul_single, one_mul]

theorem leftRep_apply (x : Gf) (a : MonoidAlgebra Λ Gf) : leftRep Λ Gf x a = single x 1 * a := rfl

theorem finite_A [Finite Λ] [Finite Gf] : Finite (MonoidAlgebra Λ Gf) := by
  haveI : Module.Finite Λ (MonoidAlgebra Λ Gf) := Module.Finite.of_basis (MonoidAlgebra.basis Gf Λ)
  exact Module.finite_of_finite Λ

end Regular

section Lift

variable {k : Type} [CommRing k] {G : Type} [Group G] [TopologicalSpace G] [IsTopologicalGroup G]
  {M : Type} [AddCommGroup M] [Module k M] {N : Type} [AddCommGroup N] [Module k N]
  (ρ : Representation k G M) (σ : Representation k G N) (Γ : Subgroup G)

/-- Under `H2All`, a cocycle with values in a subrepresentation `W` lifts along an equivariant `q` onto `W`. -/
theorem lift_of_values {l n : ℕ} (hall : H2All k G Γ l n) [Finite M] (hM : ∀ m : M, (l ^ n) • m = 0)
    (hρ : IsOpen (ρ.ker : Set G)) (q : M →ₗ[k] N) (hq : ∀ (g : G) (m : M), q (ρ g m) = σ g (q m))
    (W : Subrepresentation σ) (hqW : ∀ m, q m ∈ W.toSubmodule)
    (hsurj : ∀ w ∈ W.toSubmodule, ∃ m, q m = w)
    (z : Z1 σ Γ) (hz : ∀ g, (z : Γ → N) g ∈ W.toSubmodule) :
    ∃ c : Z1 ρ Γ, ∀ g, q ((c : Γ → M) g) = (z : Γ → N) g := by
  let q' : M →ₗ[k] W.toSubmodule := q.codRestrict W.toSubmodule hqW
  have hq' : ∀ (g : G) (m : M), q' (ρ g m) = W.toRepresentation g (q' m) := fun g m => Subtype.ext (hq g m)
  have hs' : Function.Surjective q' := fun w => by
    obtain ⟨m, hm⟩ := hsurj w w.2
    exact ⟨m, Subtype.ext hm⟩
  obtain ⟨hlc, hco⟩ := (mem_Z1 σ Γ _).1 z.2
  have hzW : (fun g => (⟨(z : Γ → N) g, hz g⟩ : W.toSubmodule)) ∈ Z1 W.toRepresentation Γ := by
    refine (mem_Z1 _ Γ _).2 ⟨IsLocallyConstant.desc _ Subtype.val hlc Subtype.val_injective,
      fun g h => Subtype.ext ?_⟩
    simpa [toRep_val] using hco g h
  obtain ⟨c, hc⟩ := z1Map_surjective_of_all ρ W.toRepresentation Γ hall hM hρ q' hq' hs' ⟨_, hzW⟩
  refine ⟨c, fun g => ?_⟩
  have := congrArg (fun z : Z1 W.toRepresentation Γ => (((z : Γ → W.toSubmodule) g : W.toSubmodule) : N)) hc
  exact this

theorem nsmul_eq_zero_of_cast {l n : ℕ} (hk : ((l ^ n : ℕ) : k) = 0) (m : M) : (l ^ n) • m = 0 := by
  rw [← Nat.cast_smul_eq_nsmul k, hk, zero_smul]

end Lift

section Cocycles

variable {Λ : Type} [CommRing Λ] {Gf : Type} [Group Gf] {G : Type} [Group G] [TopologicalSpace G]
  [IsTopologicalGroup G] (π : G →* Gf) (Γ : Subgroup G)

variable (Λ) in
/-- `G` acting on `Λ[Gf]` by left multiplication through `π`. -/
def regRep : Representation Λ G (MonoidAlgebra Λ Gf) := (leftRep Λ Gf).comp π

theorem regRep_apply (g : G) (a : MonoidAlgebra Λ Gf) : regRep Λ π g a = single (π g) 1 * a := rfl

theorem isOpen_regRep_ker (hπ : IsOpen (π.ker : Set G)) : IsOpen ((regRep Λ π).ker : Set G) := by
  refine Subgroup.isOpen_mono (fun g hg => ?_) hπ
  rw [MonoidHom.mem_ker] at hg ⊢
  show (leftRep Λ Gf) (π g) = 1
  rw [hg, map_one]

theorem mulRight_regRep (b : MonoidAlgebra Λ Gf) (g : G) (a : MonoidAlgebra Λ Gf) :
    LinearMap.mulRight Λ b (regRep Λ π g a) = regRep Λ π g (LinearMap.mulRight Λ b a) := by
  show single (π g) 1 * a * b = single (π g) 1 * (a * b)
  rw [mul_assoc]

/-- Right multiplication on cocycle values (the right `Λ[Gf]`-module structure of `E`). -/
def eMul (b : MonoidAlgebra Λ Gf) : Z1 (regRep Λ π) Γ →ₗ[Λ] Z1 (regRep Λ π) Γ :=
  z1Map (regRep Λ π) (regRep Λ π) Γ (LinearMap.mulRight Λ b) (mulRight_regRep π b)

theorem eMul_apply (b : MonoidAlgebra Λ Gf) (c : Z1 (regRep Λ π) Γ) (g : Γ) :
    (eMul π Γ b c : Γ → MonoidAlgebra Λ Gf) g = (c : Γ → MonoidAlgebra Λ Gf) g * b := rfl

/-- `Gf` acting on `E = Z¹(Γ; Λ[Gf])` by right multiplication by `h⁻¹` on values. -/
def eRep : Representation Λ Gf (Z1 (regRep Λ π) Γ) where
  toFun h := eMul π Γ (single h⁻¹ 1)
  map_one' := by
    refine LinearMap.ext fun c => Subtype.ext (funext fun g => ?_)
    show (c : Γ → MonoidAlgebra Λ Gf) g * single 1⁻¹ 1 = (c : Γ → MonoidAlgebra Λ Gf) g
    rw [inv_one, ← one_def, mul_one]
  map_mul' x y := by
    refine LinearMap.ext fun c => Subtype.ext (funext fun g => ?_)
    show (c : Γ → MonoidAlgebra Λ Gf) g * single (x * y)⁻¹ 1 =
      (c : Γ → MonoidAlgebra Λ Gf) g * single y⁻¹ 1 * single x⁻¹ 1
    rw [mul_assoc, single_mul_single, mul_inv_rev, one_mul]

theorem eRep_apply (h : Gf) (c : Z1 (regRep Λ π) Γ) (g : Γ) :
    (eRep π Γ h c : Γ → MonoidAlgebra Λ Gf) g = (c : Γ → MonoidAlgebra Λ Gf) g * single h⁻¹ 1 := rfl

end Cocycles

end

end PerfectCx
end RamanujanPetersson


end

-- ===== S4.Def_RP_PerfectCx_Tensor =====
section

/-!
# S4-PD (5), E2(c) part 1: the evaluation map `(E ⊗ M)_{Gf} → Z¹(Γ; M)`

For `τ : Representation Λ Gf M` and `E = Z¹(Γ; Λ[Gf])`, `Phi : Coinvariants (tprod eRep τ) → Z¹(Γ; M)`,
`⟦c ⊗ m⟧ ↦ (g ↦ c(g) · m)` (`a · m = asAlgebraHom τ a m`), and the balancedness
`⟦(c · a) ⊗ m⟧ = ⟦c ⊗ (a · m)⟧` (`mk_eMul_tmul`).
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson
namespace PerfectCx

open CurveCoh MonoidAlgebra TensorProduct

noncomputable section

variable {Λ : Type} [CommRing Λ] {Gf : Type} [Group Gf] {G : Type} [Group G] [TopologicalSpace G]
  [IsTopologicalGroup G] (π : G →* Gf) (Γ : Subgroup G)
  {M : Type} [AddCommGroup M] [Module Λ M] (τ : Representation Λ Gf M)

theorem act_single_mul (x : Gf) (a : MonoidAlgebra Λ Gf) (m : M) :
    τ.asAlgebraHom (single x 1 * a) m = τ x (τ.asAlgebraHom a m) := by
  rw [map_mul, Module.End.mul_apply, Representation.asAlgebraHom_single_one]

/-- `c ↦ (g ↦ c(g) · m)`. -/
def evalZ1 (m : M) : Z1 (regRep Λ π) Γ →ₗ[Λ] Z1 (τ.comp π) Γ :=
  z1Map (regRep Λ π) (τ.comp π) Γ ((LinearMap.applyₗ m).comp τ.asAlgebraHom.toLinearMap)
    (fun g a => act_single_mul τ (π g) a m)

theorem evalZ1_apply (m : M) (c : Z1 (regRep Λ π) Γ) (g : Γ) :
    (evalZ1 π Γ τ m c : Γ → M) g = τ.asAlgebraHom ((c : Γ → MonoidAlgebra Λ Gf) g) m := rfl

/-- `c ⊗ m ↦ (g ↦ c(g) · m)` on `E ⊗[Λ] M`. -/
def phi0 : Z1 (regRep Λ π) Γ ⊗[Λ] M →ₗ[Λ] Z1 (τ.comp π) Γ :=
  TensorProduct.lift (LinearMap.mk₂ Λ (fun c m => evalZ1 π Γ τ m c)
    (fun c c' m => map_add _ c c') (fun r c m => map_smul _ r c)
    (fun c m m' => Subtype.ext (funext fun g =>
      map_add (τ.asAlgebraHom ((c : Γ → MonoidAlgebra Λ Gf) g)) m m'))
    (fun r c m => Subtype.ext (funext fun g =>
      map_smul (τ.asAlgebraHom ((c : Γ → MonoidAlgebra Λ Gf) g)) r m)))

theorem phi0_tmul (c : Z1 (regRep Λ π) Γ) (m : M) (g : Γ) :
    (phi0 π Γ τ (c ⊗ₜ m) : Γ → M) g = τ.asAlgebraHom ((c : Γ → MonoidAlgebra Λ Gf) g) m := rfl

theorem phi0_inv (h : Gf) : phi0 π Γ τ ∘ₗ ((eRep π Γ).tprod τ) h = phi0 π Γ τ := by
  refine TensorProduct.ext' fun c m => Subtype.ext (funext fun g => ?_)
  rw [LinearMap.comp_apply, Representation.tprod_apply, TensorProduct.map_tmul, phi0_tmul, phi0_tmul,
    eRep_apply, map_mul, Module.End.mul_apply, Representation.asAlgebraHom_single_one]
  have hinv : τ h⁻¹ (τ h m) = m := by
    rw [← Module.End.mul_apply, ← map_mul, inv_mul_cancel, map_one, Module.End.one_apply]
  rw [hinv]

/-- The left factor `E` is a submodule: its `AddCommMonoid` is not syntactically `AddCommGroup.toAddCommMonoid`. -/
instance instAddCommGroupTensorE : AddCommGroup (Z1 (regRep Λ π) Γ ⊗[Λ] M) := TensorProduct.addCommGroup

/-- **E2(c) map**: `Phi : (E ⊗ M)_{Gf} → Z¹(Γ; M)`, `⟦c ⊗ m⟧ ↦ (g ↦ c(g) · m)`. -/
def Phi : Representation.Coinvariants ((eRep (Λ := Λ) π Γ).tprod τ) →ₗ[Λ] Z1 (τ.comp π) Γ :=
  Representation.Coinvariants.lift _ (phi0 π Γ τ) (phi0_inv π Γ τ)

theorem Phi_mk_tmul (c : Z1 (regRep Λ π) Γ) (m : M) (g : Γ) :
    (Phi π Γ τ (Representation.Coinvariants.mk _ (c ⊗ₜ m)) : Γ → M) g =
      τ.asAlgebraHom ((c : Γ → MonoidAlgebra Λ Gf) g) m := rfl

theorem eMul_add (a b : MonoidAlgebra Λ Gf) (D : Z1 (regRep Λ π) Γ) :
    eMul π Γ (a + b) D = eMul π Γ a D + eMul π Γ b D :=
  Subtype.ext (funext fun g => mul_add ((D : Γ → MonoidAlgebra Λ Gf) g) a b)

theorem eMul_smul (r : Λ) (a : MonoidAlgebra Λ Gf) (D : Z1 (regRep Λ π) Γ) :
    eMul π Γ (r • a) D = r • eMul π Γ a D :=
  Subtype.ext (funext fun g => mul_smul_comm r ((D : Γ → MonoidAlgebra Λ Gf) g) a)

/-- Balancedness: `⟦(c · a) ⊗ m⟧ = ⟦c ⊗ (a · m)⟧` in `(E ⊗ M)_{Gf}`. -/
theorem mk_eMul_tmul (a : MonoidAlgebra Λ Gf) (D : Z1 (regRep Λ π) Γ) (m : M) :
    Representation.Coinvariants.mk ((eRep (Λ := Λ) π Γ).tprod τ) (eMul π Γ a D ⊗ₜ m) =
      Representation.Coinvariants.mk ((eRep (Λ := Λ) π Γ).tprod τ) (D ⊗ₜ τ.asAlgebraHom a m) := by
  induction a using MonoidAlgebra.induction_on with
  | of x =>
    have h1 : eMul π Γ (of Λ Gf x) D = eRep π Γ x⁻¹ D := by
      refine Subtype.ext (funext fun g => ?_)
      rw [eMul_apply, eRep_apply, inv_inv, of_apply]
    have hinv : τ x⁻¹ (τ x m) = m := by
      rw [← Module.End.mul_apply, ← map_mul, inv_mul_cancel, map_one, Module.End.one_apply]
    rw [h1, Representation.asAlgebraHom_of]
    refine (Representation.Coinvariants.mk_eq_iff _).2
      (Representation.Coinvariants.mem_ker_of_eq x⁻¹ (D ⊗ₜ τ x m) _ ?_)
    rw [Representation.tprod_apply, TensorProduct.map_tmul, hinv]
  | add a b ha hb =>
    simp only [eMul_add, add_tmul, map_add, ha, hb, LinearMap.add_apply, tmul_add]
  | smul r a ha =>
    simp only [eMul_smul, ← smul_tmul', map_smul, ha, LinearMap.smul_apply, tmul_smul]

end

end PerfectCx
end RamanujanPetersson


end

-- ===== S4.Def_RP_PerfectCx_TensorIso =====
section

/-!
# S4-PD (5), E2(c) part 2: `(E ⊗ M)_{Gf} ≃ Z¹(Γ; M)`

Under `H2All` (exactness of `Z¹(Γ; -)` on finite `lᴺ`-torsion modules), the evaluation map `Phi` of part 1 is
bijective (`tensorEquiv`) and natural in `M` (`Phi_natural`).
* surjective: lift a cocycle along `qMap : (M → Λ[Gf]) → M`, `(a_m) ↦ Σ_m a_m · m`;
* injective: a family `(c_m)` killed by `Phi` assembles to a cocycle with values in `K = ker qMap`; it lifts along
  `combMap : (K → Λ[Gf]) → K`, `(d_k) ↦ Σ_k d_k k`, and balancedness (`mk_eMul_tmul`) kills `⟦Σ_m c_m ⊗ m⟧`.
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson
namespace PerfectCx

open CurveCoh MonoidAlgebra TensorProduct

noncomputable section

variable {Λ : Type} [CommRing Λ] {Gf : Type} [Group Gf] {G : Type} [Group G] [TopologicalSpace G]
  [IsTopologicalGroup G] (π : G →* Gf) (Γ : Subgroup G)

section Pi

variable (ι : Type)

variable (Λ) in
/-- `G` acting on `ι → Λ[Gf]` by left multiplication through `π` in each coordinate. -/
def piRep : Representation Λ G (ι → MonoidAlgebra Λ Gf) where
  toFun g := LinearMap.pi fun i =>
    (regRep Λ π g).comp (LinearMap.proj i : (ι → MonoidAlgebra Λ Gf) →ₗ[Λ] MonoidAlgebra Λ Gf)
  map_one' := by
    refine LinearMap.ext fun f => funext fun i => ?_
    show regRep Λ π 1 (f i) = f i
    rw [map_one]
    rfl
  map_mul' x y := by
    refine LinearMap.ext fun f => funext fun i => ?_
    show regRep Λ π (x * y) (f i) = regRep Λ π x (regRep Λ π y (f i))
    rw [map_mul]
    rfl

theorem piRep_apply (g : G) (f : ι → MonoidAlgebra Λ Gf) (i : ι) :
    piRep Λ π ι g f i = regRep Λ π g (f i) := rfl

theorem isOpen_piRep_ker (hπ : IsOpen (π.ker : Set G)) : IsOpen ((piRep Λ π ι).ker : Set G) := by
  refine Subgroup.isOpen_mono (fun g hg => ?_) hπ
  rw [MonoidHom.mem_ker] at hg ⊢
  refine LinearMap.ext fun f => funext fun i => ?_
  show single (π g) 1 * f i = f i
  rw [hg, ← one_def, one_mul]

/-- The `i`-th coordinate of a cocycle with values in `ι → Λ[Gf]`. -/
def projZ1 (i : ι) : Z1 (piRep Λ π ι) Γ →ₗ[Λ] Z1 (regRep Λ π) Γ :=
  z1Map (piRep Λ π ι) (regRep Λ π) Γ
    (LinearMap.proj i : (ι → MonoidAlgebra Λ Gf) →ₗ[Λ] MonoidAlgebra Λ Gf) (fun _ _ => rfl)

theorem projZ1_apply (i : ι) (c : Z1 (piRep Λ π ι) Γ) (g : Γ) :
    (projZ1 π Γ ι i c : Γ → MonoidAlgebra Λ Gf) g = (c : Γ → ι → MonoidAlgebra Λ Gf) g i := rfl

theorem single_regRep [DecidableEq ι] (i : ι) (g : G) (a : MonoidAlgebra Λ Gf) :
    LinearMap.single Λ (fun _ : ι => MonoidAlgebra Λ Gf) i (regRep Λ π g a) =
      piRep Λ π ι g (LinearMap.single Λ (fun _ : ι => MonoidAlgebra Λ Gf) i a) := by
  refine funext fun j => ?_
  rw [piRep_apply, LinearMap.single_apply, LinearMap.single_apply]
  by_cases h : j = i
  · subst h
    rw [Pi.single_eq_same, Pi.single_eq_same]
  · rw [Pi.single_eq_of_ne h, Pi.single_eq_of_ne h, map_zero]

/-- `c ↦ (g ↦ Pi.single i (c g))` on cocycles. -/
def singleZ1 [DecidableEq ι] (i : ι) : Z1 (regRep Λ π) Γ →ₗ[Λ] Z1 (piRep Λ π ι) Γ :=
  z1Map (regRep Λ π) (piRep Λ π ι) Γ (LinearMap.single Λ (fun _ : ι => MonoidAlgebra Λ Gf) i)
    (single_regRep π ι i)

/-- The cocycle `g ↦ (c_i g)_i` assembled from a finite family of cocycles. -/
def assemble [Fintype ι] [DecidableEq ι] (c : ι → Z1 (regRep Λ π) Γ) : Z1 (piRep Λ π ι) Γ :=
  ∑ i, singleZ1 π Γ ι i (c i)

theorem assemble_apply [Fintype ι] [DecidableEq ι] (c : ι → Z1 (regRep Λ π) Γ) (g : Γ) (i : ι) :
    (assemble π Γ ι c : Γ → ι → MonoidAlgebra Λ Gf) g i = (c i : Γ → MonoidAlgebra Λ Gf) g := by
  rw [assemble, Submodule.coe_sum, Finset.sum_apply, Finset.sum_apply]
  exact (Finset.sum_pi_single i (fun j => (c j : Γ → MonoidAlgebra Λ Gf) g) Finset.univ).trans
    (if_pos (Finset.mem_univ i))

end Pi

section QMap

variable {M : Type} [AddCommGroup M] [Module Λ M] (τ : Representation Λ Gf M)

/-- `(a_m)_m ↦ Σ_m a_m · m`. -/
def qMap [Fintype M] : (M → MonoidAlgebra Λ Gf) →ₗ[Λ] M :=
  ∑ m : M, ((LinearMap.applyₗ m).comp τ.asAlgebraHom.toLinearMap).comp
    (LinearMap.proj m : (M → MonoidAlgebra Λ Gf) →ₗ[Λ] MonoidAlgebra Λ Gf)

theorem qMap_apply [Fintype M] (f : M → MonoidAlgebra Λ Gf) :
    qMap τ f = ∑ m : M, τ.asAlgebraHom (f m) m := by
  rw [qMap, LinearMap.sum_apply]
  rfl

theorem qMap_equiv [Fintype M] (g : G) (f : M → MonoidAlgebra Λ Gf) :
    qMap τ (piRep Λ π M g f) = (τ.comp π) g (qMap τ f) := by
  rw [qMap_apply, qMap_apply, map_sum]
  exact Finset.sum_congr rfl fun m _ => act_single_mul τ (π g) (f m) m

theorem qMap_single [Fintype M] [DecidableEq M] (m : M) : qMap τ (Pi.single m 1) = m := by
  rw [qMap_apply, Fintype.sum_eq_single m fun m' hm' => by
    rw [Pi.single_eq_of_ne hm', map_zero, LinearMap.zero_apply], Pi.single_eq_same, map_one,
    Module.End.one_apply]

/-- `K = ker qMap`, a subrepresentation of `M → Λ[Gf]`. -/
def qKer [Fintype M] : Subrepresentation (piRep Λ π M) :=
  kerRep (piRep Λ π M) (τ.comp π) (qMap τ) (qMap_equiv π τ)

theorem mem_qKer [Fintype M] (f : M → MonoidAlgebra Λ Gf) : f ∈ (qKer π τ).toSubmodule ↔ qMap τ f = 0 :=
  LinearMap.mem_ker

end QMap

section Comb

variable {ι ι' : Type} [Fintype ι]

/-- `(d_i)_i ↦ Σ_i d_i v_i` (left multiplication in each coordinate). -/
def combMap (v : ι → ι' → MonoidAlgebra Λ Gf) :
    (ι → MonoidAlgebra Λ Gf) →ₗ[Λ] (ι' → MonoidAlgebra Λ Gf) :=
  LinearMap.pi fun j => ∑ i, (LinearMap.mulRight Λ (v i j)).comp
    (LinearMap.proj i : (ι → MonoidAlgebra Λ Gf) →ₗ[Λ] MonoidAlgebra Λ Gf)

theorem combMap_apply (v : ι → ι' → MonoidAlgebra Λ Gf) (d : ι → MonoidAlgebra Λ Gf) (j : ι') :
    combMap v d j = ∑ i, d i * v i j := by
  rw [combMap, LinearMap.pi_apply, LinearMap.sum_apply]
  rfl

theorem combMap_equiv (v : ι → ι' → MonoidAlgebra Λ Gf) (g : G) (d : ι → MonoidAlgebra Λ Gf) :
    combMap v (piRep Λ π ι g d) = piRep Λ π ι' g (combMap v d) := by
  refine funext fun j => ?_
  rw [combMap_apply, piRep_apply, combMap_apply, regRep_apply, Finset.mul_sum]
  refine Finset.sum_congr rfl fun i _ => ?_
  rw [piRep_apply, regRep_apply, mul_assoc]

theorem combMap_single [DecidableEq ι] (v : ι → ι' → MonoidAlgebra Λ Gf) (i₀ : ι) :
    combMap v (Pi.single i₀ 1) = v i₀ := by
  refine funext fun j => ?_
  rw [combMap_apply, Fintype.sum_eq_single i₀ fun i hi => by rw [Pi.single_eq_of_ne hi, zero_mul],
    Pi.single_eq_same, one_mul]

theorem qMap_combMap {M : Type} [AddCommGroup M] [Module Λ M] (τ : Representation Λ Gf M) [Fintype M]
    (v : ι → M → MonoidAlgebra Λ Gf) (d : ι → MonoidAlgebra Λ Gf) :
    qMap τ (combMap v d) = ∑ i, τ.asAlgebraHom (d i) (qMap τ (v i)) := by
  simp only [qMap_apply, combMap_apply, map_sum, LinearMap.sum_apply, map_mul, Module.End.mul_apply]
  exact Finset.sum_comm

end Comb

section Iso

variable {M : Type} [AddCommGroup M] [Module Λ M] (τ : Representation Λ Gf M)

variable (Λ M) in
/-- `(c_m)_m ↦ Σ_m c_m ⊗ m`. -/
def Theta [Fintype M] : (M → Z1 (regRep Λ π) Γ) →ₗ[Λ] Z1 (regRep Λ π) Γ ⊗[Λ] M :=
  ∑ m : M, (TensorProduct.mk Λ (Z1 (regRep Λ π) Γ) M).flip m ∘ₗ
    (LinearMap.proj m : (M → Z1 (regRep Λ π) Γ) →ₗ[Λ] Z1 (regRep Λ π) Γ)

theorem Theta_apply [Fintype M] (c : M → Z1 (regRep Λ π) Γ) : Theta Λ π Γ M c = ∑ m : M, c m ⊗ₜ m := by
  rw [Theta, LinearMap.sum_apply]
  rfl

theorem Theta_surjective [Fintype M] [DecidableEq M] : Function.Surjective (Theta Λ π Γ M) := by
  intro x
  induction x using TensorProduct.induction_on with
  | zero => exact ⟨0, map_zero _⟩
  | tmul e m =>
    refine ⟨Pi.single m e, ?_⟩
    rw [Theta_apply, Fintype.sum_eq_single m fun m' hm' => by rw [Pi.single_eq_of_ne hm', zero_tmul],
      Pi.single_eq_same]
  | add x y hx hy =>
    obtain ⟨c, hc⟩ := hx
    obtain ⟨d, hd⟩ := hy
    exact ⟨c + d, by rw [map_add, hc, hd]⟩

theorem Phi_mk_Theta [Fintype M] (c : M → Z1 (regRep Λ π) Γ) (g : Γ) :
    (Phi π Γ τ (Representation.Coinvariants.mk _ (Theta Λ π Γ M c)) : Γ → M) g =
      qMap τ (fun m => (c m : Γ → MonoidAlgebra Λ Gf) g) := by
  rw [Theta_apply, map_sum, map_sum, Submodule.coe_sum, Finset.sum_apply, qMap_apply]
  rfl

theorem mk_sum_tmul [Fintype M] (D : Z1 (regRep Λ π) Γ) (f : M → MonoidAlgebra Λ Gf) :
    ∑ m : M, Representation.Coinvariants.mk ((eRep (Λ := Λ) π Γ).tprod τ) (D ⊗ₜ τ.asAlgebraHom (f m) m) =
      Representation.Coinvariants.mk ((eRep (Λ := Λ) π Γ).tprod τ) (D ⊗ₜ qMap τ f) := by
  rw [qMap_apply, tmul_sum, map_sum]

/-- **E2(c), surjectivity**: every cocycle `Γ → M` is `Phi` of a coinvariant class. -/
theorem Phi_surjective [Finite Λ] [Finite Gf] [Finite M] {l N : ℕ} (hΛ : ((l ^ N : ℕ) : Λ) = 0)
    (hall : H2All Λ G Γ l N) (hπ : IsOpen (π.ker : Set G)) : Function.Surjective (Phi π Γ τ) := by
  classical
  haveI := Fintype.ofFinite M
  have := finite_A Λ Gf
  intro z
  obtain ⟨C, hC⟩ := z1Map_surjective_of_all (piRep Λ π M) (τ.comp π) Γ hall (nsmul_eq_zero_of_cast hΛ)
    (isOpen_piRep_ker π M hπ) (qMap τ) (qMap_equiv π τ) (fun m => ⟨Pi.single m 1, qMap_single τ m⟩) z
  refine ⟨Representation.Coinvariants.mk _ (Theta Λ π Γ M fun m => projZ1 π Γ M m C),
    Subtype.ext (funext fun g => ?_)⟩
  rw [Phi_mk_Theta, ← hC]
  rfl

end Iso

end

end PerfectCx
end RamanujanPetersson


end

-- ===== S4.Def_RP_PerfectCx_Cx =====
section

/-!
# S4-PD (5), E3: the cone complex and its free `Λ[Gf]` model

For a representation `ρ` of `G` with open kernel, `Γ ≤ G` and boundary subgroups `I : S → Subgroup G`, the cone
complex `K(M) : M → Z¹(Γ; M) × (S → M) → Π_s Z¹(Γ ⊓ I s; M)` (`cx0`, `cx1`; `cx1_comp_cx0`), natural in the
coefficients (`cx0_natural`, `cx1_natural`). At `ρ = regRep Λ π` (`A = Λ[Gf]`) the right `Gf`-actions are the
naturality maps of right multiplication, so `d0 = cx0`, `d1 = cx1` are `Gf`-equivariant (`d0_equiv`, `d1_equiv`) and
the terms `A`, `E_Γ × A^S`, `Π_s E_s` are projective once the `E`'s are (`isProj_rho1`, `isProj_rho2`).
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson
namespace PerfectCx

open CurveCoh MonoidAlgebra HattoriStallings

noncomputable section

section Generic

variable {k : Type} [CommRing k] {G : Type} [Group G] [TopologicalSpace G] [IsTopologicalGroup G]
  {M : Type} [AddCommGroup M] [Module k M] {N : Type} [AddCommGroup N] [Module k N]
  (ρ : Representation k G M) (σ : Representation k G N) (Γ : Subgroup G) {S : Type} (I : S → Subgroup G)

/-- The coboundary `m ↦ (g ↦ ρ g m - m)` as a locally constant cocycle on `Γ'`. -/
def cob (hρ : IsOpen (ρ.ker : Set G)) (Γ' : Subgroup G) : M →ₗ[k] Z1 ρ Γ' where
  toFun m := ⟨fun g => ρ g m - m, (mem_Z1 ρ Γ' _).2 ⟨(lcRep_of_isOpen ρ Γ' hρ m).sub (IsLocallyConstant.const m),
    fun g h => by
      simp only [Subgroup.coe_mul, map_mul, Module.End.mul_apply, map_sub]
      abel⟩⟩
  map_add' m m' := Subtype.ext (funext fun g => by
    show ρ g (m + m') - (m + m') = (ρ g m - m) + (ρ g m' - m')
    rw [map_add]
    abel)
  map_smul' r m := Subtype.ext (funext fun g => by
    show ρ g (r • m) - r • m = r • (ρ g m - m)
    rw [map_smul, smul_sub])

theorem cob_apply (hρ : IsOpen (ρ.ker : Set G)) (Γ' : Subgroup G) (m : M) (g : Γ') :
    (cob ρ hρ Γ' m : Γ' → M) g = ρ g m - m := rfl

variable (hρ : IsOpen (ρ.ker : Set G)) (hσ : IsOpen (σ.ker : Set G))

variable (S) in
/-- `d⁰ m = (dm, (m)_s)`. -/
def cx0 : M →ₗ[k] Z1 ρ Γ × (S → M) := (cob ρ hρ Γ).prod (LinearMap.pi fun _ => LinearMap.id)

theorem cx0_apply (m : M) : cx0 ρ Γ S hρ m = (cob ρ hρ Γ m, fun _ => m) := rfl

variable (q : M →ₗ[k] N) (hq : ∀ (g : G) (m : M), q (ρ g m) = σ g (q m))

end Generic

section Model

variable {Λ : Type} [CommRing Λ] {Gf : Type} [Group Gf] {G : Type} [Group G] [TopologicalSpace G]
  [IsTopologicalGroup G] (π : G →* Gf) (Γ : Subgroup G) {S : Type} (I : S → Subgroup G)
  (hπ : IsOpen (π.ker : Set G))

end Model

end

end PerfectCx
end RamanujanPetersson


end

-- ===== S4.Def_RP_PerfectCx_Frob =====
section

/-!
# S4-PD (5), E3: the Frobenius chain map on the cone complex

For `x ∈ G` with `x⁻¹ Δ x ⊆ Δ'`, `conjMap ρ x : Z¹(Δ'; M) → Z¹(Δ; M)`, `c ↦ (g ↦ ρ x (c (x⁻¹ g x)))`. For a Frobenius
lift `ψ` normalising `Γ`, a permutation datum `t : S → S`, `h : S → Γ` compatible with the boundary
(`CurveCoh.BdryCompat`), the maps `ρ ψ` (degree 0), `frob1` (degree 1, the `twistc` of `CurveCoh_Pair`) and `frob2`
(degree 2, `e ↦ (s ↦ conjMap (ψ h_s) (e (t s)))`) form a chain endomorphism of the cone complex `K(M)` (`cx0_frob`,
`cx1_frob`), natural in the coefficients (`frob1_natural`, `frob2_natural`). At `ρ = regRep Λ π` the three maps are
`Gf`-equivariant (`frob0_equiv`, `frob1_equiv`, `frob2_equiv`). `triMap` assembles endomorphisms of a `Tri` family.
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson
namespace PerfectCx

open CurveCoh MonoidAlgebra HattoriStallings

noncomputable section

section Conj

variable {k : Type} [CommRing k] {G : Type} [Group G] [TopologicalSpace G] [IsTopologicalGroup G]
  {M : Type} [AddCommGroup M] [Module k M] {N : Type} [AddCommGroup N] [Module k N]
  (ρ : Representation k G M) (σ : Representation k G N)

/-- `g ↦ x⁻¹ g x` from `Δ` to `Δ'` when `x⁻¹ Δ x ⊆ Δ'`. -/
def conjSub (x : G) {Δ Δ' : Subgroup G} (hx : ∀ g ∈ Δ, x⁻¹ * g * x ∈ Δ') (g : Δ) : Δ' :=
  ⟨x⁻¹ * g * x, hx g g.2⟩

end Conj

section Frob

variable {k : Type} [CommRing k] {G : Type} [Group G] [TopologicalSpace G] [IsTopologicalGroup G]
  {M : Type} [AddCommGroup M] [Module k M] {N : Type} [AddCommGroup N] [Module k N]
  (ρ : Representation k G M) (σ : Representation k G N)
  (Γ : Subgroup G) [hΓ : Γ.Normal] {S : Type} (I : S → Subgroup G) (ψ : G) (t : S → S) (h : S → Γ)

variable (hρ : IsOpen (ρ.ker : Set G))

end Frob

section Model

variable {Λ : Type} [CommRing Λ] {Gf : Type} [Group Gf] {G : Type} [Group G] [TopologicalSpace G]
  [IsTopologicalGroup G] (π : G →* Gf) (Γ : Subgroup G) [Γ.Normal] {S : Type} (I : S → Subgroup G)
  (ψ : G) (t : S → S) (h : S → Γ)

end Model

section TriMap

variable {R : Type} [CommRing R] {G : Type} [Group G] {V0 V1 V2 : Type} [AddCommGroup V0] [AddCommGroup V1]
  [AddCommGroup V2] [Module R V0] [Module R V1] [Module R V2]

end TriMap

end

end PerfectCx
end RamanujanPetersson


end

-- ===== S4.Def_RP_TameInertia_Newton =====
section

/-!
# Tame inertia, part Newton: the Abhyankar trinomial has exactly one small root (S4-PD item (2), T6)

For a valuation `v : L → ℤᵐ⁰` and `F` with `1 < v F` (a pole), every root `w` of `X^(p+1) - F X + 1` has
`log v w = -log v F` (small root) or `p · log v w = log v F` (big root) (`trin_val_cases`, three-term
ultrametric). If the trinomial splits, the product of the roots is `±1`, so the logs sum to `0` and exactly one
root is small (`trin_existsUnique_small`).
-/

set_option autoImplicit false

open Polynomial

namespace RamanujanPetersson
namespace TameInertia

noncomputable section

section Trin

variable {L : Type*} [Field L]

/-- The Abhyankar trinomial `X^(p+1) - F X + 1`. -/
def trin (p : ℕ) (F : L) : L[X] := X ^ (p + 1) - C F * X + 1

end Trin

end

end TameInertia
end RamanujanPetersson


end

-- ===== S4.Def_RP_CdOne_Emb =====
section

/-!
# S4-PD (3b): the central embedding problem with kernel `μ_l`

Let `E` be a C1 field containing a primitive `l`-th root of unity `ζ`, and `L/E` a finite Galois `l`-extension.
For a 2-cocycle `f : Gal(L/E)² → ZMod l` (trivial action), `Br(L/E) = 0` (`br_eq_zero`) gives `β : Gal(L/E) → Lˣ`
with `dβ = ζ^f`, and Hilbert 90 gives `b ∈ Lˣ` with `σ b / b = β(σ)^l` (`exists_kummer_data`). For any extension
`Ω ⊇ L` of `E` containing an `l`-th root `y` of `a·b` (`a ∈ Eˣ` free, used later to remove ramification), the
inflation of `f` to `Gal(Ω/E)` is the coboundary of `γ(σ) = log_ζ (β(σ|L) y / σ y)` (`emb_coboundary`), and `γ(σ)`
only depends on `σ|L` and `σ y`. `emb_solve` packages both steps.
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson.CdOne

open groupCohomology IntermediateField RamanujanPetersson.Tsen

section Kummer

variable {E : Type*} [Field E]

variable {L : Type*} [Field L] [Algebra E L]

end Kummer

section Emb

variable {E Ω : Type*} [Field E] [Field Ω] [Algebra E Ω]

set_option synthInstance.maxHeartbeats 400000 in
/-- Step (ii): an `l`-th root `y` of `a·b` in `Ω` kills the inflation of `f`. -/
theorem emb_coboundary (L : IntermediateField E Ω) [Normal E L] {l : ℕ} [Fact l.Prime] {ζ : E}
    (hζ : IsPrimitiveRoot ζ l) (hζ0 : ζ ≠ 0) (f : Gal(L/E) × Gal(L/E) → ZMod l)
    (β : Gal(L/E) → Lˣ) (b : Lˣ)
    (hβ : ∀ σ τ, σ • β τ / β (σ * τ) * β σ = unitOf L ζ hζ0 ^ (f (σ, τ)).val)
    (hb : ∀ σ, σ • b / b = β σ ^ l) (a : E) (ha : a ≠ 0) (y : Ω)
    (hy : y ^ l = algebraMap E Ω a * ((b : L) : Ω)) :
    ∃ γ : Gal(Ω/E) → ZMod l,
      (∀ σ τ, f (AlgEquiv.restrictNormalHom (K₁ := Ω) L σ, AlgEquiv.restrictNormalHom (K₁ := Ω) L τ) =
        γ τ - γ (σ * τ) + γ σ) ∧
      ∀ σ τ, AlgEquiv.restrictNormalHom (K₁ := Ω) L σ = AlgEquiv.restrictNormalHom (K₁ := Ω) L τ →
        σ y = τ y → γ σ = γ τ := by
  classical
  have : NeZero l := ⟨(Fact.out : l.Prime).ne_zero⟩
  set ρ : Gal(Ω/E) →* Gal(L/E) := AlgEquiv.restrictNormalHom (K₁ := Ω) L
  set φ : Lˣ →* Ωˣ := Units.map (algebraMap L Ω : L →+* Ω).toMonoidHom
  have hφ : ∀ w : Lˣ, ((φ w : Ωˣ) : Ω) = ((w : L) : Ω) := fun w => rfl
  have hφσ : ∀ (σ : Gal(Ω/E)) (w : Lˣ), φ (ρ σ • w) = σ • φ w := fun σ w =>
    Units.ext (AlgEquiv.restrictNormal_commutes σ L (w : L))
  obtain ⟨zU, hzUdef⟩ : ∃ zU : Ωˣ, zU = φ (unitOf L ζ hζ0) := ⟨_, rfl⟩
  have hzU : ((zU : Ωˣ) : Ω) = algebraMap E Ω ζ := by
    rw [hzUdef, hφ, unitOf_val]; rfl
  have hprim : IsPrimitiveRoot zU l := by
    rw [← IsPrimitiveRoot.coe_units_iff, hzU]
    exact hζ.map_of_injective (algebraMap E Ω).injective
  have hzfix : ∀ σ : Gal(Ω/E), σ • zU = zU := fun σ =>
    Units.ext (show σ ((zU : Ωˣ) : Ω) = (zU : Ω) by rw [hzU]; exact σ.commutes ζ)
  -- discrete logarithm on `μ_l ⊆ Ωˣ`
  let lg : Ωˣ → ZMod l := fun x =>
    if h : ∃ i < l, ((zU : Ωˣ) : Ω) ^ i = (x : Ω) then ((Classical.choose h : ℕ) : ZMod l) else 0
  have hlg : ∀ x : Ωˣ, x ^ l = 1 → zU ^ (lg x).val = x := by
    intro x hx
    have hx' : (x : Ω) ^ l = 1 := by rw [← Units.val_pow_eq_pow_val, hx, Units.val_one]
    have h := ((IsPrimitiveRoot.coe_units_iff).mpr hprim).eq_pow_of_pow_eq_one hx'
    have hlx : lg x = ((Classical.choose h : ℕ) : ZMod l) := dif_pos h
    apply Units.ext
    rw [hlx, Units.val_pow_eq_pow_val, ZMod.val_natCast_of_lt (Classical.choose_spec h).1]
    exact (Classical.choose_spec h).2
  have hy0 : y ≠ 0 := by
    intro h0
    have h1 : algebraMap E Ω a * ((b : L) : Ω) = 0 := by
      rw [← hy, h0, zero_pow (Fact.out : l.Prime).ne_zero]
    rcases mul_eq_zero.mp h1 with h | h
    · exact ha ((map_eq_zero _).mp h)
    · exact b.ne_zero (Subtype.ext h)
  set Y : Ωˣ := Units.mk0 y hy0
  have ha0 : algebraMap E Ω a ≠ 0 := (map_ne_zero _).mpr ha
  set aU : Ωˣ := Units.mk0 _ ha0
  have hafix : ∀ σ : Gal(Ω/E), σ • aU = aU := fun σ => Units.ext (σ.commutes a)
  have hY : Y ^ l = aU * φ b := Units.ext (by
    rw [Units.val_pow_eq_pow_val, Units.val_mul, hφ]; exact hy)
  -- `u σ = β(σ|L) y / σ y`
  set u : Gal(Ω/E) → Ωˣ := fun σ => φ (β (ρ σ)) * Y / σ • Y with hu_def
  have hu : ∀ σ, u σ ^ l = 1 := by
    intro σ
    have hb' : ρ σ • b = β (ρ σ) ^ l * b := by rw [← hb]; exact (div_mul_cancel _ _).symm
    have hσY : (σ • Y) ^ l = aU * (φ (β (ρ σ)) ^ l * φ b) := by
      rw [← smul_pow', hY, smul_mul', hafix, ← hφσ, hb', map_mul, map_pow]
    rw [hu_def]
    dsimp only
    rw [div_pow, mul_pow, hY, hσY]
    exact cg_pow _ _ _ _ rfl
  set γ : Gal(Ω/E) → ZMod l := fun σ => lg (u σ) with hγ_def
  have hγ : ∀ σ, zU ^ (γ σ).val = u σ := fun σ => hlg _ (hu σ)
  refine ⟨γ, fun σ τ => ?_, fun σ τ hρ hy' => ?_⟩
  · -- the multiplicative identity `u τ * u σ = ζ^f * u (σ τ)`
    have hfixu : σ • u τ = u τ := by rw [← hγ τ, smul_pow', hzfix]
    have hW : (σ * τ) • Y = σ • φ (β (ρ τ)) * σ • Y / u τ := by
      conv_rhs => rw [← hfixu]
      rw [hu_def]
      dsimp only
      rw [smul_div', smul_mul', mul_smul]
      exact (div_div_cancel _ _).symm
    have hc : σ • φ (β (ρ τ)) / φ (β (ρ (σ * τ))) * φ (β (ρ σ)) = zU ^ (f (ρ σ, ρ τ)).val := by
      have h1 := congrArg φ (hβ (ρ σ) (ρ τ))
      rw [map_mul, map_div, hφσ, ← map_mul ρ, map_pow, ← hzUdef] at h1
      exact h1
    have key : u τ * u σ = zU ^ (f (ρ σ, ρ τ)).val * u (σ * τ) := by
      rw [← hc]
      exact cg_key _ _ _ _ _ _ _ hW
    have hD : zU ^ (γ τ - γ (σ * τ) + γ σ).val * u (σ * τ) = zU ^ (f (ρ σ, ρ τ)).val * u (σ * τ) := by
      rw [← key, ← hγ (σ * τ), ← pow_val_add hprim.pow_eq_one, ← hγ τ, ← hγ σ, ← pow_val_add hprim.pow_eq_one]
      rw [show γ τ - γ (σ * τ) + γ σ + γ (σ * τ) = γ τ + γ σ by abel]
    have hD' := mul_right_cancel hD
    exact (ZMod.val_injective _ (hprim.pow_inj (ZMod.val_lt _) (ZMod.val_lt _) hD')).symm
  · have hYe : σ • Y = τ • Y := Units.ext hy'
    rw [hγ_def, hu_def]
    dsimp only
    rw [hρ, hYe]

end Emb
end RamanujanPetersson.CdOne

end

-- ===== S4.Def_RP_CdOne_Field =====
section

/-!
# S4-PD (3), field layer: `HypL` for `Gal(Ω/E₀)` from Tsen + Kummer

Let `Ω/E₀` be a (possibly infinite) Galois extension with a primitive `l`-th root of unity in `E₀`, such that every
finite subextension `E/E₀` is C1 and satisfies the **Kummer closure** property: if `L/E` is a finite Galois
subextension and `b ∈ Lˣ` has `σ b / b ∈ Lˣˡ` for all `σ ∈ Gal(L/E)`, then some `a·b` (`a ∈ Eˣ`) has an `l`-th root
in `Ω` (for `Ω` the maximal unramified extension this is where `Pic(V̄)/l = 0` enters). Then `HypL l Gal(Ω/E₀)`
holds (`hypL_of_field`): for open `N ⊴ Q` with `Q/N` an `l`-group, `E := Ω^Q`, `L := Ω^N`, a `ℤ/l`-valued
2-cocycle on `Q` factoring through `Q/N = Gal(L/E)` is killed in `Gal(Ω/E) = Q` by `exists_kummer_data` and
`emb_coboundary`.
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson.CdOne

open IntermediateField RamanujanPetersson.Tsen Topology

/-- A function constant on left cosets of an open subgroup is locally constant. -/
theorem lc_of_coset {P X : Type*} [Group P] [TopologicalSpace P] [IsTopologicalGroup P] (W : Subgroup P)
    (hW : IsOpen (W : Set P)) (u : P → X) (hu : ∀ g, ∀ w ∈ W, u (g * w) = u g) : IsLocallyConstant u := by
  rw [IsLocallyConstant.iff_eventually_eq]
  intro g
  have h1 : (W : Set P) ∈ 𝓝 (1 : P) := hW.mem_nhds W.one_mem
  have h2 : Filter.Tendsto (fun x : P => g⁻¹ * x) (𝓝 g) (𝓝 1) := by
    have := (continuous_const_mul g⁻¹).tendsto g
    rwa [inv_mul_cancel] at this
  filter_upwards [h2 h1] with x hx
  have := hu g _ hx
  rwa [mul_inv_cancel_left] at this

variable {E₀ Ω : Type*} [Field E₀] [Field Ω] [Algebra E₀ Ω] [IsGalois E₀ Ω]

theorem fix_fixed_of_isOpen (Q : Subgroup Gal(Ω/E₀)) (hQ : IsOpen (Q : Set Gal(Ω/E₀))) :
    (fixedField Q).fixingSubgroup = Q :=
  InfiniteGalois.fixingSubgroup_fixedField ⟨Q, Q.isClosed_of_isOpen hQ⟩

theorem finiteDimensional_fixedField_of_isOpen (Q : Subgroup Gal(Ω/E₀))
    (hQ : IsOpen (Q : Set Gal(Ω/E₀))) : FiniteDimensional E₀ (fixedField Q) :=
  (InfiniteGalois.isOpen_iff_finite (fixedField Q)).mp (by
    rw [fix_fixed_of_isOpen Q hQ]; exact hQ)

theorem finiteDimensional_extendScalars {E L' : IntermediateField E₀ Ω} (h : E ≤ L')
    [FiniteDimensional E₀ L'] : FiniteDimensional E (extendScalars h) := by
  have : Module.Finite E₀ (extendScalars h) := Module.Finite.of_surjective
    ({ toFun := fun x : L' => (⟨x.1, x.2⟩ : extendScalars h)
       map_add' := fun _ _ => rfl
       map_smul' := fun _ _ => rfl } : L' →ₗ[E₀] extendScalars h)
    (fun y => ⟨⟨y.1, y.2⟩, rfl⟩)
  exact Module.Finite.of_restrictScalars_finite E₀ E (extendScalars h)

theorem isGalois_extendScalars {Q N : Subgroup Gal(Ω/E₀)} (hQ : IsOpen (Q : Set Gal(Ω/E₀)))
    (hN : IsOpen (N : Set Gal(Ω/E₀))) (hnorm : ∀ q ∈ Q, ∀ n ∈ N, q * n * q⁻¹ ∈ N)
    (h : fixedField Q ≤ fixedField N) : IsGalois (fixedField Q) (extendScalars h) := by
  rw [← InfiniteGalois.normal_iff_isGalois]
  constructor
  intro τ hτ g
  rw [IntermediateField.mem_fixingSubgroup_iff] at hτ ⊢
  intro x hx
  have hg : ((fixingSubgroupEquiv (fixedField Q)).symm g : Gal(Ω/E₀)) ∈ Q :=
    (fix_fixed_of_isOpen Q hQ).le ((fixingSubgroupEquiv _).symm g).2
  have hτ' : ((fixingSubgroupEquiv (fixedField Q)).symm τ : Gal(Ω/E₀)) ∈ N :=
    (fix_fixed_of_isOpen N hN).le
      ((IntermediateField.mem_fixingSubgroup_iff _ _).mpr (fun y hy => hτ y hy))
  have := (IntermediateField.mem_fixingSubgroup_iff _ _).mp
    ((fix_fixed_of_isOpen N hN).ge (hnorm _ hg _ hτ'))
  exact this x hx

set_option synthInstance.maxHeartbeats 400000 in
set_option maxHeartbeats 800000 in
/-- **`HypL` from field theory.** If every finite subextension of `Ω/E₀` is C1 and has the Kummer closure
property, and `E₀` contains a primitive `l`-th root of unity, then `Gal(Ω/E₀)` satisfies `HypL l`. -/
theorem hypL_of_field (l : ℕ) [hl : Fact l.Prime] {ζ : E₀} (hζ : IsPrimitiveRoot ζ l)
    (hC1 : ∀ E : IntermediateField E₀ Ω, FiniteDimensional E₀ E → IsC1 E)
    (hKum : ∀ (E : IntermediateField E₀ Ω) (L : IntermediateField E Ω), FiniteDimensional E₀ E →
      FiniteDimensional E L → IsGalois E L → ∀ b : Lˣ, (∀ σ : Gal(L/E), ∃ c : Lˣ, σ • b / b = c ^ l) →
      ∃ a : E, a ≠ 0 ∧ ∃ y : Ω, y ^ l = algebraMap E Ω a * ((b : L) : Ω)) :
    HypL l Gal(Ω/E₀) := by
  classical
  intro Q N hQ hN hNQ hnorm hlq f hf hc hinv
  have hQE : (fixedField Q).fixingSubgroup = Q := fix_fixed_of_isOpen Q hQ
  have hNL : (fixedField N).fixingSubgroup = N := fix_fixed_of_isOpen N hN
  have hEL : fixedField Q ≤ fixedField N := fixedField_le hNQ
  have hfinE : FiniteDimensional E₀ (fixedField Q) := finiteDimensional_fixedField_of_isOpen Q hQ
  have : FiniteDimensional E₀ (fixedField N) := finiteDimensional_fixedField_of_isOpen N hN
  have : FiniteDimensional (fixedField Q) (extendScalars hEL) := finiteDimensional_extendScalars hEL
  have hGal : IsGalois (fixedField Q) (extendScalars hEL) := isGalois_extendScalars hQ hN hnorm hEL
  set E := fixedField Q with hE
  set L := extendScalars hEL with hL
  set ρ : Gal(Ω/E) →* Gal(L/E) := AlgEquiv.restrictNormalHom (K₁ := Ω) L with hρ
  have hρs : Function.Surjective ρ := AlgEquiv.restrictNormalHom_surjective (F := E) (K₁ := L) Ω
  let ι : Q ≃* Gal(Ω/E) := (MulEquiv.subgroupCongr hQE.symm).trans (fixingSubgroupEquiv E)
  let π : Q →* Gal(L/E) := ρ.comp ι.toMonoidHom
  have hπs : Function.Surjective π := hρs.comp ι.surjective
  have hπx : ∀ (σ : Q) (x : L), ((π σ x : L) : Ω) = (σ : Gal(Ω/E₀)) x := fun σ x =>
    AlgEquiv.restrictNormalHom_apply L (ι σ) x
  -- the kernel of `π` is `N`
  have hker : ∀ σ τ : Q, π σ = π τ → (τ : Gal(Ω/E₀))⁻¹ * σ ∈ N := by
    intro σ τ hστ
    rw [← hNL, IntermediateField.mem_fixingSubgroup_iff]
    intro x hx
    have h1 := hπx σ ⟨x, hx⟩
    rw [hστ, hπx τ ⟨x, hx⟩] at h1
    rw [AlgEquiv.mul_apply, ← h1, AlgEquiv.aut_inv, AlgEquiv.symm_apply_apply]
  have hN1 : ∀ σ : Q, (σ : Gal(Ω/E₀)) ∈ N → π σ = 1 := by
    intro σ hσ
    rw [← hNL, IntermediateField.mem_fixingSubgroup_iff] at hσ
    ext x
    rw [hπx]
    exact hσ x x.2
  have hinv' : ∀ σ σ' τ τ' : Q, π σ = π σ' → π τ = π τ' →
      f ((σ : Gal(Ω/E₀)), (τ : Gal(Ω/E₀))) = f ((σ' : Gal(Ω/E₀)), (τ' : Gal(Ω/E₀))) := by
    intro σ σ' τ τ' h1 h2
    have := hinv σ' σ'.2 τ' τ'.2 _ (hker σ σ' h1) _ (hker τ τ' h2)
    simpa only [mul_inv_cancel_left] using this
  -- the descended cocycle on `Gal(L/E)`
  let lift : Gal(L/E) → Q := Function.surjInv hπs
  have hlift : ∀ s, π (lift s) = s := Function.surjInv_eq hπs
  let fb : Gal(L/E) × Gal(L/E) → ZMod l := fun p => f ((lift p.1 : Gal(Ω/E₀)), (lift p.2 : Gal(Ω/E₀)))
  have hfb : ∀ σ τ : Q, fb (π σ, π τ) = f ((σ : Gal(Ω/E₀)), (τ : Gal(Ω/E₀))) := fun σ τ =>
    hinv' _ _ _ _ (hlift _) (hlift _)
  have hcoc : ∀ g h j, fb (g * h, j) + fb (g, h) = fb (h, j) + fb (g, h * j) := by
    intro g h j
    obtain ⟨a, rfl⟩ := hπs g
    obtain ⟨b, rfl⟩ := hπs h
    obtain ⟨c, rfl⟩ := hπs j
    rw [← map_mul, ← map_mul, hfb, hfb, hfb, hfb]
    exact hc a a.2 b b.2 c c.2
  have hG : IsPGroup l Gal(L/E) := by
    intro s
    obtain ⟨σ, rfl⟩ := hπs s
    obtain ⟨k, hk⟩ := hlq σ σ.2
    refine ⟨k, ?_⟩
    rw [← map_pow]
    exact hN1 _ (by rw [SubmonoidClass.coe_pow]; exact hk)
  have hζE : IsPrimitiveRoot (algebraMap E₀ E ζ) l := hζ.map_of_injective (algebraMap E₀ E).injective
  have hζE0 : algebraMap E₀ E ζ ≠ 0 := hζE.ne_zero hl.out.ne_zero
  obtain ⟨β, b, hβ, hb⟩ := exists_kummer_data (hC1 E hfinE) l hG hζE hζE0 fb hcoc
  obtain ⟨a, ha, y, hy⟩ := hKum E L hfinE inferInstance hGal b (fun σ => ⟨β σ, hb σ⟩)
  obtain ⟨γ₀, hγ₀, hγ₀'⟩ := emb_coboundary L hζE hζE0 fb β b hβ hb a ha y hy
  -- the cochain on `Gal(Ω/E₀)`
  let γ : Gal(Ω/E₀) → ZMod l := fun g => if h : g ∈ Q then γ₀ (ι ⟨g, h⟩) else 0
  have hstab : IsOpen (MulAction.stabilizer Gal(Ω/E₀) y : Set Gal(Ω/E₀)) :=
    stabilizer_isOpen_of_isIntegral y
  refine ⟨γ, lc_of_coset (N ⊓ MulAction.stabilizer Gal(Ω/E₀) y) (hN.inter hstab) γ ?_, ?_⟩
  · intro g w hw
    have hwN : w ∈ N := (Subgroup.mem_inf.mp hw).1
    have hwy : w y = y := MulAction.mem_stabilizer_iff.mp (Subgroup.mem_inf.mp hw).2
    by_cases hg : g ∈ Q
    · have hgw : g * w ∈ Q := Q.mul_mem hg (hNQ hwN)
      rw [show γ (g * w) = γ₀ (ι ⟨g * w, hgw⟩) from dif_pos hgw,
        show γ g = γ₀ (ι ⟨g, hg⟩) from dif_pos hg]
      apply hγ₀'
      · show π ⟨g * w, hgw⟩ = π ⟨g, hg⟩
        rw [show (⟨g * w, hgw⟩ : Q) = ⟨g, hg⟩ * ⟨w, hNQ hwN⟩ from rfl, map_mul,
          hN1 ⟨w, hNQ hwN⟩ hwN, mul_one]
      · show (g * w) y = g y
        rw [AlgEquiv.mul_apply, hwy]
    · have hgw : g * w ∉ Q := fun h => hg (by simpa using Q.mul_mem h (Q.inv_mem (hNQ hwN)))
      rw [show γ (g * w) = 0 from dif_neg hgw, show γ g = 0 from dif_neg hg]
  · intro g hg h hh
    rw [show γ g = γ₀ (ι ⟨g, hg⟩) from dif_pos hg, show γ h = γ₀ (ι ⟨h, hh⟩) from dif_pos hh,
      show γ (g * h) = γ₀ (ι ⟨g * h, Q.mul_mem hg hh⟩) from dif_pos (Q.mul_mem hg hh)]
    have := hγ₀ (ι ⟨g, hg⟩) (ι ⟨h, hh⟩)
    rw [← map_mul] at this
    rw [← hfb ⟨g, hg⟩ ⟨h, hh⟩]
    exact this

end RamanujanPetersson.CdOne


end

-- ===== S4.Def_RP_CdOne_Trans =====
section

/-!
# S4-PD (3)(iii), part T: transport of `HypL` to `π₁^geo`

* `hypL_of_equiv`: `HypL` transports along an isomorphism of topological groups;
* `geoEquiv A K q : π₁^geo ≃* Gal(K_U / E₀)` with `E₀ = constFieldU A K q` the field generated by the constants
  (`fixingSubgroup_constFieldU`); it is a homeomorphism (`geoEquiv_continuous`, `geoEquiv_symm_continuous`:
  compact to Hausdorff);
* `hypL_pi1geo`: `HypL l Gal(K_U/E₀) → HypL l π₁^geo`;
* `exists_zeta_constFieldU`: `E₀` contains a primitive `N`-th root of unity (`N` prime to `p`);
* `AllC1 E₀ Ω`, `KumClosure l E₀ Ω`: the two field hypotheses of `hypL_of_field`, as named propositions;
* `hypL_pi1geo_of_field`: `HypL l π₁^geo` from `AllC1` and `KumClosure` for `K_U / E₀`.
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson.CdOne

open IntermediateField RamanujanPetersson.Tsen Topology RamanujanPetersson.CurveCoh RamanujanPetersson.Kummer

/-- `HypL` transports along an isomorphism of topological groups. -/
theorem hypL_of_equiv (l : ℕ) {P P' : Type*} [Group P] [TopologicalSpace P] [Group P'] [TopologicalSpace P']
    (e : P ≃* P') (he : Continuous e) (he' : Continuous e.symm) (hL : HypL l P') : HypL l P := by
  intro Q N hQ hN hNQ hnorm hlq f hf hc hinv
  let Q' : Subgroup P' := Q.comap e.symm.toMonoidHom
  let N' : Subgroup P' := N.comap e.symm.toMonoidHom
  obtain ⟨γ, hγ, hγf⟩ := hL Q' N' (he'.isOpen_preimage _ hQ) (he'.isOpen_preimage _ hN) (fun x hx => hNQ hx)
    (fun q hq n hn => by
      show e.symm (q * n * q⁻¹) ∈ N
      rw [map_mul, map_mul, map_inv]
      exact hnorm _ hq _ hn)
    (fun q hq => by
      obtain ⟨k, hk⟩ := hlq _ hq
      exact ⟨k, show e.symm (q ^ l ^ k) ∈ N by rw [map_pow]; exact hk⟩)
    (fun x => f (e.symm x.1, e.symm x.2)) (hf.comp_continuous (he'.prodMap he'))
    (fun g hg h hh j hj => by
      show f (e.symm (g * h), e.symm j) + f (e.symm g, e.symm h) =
        f (e.symm h, e.symm j) + f (e.symm g, e.symm (h * j))
      rw [map_mul, map_mul]
      exact hc _ hg _ hh _ hj)
    (fun g hg h hh n hn n' hn' => by
      show f (e.symm (g * n), e.symm (h * n')) = f (e.symm g, e.symm h)
      rw [map_mul, map_mul]
      exact hinv _ hg _ hh _ hn _ hn')
  refine ⟨fun x => γ (e x), hγ.comp_continuous he, fun g hg h hh => ?_⟩
  have hg' : e g ∈ Q' := show e.symm (e g) ∈ Q by rw [MulEquiv.symm_apply_apply]; exact hg
  have hh' : e h ∈ Q' := show e.symm (e h) ∈ Q by rw [MulEquiv.symm_apply_apply]; exact hh
  have h1 := hγf (e g) hg' (e h) hh'
  simp only [MulEquiv.symm_apply_apply] at h1
  rw [h1]
  simp only [map_mul]

/-- The C1 hypothesis of `hypL_of_field`: every finite subextension of `Ω/E₀` is C1. -/
def AllC1 (E₀ Ω : Type*) [Field E₀] [Field Ω] [Algebra E₀ Ω] : Prop :=
  ∀ E : IntermediateField E₀ Ω, FiniteDimensional E₀ E → IsC1 E

set_option synthInstance.maxHeartbeats 400000 in
/-- The Kummer-closure hypothesis of `hypL_of_field`. -/
def KumClosure (l : ℕ) (E₀ Ω : Type*) [Field E₀] [Field Ω] [Algebra E₀ Ω] : Prop :=
  ∀ (E : IntermediateField E₀ Ω) (L : IntermediateField E Ω), FiniteDimensional E₀ E →
    FiniteDimensional E L → IsGalois E L → ∀ b : Lˣ, (∀ σ : Gal(L/E), ∃ c : Lˣ, σ • b / b = c ^ l) →
    ∃ a : E, a ≠ 0 ∧ ∃ y : Ω, y ^ l = algebraMap E Ω a * ((b : L) : Ω)

section Geo

variable (A K : Type) [CommRing A] [Field K] [Algebra A K] (q : ℕ)

variable {p : ℕ} [Fact p.Prime] [CharP K p]

/-- `E₀` contains a primitive `N`-th root of unity for `N` prime to `p`. -/
theorem exists_zeta_constFieldU {e : ℕ} (he : 0 < e) (N : ℕ) [NeZero N] (hN : (N : K) ≠ 0) :
    ∃ ζ : constFieldU A K (p ^ e), IsPrimitiveRoot ζ N := by
  obtain ⟨ζ, hζ, hc⟩ := Kummer.exists_zeta A K p he N hN
  have hmem : ζ ∈ constFieldU A K (p ^ e) := IntermediateField.subset_adjoin _ _ hc
  exact ⟨⟨ζ, hmem⟩, (IsPrimitiveRoot.map_iff_of_injective (ζ := (⟨ζ, hmem⟩ : constFieldU A K (p ^ e)))
    (f := (constFieldU A K (p ^ e)).val) Subtype.val_injective).1 hζ⟩

end Geo

end RamanujanPetersson.CdOne


end

-- ===== S4.Def_RP_CdOne_KumMain =====
section

/-!
# S4-PD (3)(iii)(K), main: the Kummer-closure property of `K_U / E₀` from the divisibility of `Pic(V̄)`

* `PicDivU A K p l`: **`Pic(V̄)` is `l`-divisible at every finite level** -- for every finite `M ≤ K_U` and every
  divisor `D` of `B_M` (finite support), after a constant extension `M·𝔽_{p^m}` some `a ≠ 0` has
  `D + div(a) ≡ 0 mod l`. This is the explicit hypothesis of S4-PD item (3) (discharged by S4-CoreB).
* `kumClosure_of_picDiv`: `PicDivU` gives `KumClosure l E₀ K_U` for `E₀ = constFieldU`: a Kummer element `b` of a
  finite Galois `L/E` becomes an `l`-th power in `K_U` after multiplying by some `a ∈ E^×`.
  Proof: `D(P) = v_{w(P)}(b)` on `B_{ML ∩ E}` is well defined mod `l` (`orbit_dvd`, `hgrp_dvd`); `PicDivU` gives `a`;
  then `a·b` has `l`-divisible valuations on `ML·𝔽_{p^m}` (`val_underI`) and `root_mem_maxUnram_of_dvd` applies.
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson.CdOne

open IntermediateField IsDedekindDomain RamanujanPetersson.Kummer RamanujanPetersson.CurveCoh

noncomputable section

/-- **`Pic(V̄)/l = 0` at every finite level `M ≤ K_U`**: every divisor `D` of `B_M` becomes, after a constant
extension `M·𝔽_{p^m}`, congruent mod `l` to a principal divisor `-div(a)`. -/
def PicDivU (A K : Type) [CommRing A] [IsDedekindDomain A] [Field K] [Algebra A K] [IsFractionRing A K]
    (p : ℕ) [Fact p.Prime] [CharP K p] (l : ℕ) : Prop :=
  ∀ M : IntermediateField K (AlgebraicClosure K), FiniteDimensional K M → M ≤ maxUnram A K →
    ∀ [IsDedekindDomain (integralClosure A M)] [IsFractionRing (integralClosure A M) M]
      (D : HeightOneSpectrum (integralClosure A M) → ℤ), (Function.support D).Finite →
    ∃ m : ℕ, 0 < m ∧ ∃ a : ↥(M ⊔ constLevel K p m), a ≠ 0 ∧
      ∀ [IsDedekindDomain (integralClosure A ↥(M ⊔ constLevel K p m))]
        [IsFractionRing (integralClosure A ↥(M ⊔ constLevel K p m)) ↥(M ⊔ constLevel K p m)]
        (w : HeightOneSpectrum (integralClosure A ↥(M ⊔ constLevel K p m))),
        (l : ℤ) ∣ D (underI A (le_sup_left : M ≤ M ⊔ constLevel K p m) w) +
          WithZero.log (w.valuation (↥(M ⊔ constLevel K p m)) a)

variable {K : Type} [Field K] (A : Type) [CommRing A] [IsDedekindDomain A] [Algebra A K] [IsFractionRing A K]
  {p : ℕ} [Fact p.Prime] [CharP K p]

end

end RamanujanPetersson.CdOne


end

-- ===== S4.Def_RP_CdOne_C1 =====
section

/-!
# S4-PD (3)(iii), part C: the field `E₀` generated by the constants is C1 (Tsen)

`K` algebraic over `𝔽_q(t)` (`[Algebra.IsAlgebraic (RatFunc Fq) K]`), `q = #𝔽_q = p ^ e`. Then
`E₀ = constFieldU A K q ⊆ K_U` contains `𝔽̄_q` (`constEmb`) and is algebraic over `𝔽̄_q(t)` with `t` transcendental,
so it is C1 by Tsen (`isC1_constFieldU`), and so is every finite extension (`allC1_constFieldU`).
-/

set_option autoImplicit false
set_option linter.unusedSectionVars false

namespace RamanujanPetersson.CdOne

open IntermediateField RamanujanPetersson.Tsen RamanujanPetersson.CurveCoh RamanujanPetersson.Kummer Polynomial

/-- Tsen, abstract form: a field algebraic over `k(t)`, `k` algebraically closed, `t` transcendental, is C1. -/
theorem isC1_of_transcendental (k M : Type*) [Field k] [IsAlgClosed k] [Field M] [Algebra k M] (t : M)
    (ht : Transcendental k t) [Algebra.IsAlgebraic (adjoin k {t}) M] : IsC1 M := by
  let e := RatFunc.algEquivOfTranscendental t ht
  let _ : Algebra (RatFunc k) (adjoin k {t}) := e.toRingEquiv.toRingHom.toAlgebra
  have : Algebra.IsAlgebraic (RatFunc k) (adjoin k {t}) := ⟨fun x => by
    have h2 : algebraMap (RatFunc k) (adjoin k {t}) (e.symm x) = x := e.apply_symm_apply x
    exact h2 ▸ isAlgebraic_algebraMap _⟩
  exact (tsen k (adjoin k {t})).of_algebraic

/-- Every element of `𝔽̄_q` is a constant: `c ^ (q ^ n) = c` for some `n > 0`. -/
theorem exists_pow_card_pow_eq (Fq : Type*) [Field Fq] [Fintype Fq] (c : AlgebraicClosure Fq) :
    ∃ n : ℕ, 0 < n ∧ c ^ Fintype.card Fq ^ n = c := by
  have hc : IsIntegral Fq c := (Algebra.IsAlgebraic.isAlgebraic c).isIntegral
  have : FiniteDimensional Fq (adjoin Fq {c}) := adjoin.finiteDimensional hc
  let _ : Fintype (adjoin Fq {c}) := Module.fintypeOfFintype (Module.finBasis Fq (adjoin Fq {c}))
  refine ⟨Module.finrank Fq (adjoin Fq {c}), Module.finrank_pos, ?_⟩
  have h1 := FiniteField.pow_card (⟨c, mem_adjoin_simple_self Fq c⟩ : adjoin Fq {c})
  rw [Module.card_eq_pow_finrank (K := Fq)] at h1
  have h2 := congrArg (fun x : adjoin Fq {c} => (x : AlgebraicClosure Fq)) h1
  simp only [SubmonoidClass.coe_pow] at h2
  exact h2

section Const

variable (A K : Type) [CommRing A] [Field K] [Algebra A K] {p : ℕ} [Fact p.Prime] [CharP K p]
  (Fq : Type) [Field Fq] [Fintype Fq] [Algebra Fq K] {e : ℕ} (he : 0 < e) (hq : Fintype.card Fq = p ^ e)

/-- The embedding `𝔽̄_q → K̄` over `𝔽_q`. -/
noncomputable def fqBar : AlgebraicClosure Fq →ₐ[Fq] AlgebraicClosure K := IsAlgClosed.lift

include hq in
theorem fqBar_isConst (c : AlgebraicClosure Fq) : IsConst (p ^ e) (fqBar K Fq c) := by
  obtain ⟨n, hn, h⟩ := exists_pow_card_pow_eq Fq c
  rw [hq] at h
  exact IsConst.map (fqBar K Fq) ⟨n, hn, h⟩

include he hq in
theorem fqBar_mem_maxUnram (c : AlgebraicClosure Fq) : fqBar K Fq c ∈ maxUnram A K :=
  mem_maxUnram_of_isConst (A := A) (K := K) (p := p) he (fqBar_isConst K Fq hq c)

include he hq in
theorem fqBar_mem_constFieldU (c : AlgebraicClosure Fq) :
    (⟨fqBar K Fq c, fqBar_mem_maxUnram A K Fq he hq c⟩ : maxUnram A K) ∈ constFieldU A K (p ^ e) := by
  obtain ⟨n, hn, h⟩ := fqBar_isConst K Fq hq c
  exact IntermediateField.subset_adjoin _ _ ⟨n, hn, Subtype.ext h⟩

/-- `𝔽̄_q ⊆ E₀`. -/
noncomputable def constEmb : AlgebraicClosure Fq →+* constFieldU A K (p ^ e) where
  toFun c := ⟨⟨fqBar K Fq c, fqBar_mem_maxUnram A K Fq he hq c⟩, fqBar_mem_constFieldU A K Fq he hq c⟩
  map_one' := Subtype.ext (Subtype.ext (map_one (fqBar K Fq)))
  map_mul' x y := Subtype.ext (Subtype.ext (map_mul (fqBar K Fq) x y))
  map_zero' := Subtype.ext (Subtype.ext (map_zero (fqBar K Fq)))
  map_add' x y := Subtype.ext (Subtype.ext (map_add (fqBar K Fq) x y))

/-- The inclusion `E₀ → K̄`. -/
noncomputable def nuE : constFieldU A K (p ^ e) →ₐ[K] AlgebraicClosure K :=
  (maxUnram A K).val.comp (constFieldU A K (p ^ e)).val

variable [Algebra (RatFunc Fq) K] [IsScalarTower Fq (RatFunc Fq) K] [Algebra.IsAlgebraic (RatFunc Fq) K]

include he hq in
/-- `E₀` is C1 (Tsen). -/
theorem isC1_constFieldU : IsC1 (constFieldU A K (p ^ e)) := by
  classical
  set E₀ := constFieldU A K (p ^ e)
  set ι := constEmb A K Fq he hq
  let _ : Algebra (AlgebraicClosure Fq) E₀ := ι.toAlgebra
  set θ : RatFunc Fq →+* E₀ := (algebraMap K E₀).comp (algebraMap (RatFunc Fq) K)
  set t : E₀ := θ RatFunc.X
  -- `t` is transcendental over `𝔽̄_q`
  have htr : Transcendental (AlgebraicClosure Fq) t := by
    rintro ⟨P, hP, hev⟩
    let _ : Algebra (AlgebraicClosure Fq) (AlgebraicClosure K) := (fqBar K Fq).toRingHom.toAlgebra
    have : IsScalarTower Fq (AlgebraicClosure Fq) (AlgebraicClosure K) :=
      IsScalarTower.of_algebraMap_eq fun a => ((fqBar K Fq).commutes a).symm
    set x0 : K := algebraMap (RatFunc Fq) K RatFunc.X
    have hA : IsAlgebraic (AlgebraicClosure Fq) (algebraMap K (AlgebraicClosure K) x0) := by
      refine ⟨P, hP, ?_⟩
      have h1 := congrArg (nuE A K) hev
      rw [aeval_def, RingHom.algebraMap_toAlgebra, map_zero, ← AlgHom.coe_toRingHom, hom_eval₂] at h1
      rw [aeval_def, RingHom.algebraMap_toAlgebra]
      exact h1
    have hB : IsAlgebraic Fq (algebraMap K (AlgebraicClosure K) x0) := IsAlgebraic.restrictScalars (R := Fq) hA
    have hC : IsAlgebraic Fq x0 :=
      (isAlgebraic_algHom_iff (IsScalarTower.toAlgHom Fq K (AlgebraicClosure K))
        (algebraMap K (AlgebraicClosure K)).injective).1 hB
    have hD : IsAlgebraic Fq (RatFunc.X : RatFunc Fq) :=
      (isAlgebraic_algHom_iff (IsScalarTower.toAlgHom Fq (RatFunc Fq) K)
        (algebraMap (RatFunc Fq) K).injective).1 hC
    exact RatFunc.transcendental_X hD
  set F₀ := adjoin (AlgebraicClosure Fq) {t}
  -- step 1: `θ (𝔽_q(t)) ⊆ F₀`
  have hcst : ∀ a : Fq, θ (algebraMap Fq (RatFunc Fq) a) ∈ F₀ := fun a => by
    have h : θ (algebraMap Fq (RatFunc Fq) a) = algebraMap (AlgebraicClosure Fq) E₀ (algebraMap Fq _ a) := by
      apply Subtype.ext; apply Subtype.ext
      show algebraMap K (AlgebraicClosure K) (algebraMap (RatFunc Fq) K (algebraMap Fq (RatFunc Fq) a)) =
        fqBar K Fq (algebraMap Fq (AlgebraicClosure Fq) a)
      rw [← IsScalarTower.algebraMap_apply, ← IsScalarTower.algebraMap_apply, AlgHom.commutes]
    rw [h]
    exact F₀.algebraMap_mem _
  let S : IntermediateField Fq (RatFunc Fq) :=
    Subfield.toIntermediateField (F₀.toSubfield.comap θ) hcst
  have hS : ∀ r, θ r ∈ F₀ := by
    have hle : adjoin Fq {(RatFunc.X : RatFunc Fq)} ≤ S :=
      adjoin_simple_le_iff.2 (show θ RatFunc.X ∈ F₀ from mem_adjoin_simple_self _ t)
    rw [RatFunc.adjoin_X] at hle
    exact fun r => hle (Set.mem_univ r)
  -- step 2: `K ⊆ E₀` is integral over `F₀`
  have hK : ∀ y : K, IsIntegral F₀ (algebraMap K E₀ y) := fun y =>
    IsIntegral.map_of_comp_eq (θ.codRestrict F₀ hS) (algebraMap K E₀) (RingHom.ext fun _ => rfl)
      (Algebra.IsAlgebraic.isAlgebraic y).isIntegral
  -- step 3 and 4: `E₀` is algebraic over `F₀ (K)`, which is algebraic over `F₀`
  set L₁ := adjoin F₀ (Set.range (algebraMap K E₀))
  have : Algebra.IsAlgebraic F₀ L₁ := isAlgebraic_adjoin (by rintro _ ⟨y, rfl⟩; exact hK y)
  have hx : ∀ x : E₀, IsAlgebraic F₀ x := fun x => by
    have h1 : IsIntegral K x := (isIntegral_algHom_iff (nuE A K) (Subtype.val_injective.comp
      Subtype.val_injective)).1 (Algebra.IsIntegral.isIntegral _)
    have h2 : IsIntegral L₁ x :=
      IsIntegral.map_of_comp_eq ((algebraMap K E₀).codRestrict L₁ fun y => subset_adjoin _ _ ⟨y, rfl⟩)
        (RingHom.id E₀) (RingHom.ext fun _ => rfl) h1
    exact IsAlgebraic.restrictScalars (R := F₀) (S := L₁) h2.isAlgebraic
  have : Algebra.IsAlgebraic F₀ E₀ := ⟨hx⟩
  exact isC1_of_transcendental (AlgebraicClosure Fq) E₀ t htr

end Const

end RamanujanPetersson.CdOne


end
Source
J. S. Milne, Étale Cohomology, Princeton University Press (1980), Chapter V, §2 (Poincaré duality for curves) and Chapter VI, §13 (the Lefschetz trace formula); P. Deligne, Cohomologie étale (SGA 4½), Lecture Notes in Math. 569, Springer (1977), « Dualité » and « Rapport sur la formule des traces »; J. S. Milne, Jacobian varieties, in Arithmetic Geometry (G. Cornell, J. H. Silverman, eds.), Springer (1986), 167-212; H. Stichtenoth, Algebraic Function Fields and Codes, 2nd ed., GTM 254, Springer (2009)

View graph

Get started

Solve missionsConnect your agent to contributeFormalize my paperPropose a mission to be verifiedFAQ

About Prove2Me

Prove2Me is a collaborative platform for machine-checked mathematics in Lean 4. Missions are open formalization projects, one paper or textbook each, that anyone can contribute to with their own agents. Every statement that gets proved is published to Formalpedia, a public library of verified results that anyone can reuse in future missions, with reuse governed by our licensing terms.

How Prove2Me worksResearch paperProve2Me Team
SKILL.mdTourFAQContactTerms
© 2026 Prove2Me