Skip to content

Lean formalization of the Riemann Hypothesis (Alpöge, 2026-11-20) being cleaned up by members of the Lean community.

Python
79.2 KB
Raw Blame
module

import Mathlib.Algebra.Order.Star.Int
import Mathlib.RingTheory.PicardGroup
import Mathlib.Tactic.Monotonicity.Lemmas
public import New.Congruences.Lifting.ExponentLattices
import Lib.PadicComparison.Descent.TestCategory
import Lib.PadicHodge.Kisin.FrameTheorem
import Lib.PadicHodge.Kisin.PeriodMatrixBasis
import New.Congruences.Lifting.HodgeExpansion

/-!
# Sides of a pairing, cokernel killers and the pairing lemma for cup products

A side `New.Lift.KummerChart.PairingSide` consists of a lattice Y, a lattice C (`paramLattice`) and
an O-linear map α (`cocycleMap`) from C to the crystalline cocycles Z_f(Y)
(`New.Period.crysCocycles`). These cocycles define an extension of the trivial lattice on
`S.paramLattice` by Y. All lattices are tensored with W(C^♭), on which ℤ × Γ acts with φ the
Frobenius, and `P` is a pairing of the lattices of two sides modulo p^m. The pairing lemma shows
that, for cocycles that pair safely, safe moves from (φx, φx') to (x, x') make a multiple `p ^ e` of
their cup product, read in ℚ̄_p^×, a coboundary.

On a Kummer chart let z be the coordinate, E a generator of ker θ and N the Kisin module. The ideal
J_l(i) is generated by a modulus r and by the multipliers s ∈ A_inf for which s times each constant
(the letter-i part of 1 ⊗ c, c ∈ C) lifts to the extension inside A_inf·φ^{l*}N. Elements of the
form p^κ E^s and z^a are shown to lie in it.

## Main definitions and results

* `New.Lift.Pairing.IsSafe`: a pair is safe if `p ^ e` times its pairing is small, that is, lies in
  the image `New.Lift.smallPart` of W(𝔪^♭).
* `New.Lift.Pairing.IsScaledCupCoboundary`: the cup product of the cocycles `S.cocycleMap c` and
  `p ^ e • S'.cocycleMap c'` is a coboundary.
* `New.Lift.Pairing.IsScaledCupCoboundary.of_isSafePath`: the pairing lemma, which derives this from
  a path of safe moves.
* `New.Lift.KummerChart.PairingSide.liftIdeal`, `New.Lift.KummerChart.PairingSide.KillsCokernel`:
  the ideal J_l(i); p^κ E^s lies in J_0(i) with r = 0.
* `New.Lift.KummerChart.PairingSide.exists_z_pow_mem_liftIdeal`: z^a ∈ J_0(i) with r = p^{κ+1} and
  (p − 1)a ≤ e(ω + κ), where the jumps are ≤ ω and e is the ramification index.
* `New.Lift.KummerChart.PairingSide.killsCokernel_of_isUnramified`: on an unramified chart with p ≥
  5, p^s E^t ∈ J_0(i), r = 0, when the jumps are ≤ (p − 3)(s + t).

Notions from other files:
* `New.Lift.KummerChart.Coeffs`: a ring of coefficients O, a finite free Z_p-algebra with an element
  ζ such that ζ^{p^f−1} = 1; ζ cuts out the letters.
* `New.Lift.KummerChart.JumpLattice`: a finite free O-module with an action of Γ, crystalline over
  the subgroup Γ' of the chart, with a finite set `jumpSet i` of integers holding its jumps at each
  letter i. Its `Ambient` is its tensor product with W(C^♭).
* `New.Lift.KummerChart.Letter`: the letters of a Kummer chart: the multiplicative group of the
  field with p^f elements inside C^♭, where f is the number `k.f` of the chart.
* `New.Lift.KummerChart.stdOrders`: the exponents (a, u) ↦ 0 for a < l and −u for a ≥ l, prescribed
  at φ^a E for the jump u.
* `New.Lift.KummerChart.JumpLattice.stdOrdersPart`: the elements of 𝒩, the Kisin module with all φ^a
  E inverted, that lie at the letter i and have the standard exponents of level l.
-/

@[expose] public section

noncomputable section

/-! ## The pairing lemma for scaled cup products -/

namespace New.Lift

open Period KummerChart Topology crysCocycles FrobGroup Submodule Selmer IsLocallyConstant Finset

variable {p : ℕ} [ThePrime p] [Γ : GroupOverGp p] [k : KummerChart Γ] {O : Coeffs}

/-- One side of a pairing: a lattice Y (`kerLattice`), a lattice C (`paramLattice`), an O-linear map
α (`cocycleMap`) from C to the crystalline cocycles Z_f(Y), and for each letter a finite set of
integers that contains 0. -/
structure KummerChart.PairingSide (O : Coeffs) extends kerLattice : JumpLattice O where
  /-- The lattice C that parametrises the cocycles. -/
  paramLattice : GalLattice O Γ
  /-- An O-linear map from C to the crystalline cocycles Z_f(Y). -/
  cocycleMap : paramLattice →ₗ[O] crysCocycles ρ
  /-- Each jump set of the side contains 0. -/
  zero_mem (i : Letter) : 0 ∈ jumpSet i

section

variable {k} (S S' : PairingSide O)

/-- For a side S, the lattice datum formed by the extension of the trivial lattice on
`S.paramLattice` by Y given by the cocycles of S. At each letter it has the jump set of S; at each
embedding of O into ℂ_p its set `embJumps` is that of S with 0 added. The field `inClass` says that
the extension is crystalline over Γ' with its jumps in these sets. -/
abbrev KummerChart.PairingSide.extensionLattice : JumpLattice O where
  toGalLattice := ⟨S.Carrier × S.paramLattice.Carrier, extensionRep S.cocycleMap⟩
  jumpSet := S.jumpSet
  embJumps g := insert 0 (S.embJumps g)
  inClass := by
    refine ⟨isAdmissible_extensionRep _ S.inClass.1, fun g u hu ↦ ?_, nofun⟩
    -- A nonzero jump of the extension is a jump of the lattice of `S`.
    simpa [or_iff_not_imp_left] using fun hu₀ : u ≠ 0 ↦
      S.inClass.2.1 g u (ne_bot_of_le_ne_bot hu (jump_extensionRep_le _ hu₀))
  embJumps_subset h := insert_subset (S.zero_mem _) (S.embJumps_subset h)

/-- For a side S, the lattice datum formed by C with trivial action of Γ, with jump set {0} at
every letter and at every embedding of O into ℂ_p. The latter is written {−0}, the case c = 0 of
the jump −c of the c-th power of the cyclotomic character. -/
abbrev KummerChart.PairingSide.trivialLattice : JumpLattice O where
  toGalLattice := ⟨S.paramLattice, 1⟩
  jumpSet _ := {0}
  embJumps _ := {-0}
  inClass := InClass.of_cyclotomic_pow 0 (by simp)
  embJumps_subset := by simp

/-- The projection from the extension of C by Y onto the trivial lattice C, as an equivariant
map of lattice data. -/
abbrev KummerChart.PairingSide.projTrivial : S.extensionLattice.Hom S.trivialLattice :=
  ⟨LinearMap.snd O S.Carrier S.paramLattice.Carrier, fun _ ↦ rfl⟩

/-- For a side S, the W(C^♭)-linear extension of the projection of Y × C onto Y, from the ambient
module of the extension lattice to that of Y. -/
abbrev KummerChart.PairingSide.wittFst : S.extensionLattice.Ambient →ₗ[WittCFlat]
  S.kerLattice.Ambient :=
  S.extensionLattice.wittMap S.kerLattice (LinearMap.fst O S.Carrier S.paramLattice.Carrier)

/-- For two sides S, S', the lattice datum Y ⊗_O Y' with, at each letter i, the sumset U(i) + U'(i)
of their integer sets. -/
abbrev KummerChart.PairingSide.tensorLattice : JumpLattice O where
  toGalLattice := S.toGalLattice.tensor S'.toGalLattice
  jumpSet i := (S.jumpSet i).image₂ (· + ·) (S'.jumpSet i)
  embJumps g := (S.embJumps g).image₂ (· + ·) (S'.embJumps g)
  inClass := S.inClass.tensor S'.inClass
  embJumps_subset h := by grw [S.embJumps_subset h, S'.embJumps_subset h]

end

variable {k} {S S' : PairingSide O} {e : ℕ} (P : Pairing S.toGalLattice S'.toGalLattice)
  (n : FrobGroup Γ)

/-- The third side of a pairing P. Its lattice is the Tate dual Hom(Y ⊗ Y', O(1)), and
`paramLattice` = O maps 1 to `P.cocycle`, the crystalline cocycle c with gψ − ψ = p^m c(g) for the
form ψ of P. The jump sets are {0} ∪ {−u − u' − 1 : u ∈ `S.jumpSet i`, u' ∈ `S'.jumpSet i`} at the
letters i; at the embeddings of O into ℂ_p (`embJumps`) they are formed in the same way, without
adding 0. -/
abbrev Pairing.tateDualSide : PairingSide O :=
  let T := S.tensorLattice S'
  { toGalLattice := T.toGalLattice.tateDual
    jumpSet i := insert 0 ((T.jumpSet i).image fun u ↦ -u - 1)
    embJumps g := (T.embJumps g).image fun u ↦ -u - 1
    inClass := T.inClass.dual
    embJumps_subset h := by grind [T.embJumps_subset h]
    paramLattice := ⟨O, 1⟩
    cocycleMap := LinearMap.toSpanSingleton O _ P.cocycle
    zero_mem := by simp }

/-- The W(C^♭)-bilinear extension of the pairing Y × Y' → ℤ/p^m(1) of P to a pairing of
W(C^♭) ⊗ Y and W(C^♭) ⊗ Y' with values in W(C^♭) ⊗ ℤ/p^m(1). Here `DiagTensor T` is W(C^♭) ⊗ T
over ℤ_p, `overZp` reads a representation over O as one over ℤ_p, and `charRep M χ` is M with Γ
acting through the cyclotomic character χ. -/
abbrev Pairing.wittPairing :
    DiagTensor (Rep.of (overZp S.ρ)) →ₗ[WittCFlat] DiagTensor (Rep.of (overZp S'.ρ)) →ₗ[WittCFlat]
      DiagTensor (Rep.of (charRep (ℤ_[p] ⧸ Ideal.span {(p : ℤ_[p]) ^ P.exponent}) χ)) :=
  DiagTensor.pair P.modPairing

/-- The pair (w, y) of elements of the ambient modules of the two extension lattices is safe: p^e
times the pairing of their components in W(C^♭) ⊗ Y and W(C^♭) ⊗ Y' lies in `New.Lift.smallPart`,
the image of W(𝔪^♭). -/
def Pairing.IsSafe (e : ℕ) (w : S.extensionLattice.Ambient) (y : S'.extensionLattice.Ambient) :
    Prop :=
  p ^ e • P.wittPairing (S.wittFst w) (S'.wittFst y) ∈ smallPart P.exponent

/-- The move of the first side by `y` is safe while `x'` is at rest: for every `g` in `k.galMonoid`
(the elements (0, g) with g in Γ'), the pair `(y, g • x' - x')` is safe. -/
def Pairing.IsSafeMoveFst (e : ℕ) (y : S.extensionLattice.Ambient)
    (x' : S'.extensionLattice.Ambient) : Prop :=
  ∀ g : k.galMonoid, P.IsSafe e y (g • x' - x')

/-- The move of the second side by `y'` is safe while `x` is at rest: for every `g` in
`k.galMonoid`, the pair `(g • x - x, g • y')` is safe. -/
def Pairing.IsSafeMoveSnd (e : ℕ) (x : S.extensionLattice.Ambient)
    (y' : S'.extensionLattice.Ambient) : Prop :=
  ∀ g : k.galMonoid, P.IsSafe e (g • x - x) (g • y')

/-- Four safe moves lead from `(y, y')` by `(w, y')`, `(w, w')` and `(x, w')` to `(x, x')`. -/
structure Pairing.IsSafePath (e : ℕ) (y w x : S.extensionLattice.Ambient)
    (y' w' x' : S'.extensionLattice.Ambient) : Prop where
  /-- The first side moves between `y` and `w` with `y'` at rest. -/
  isSafeMoveFst_start : P.IsSafeMoveFst e (y - w) y'
  /-- The second side moves between `y'` and `w'` with `w` at rest. -/
  isSafeMoveSnd_start : P.IsSafeMoveSnd e w (y' - w')
  /-- The first side moves between `w` and `x` with `w'` at rest. -/
  isSafeMoveFst_end : P.IsSafeMoveFst e (w - x) w'
  /-- The second side moves between `w'` and `x'` with `x` at rest. -/
  isSafeMoveSnd_end : P.IsSafeMoveSnd e x (w' - x')

/-- The conclusion of the pairing lemma. For every topology on Γ for which the map to G_p is an open
embedding, the cup product of the cocycles `S.cocycleMap c` and `p ^ e • S'.cocycleMap c'`, read in
ℚ̄_p^×, is the coboundary of a continuous cochain (`New.Lift.Pairing.IsCupCoboundary`). -/
def Pairing.IsScaledCupCoboundary (e : ℕ) (c : S.paramLattice.Carrier)
    (c' : S'.paramLattice.Carrier) : Prop :=
  ∀ ⦃_ : TopologicalSpace Γ⦄, IsOpenEmbedding Γ.overGp.toGp → P.IsCupCoboundary (S.cocycleMap c)
    (p ^ e • S'.cocycleMap c')

/-- For `n` in ℤ × Γ and `x` in the extension lattice tensored with W(C^♭), the Y-component of
`n • x` is `n` applied to the Y-component of `x`, plus the cocycle of the Γ-component of `n` at
the C-component of `n • x`. -/
lemma wittFst_smul (x : S.extensionLattice.Ambient) :
    S.wittFst (n • x) = n • S.wittFst x + S.trivialLattice.wittMap S.kerLattice
      (LinearMap.fst O.O S.Carrier S.paramLattice.Carrier ∘ₗ extensionRep S.cocycleMap
        (FrobGroup.snd n) ∘ₗ
        LinearMap.inr O.O S.Carrier S.trivialLattice.Carrier) (n • S.projTrivial.wittMap x) := by
  -- Both sides are additive in `x`; on a pure tensor this is the formula for `extensionRep`.
  revert x
  refine diagTensor_induction fun a t ↦ ?_
  have h_fst : (extensionRep S.cocycleMap (FrobGroup.snd n) t).1 = S.ρ (FrobGroup.snd n) t.1 +
      (extensionRep S.cocycleMap (FrobGroup.snd n) (0, t.2)).1 := by simp [extensionRep]
  simp [h_fst]

/-- The extended pairing of a pairing P commutes with the action of ℤ × Γ. -/
lemma Pairing.smul_wittPairing (x : DiagTensor (Rep.of (overZp S.ρ)))
    (y : DiagTensor (Rep.of (overZp S'.ρ))) :
    n • P.wittPairing x y = P.wittPairing (n • x) (n • y) :=
  (baseChangePairing_map _ (P.modPairing_rho (FrobGroup.snd n)) x y).symm

/-- Let `Γ` map to G_p by an open embedding (`hj`), and let `a` and `a'` be crystalline cocycles of
the lattices Y and Y' of the sides `S` and `S'`. If on `k.subgroup` their cup product under `P` is
the coboundary of a function `κ` that vanishes near `1`, then `P.IsCupCoboundary a a'`: on all of
`Γ` the image of the cup product in ℚ̄_p^× is the coboundary of a continuous cochain. -/
lemma Pairing.isCupCoboundary_of_eq_coboundary [TopologicalSpace Γ]
    (hj : IsOpenEmbedding Γ.overGp.toGp) (a : crysCocycles S.ρ) (a' : crysCocycles S'.ρ)
    (κ : k.subgroup → QuotSpan ((p : ℤ_[p]) ^ P.exponent))
    (hκ_near : ∀ᶠ h : k.subgroup in 𝓝 1, κ h = 0)
    (h_coboundary : ∀ g h : k.subgroup,
      P.modPairing ((a : Γ → S.Carrier) g) (S'.ρ g ((a' : Γ → S'.Carrier) h)) =
        charRep (QuotSpan ((p : ℤ_[p]) ^ P.exponent)) χ (g : Γ) (κ h) - κ (g * h) + κ g) :
    P.IsCupCoboundary a a' := by
  -- The class of the cup product `b` on `Γ` is killed by the index of `k.subgroup`; it is also
  -- killed by `p ^ m`, and the two are coprime.
  have h_local := isLocalGalois_of_isOpenEmbedding hj
  have h_dvd {T : PairingSide O} {z : Γ → T.Carrier} (hz : z ∈ crysCocycles T.ρ) :
      ∀ᶠ g in 𝓝 (1 : Γ), ∃ v : T.Carrier, z g = p ^ P.exponent • v :=
    (nearOne_eq_nhds_one hj).ge (eventually_eq_pow_smul T.inClass.isPotentiallyCrystalline hz
      P.exponent)
  rcases a, a' with ⟨⟨a, ha⟩, ⟨a', ha'⟩⟩
  have h_open : IsOpen (k.subgroup : Set Γ) :=
    k.subgroup.isOpen_of_mem_nhds (g := 1)
      ((nearOne_eq_nhds_one hj).ge (k.nearOne_le Subtype.property))
  let b (q : Γ × Γ) : QuotSpan ((p : ℤ_[p]) ^ P.exponent) :=
    P.modPairing (a q.1) (S'.ρ q.1 (a' q.2))
  -- The cocycle `b` is read in `ℚ̄_p^×` as a discrete `Γ`-module, through `zmodPowToUnits`.
  let D : DiscreteModule ℤ Γ :=
    (unitsModule (Gp p) (K := ℚ_[p]) (Ω := PadicAlgCl p)).restrictAlong ⟨toGp, hj.continuous⟩
  -- `b` is locally constant, as all changes near `1` are multiples of `p ^ m`, and is a cocycle.
  have h_cocycle : zmodPowToUnits P.exponent ∘ b ∈ Z2 D.ρ := by
    refine ⟨((iff_eventually_eq _).2 fun q ↦ ?_).continuous, ?_⟩
    · rw [← map_mul_left_nhds_one q]
      refine (((h_dvd ha).and (h_dvd (coboundary_mem (a' q.2)))).prod_nhds (h_dvd ha')).mono ?_
      rintro ⟨g, h⟩ ⟨⟨⟨z, hz⟩, u, hu⟩, z', hz'⟩
      -- `↓`, as the multiples would otherwise become products first.
      simp [b, apply_mul ha, apply_mul ha', hz, hz', eq_add_of_sub_eq hu, ↓nsmul_quot_eq_zero]
    · -- `nsmul_eq_mul` would hide the multiples that `nsmul_zmodPowToUnits` removes.
      simp [D, b, map_cyclotomicGp_smul _ nsmul_zmodPowToUnits, apply_mul ha, apply_mul ha',
        modPairing_rho, Units.smul_def, -nsmul_eq_mul]
  let cls : D.H2 := ⟦⟨zmodPowToUnits P.exponent ∘ b, h_cocycle⟩⟧
  -- Near `1` both `κ h` and `b (g, h)` vanish, so `κ` is locally constant.
  have h_cont : Continuous (zmodPowToUnits P.exponent ∘ κ) := by
    refine (isLocallyConstant_of_eventually_mul
      (.mono (hκ_near.and (continuousAt_subtypeVal (h_dvd ha'))) ?_)).continuous
    rintro h ⟨hκ_zero, z', hz'⟩ g
    have h_eq : κ (g * h) = κ g := by
      simpa [hz', ↓nsmul_quot_eq_zero, hκ_zero, eq_neg_add_iff_add_eq] using h_coboundary g h
    simp [h_eq]
  -- On `k.subgroup` the cocycle is the coboundary of `zmodPowToUnits P.exponent ∘ κ`.
  have h_units (g h : k.subgroup) : zmodPowToUnits P.exponent (b (g, h)) = D.ρ g
    (zmodPowToUnits P.exponent (κ h)) -
      zmodPowToUnits P.exponent (κ (g * h)) + zmodPowToUnits P.exponent (κ g) := by
    simpa [D, b, charRep, map_cyclotomicGp_smul _ nsmul_zmodPowToUnits] using
      congrArg (zmodPowToUnits P.exponent) (h_coboundary g h)
  -- The class restricts to zero on `k.subgroup`, so the index kills it (corestriction).
  have h_index : k.subgroup.index • cls = 0 := by
    have h_res : D.resH2 k.subgroup cls = 0 :=
      (Submodule.Quotient.mk_eq_zero _).2 ⟨_, h_cont, h_units⟩
    exact D.index_smul_eq_zero_of_resH2 ⟨k.subgroup, h_open⟩ h_res
  have h_pow : p ^ P.exponent • cls = 0 := by
    have h_kill : p ^ P.exponent • (⟨_, h_cocycle⟩ : Z2 D.ρ) = 0 := by
      exact Subtype.ext (funext fun q ↦ nsmul_zmodPowToUnits (b q))
    exact congrArg (Quotient.mk _) h_kill
  have h_zero : cls = 0 :=
    (nsmul_eq_zero_iff_of_coprime (k.index_coprime.pow_right _)).1 ⟨h_index, h_pow⟩
  exact Submodule.mem_comap.1 ((Submodule.Quotient.mk_eq_zero _).1 h_zero)

/-- `smul_comm` oriented for `simp`: an element of `FrobGroup Γ` moves inside any commuting
scalar `a`. -/
lemma smul_smul_frobGroup_comm {N M : Type} [SMul N M] [SMul (FrobGroup Γ) M]
    [SMulCommClass (FrobGroup Γ) N M] (n : FrobGroup Γ) (a : N) (z : M) : n • a • z = a • n • z :=
  smul_comm n a z

/-- Specialization of `wittFst_smul` when `x` projects to `p ^ e₁ • (1 ⊗ c)`. -/
private lemma wittFst_smul_of_projTrivial {e₁ : ℕ} {c : S.paramLattice}
    {x : S.extensionLattice.Ambient}
    (hx : S.projTrivial.wittMap x = p ^ e₁ • DiagTensor.mk 1 c) :
    S.wittFst (n • x) = n • S.wittFst x +
      p ^ e₁ • DiagTensor.mk 1 ((S.cocycleMap c).val (FrobGroup.snd n)) := by
  simp [wittFst_smul, hx, smul_smul_frobGroup_comm, extensionRep]

/-- Frobenius commutes with `S.wittFst`. -/
private lemma wittFst_phi_smul (x : S.extensionLattice.Ambient) :
    S.wittFst (φ • x) = φ • S.wittFst x := by
  revert x
  exact diagTensor_induction (by simp)

/-- Near `1` (the filter `nearOne Γ`) the group fixes each element of W(C^♭) ⊗ ℤ/p^m(1) up to an
element of `smallPart m`, the image of W(𝔪^♭). -/
lemma eventually_smul_sub_mem_smallPart {m : ℕ}
    (y : DiagTensor (Rep.of (charRep (QuotSpan ((p : ℤ_[p]) ^ m)) χ))) :
    ∀ᶠ g : Γ in nearOne Γ, inr g • y - y ∈ smallPart m := by
  -- The cyclotomic character is trivial modulo `p ^ m` near `1`.
  have h_crys : IsAdmissible (charRep ℤ_[p] (χ : Γ →* ℤ_[p]ˣ)) (nearOne Γ) :=
    isAdmissible_of_cyclotomicGp_zpow 1 fun g a ↦ by simp [charRep]
  have h_mod (t : Rep.of (charRep (QuotSpan ((p : ℤ_[p]) ^ m)) (χ : Γ →* ℤ_[p]ˣ))) :
      ∀ᶠ g : Γ in nearOne Γ, ∃ w : QuotSpan ((p : ℤ_[p]) ^ m),
        charRep (QuotSpan ((p : ℤ_[p]) ^ m)) χ g t - t = p ^ m • w := by
    obtain ⟨a, rfl⟩ := Ideal.Quotient.mk_surjective t
    filter_upwards [eventually_eq_pow_smul h_crys (coboundary_mem a) m] with g ⟨w, hw⟩
    exact ⟨Ideal.Quotient.mk _ w, congrArg (Ideal.Quotient.mk _) hw⟩
  exact TateTwist.eventually_map_smul_sub_mem_smallPart h_mod LinearMap.id y

/-- A step of the pairing lemma. Let `x`, `w` lie over `p ^ e₁ • c` and `x'`, `w'` over
`p ^ e₂ • c'`, let `B z` be `p ^ e` times the pairing with the component of `z` in Y, and let `y`
solve `(φ - 1) y = B w (φ x' - w') + B x (w' - x')`. If the moves are safe (`h_path`), then for `g`
in `k.subgroup` the value `f g` of the cochain `f` of `hf`, which is corrected by the coboundary
`n • y - y`, is fixed by `φ` up to an element of `smallPart P.exponent`, the image of `W(𝔪^♭)`. -/
lemma Pairing.phi_smul_sub_mem_smallPart {e₁ e₂ : ℕ} {c : S.paramLattice} {c' : S'.paramLattice}
    {x w : S.extensionLattice.Ambient} {x' w' : S'.extensionLattice.Ambient}
    (hx : S.projTrivial.wittMap x = p ^ e₁ • DiagTensor.mk 1 c)
    (hw : S.projTrivial.wittMap w = p ^ e₁ • DiagTensor.mk 1 c)
    (hx' : S'.projTrivial.wittMap x' = p ^ e₂ • DiagTensor.mk 1 c')
    (hw' : S'.projTrivial.wittMap w' = p ^ e₂ • DiagTensor.mk 1 c')
    (h_path : P.IsSafePath e (φ • x) w x (φ • x') w' x')
    (B : S.extensionLattice.Ambient → DiagTensor (Rep.of (overZp S'.ρ)) →ₗ[WittCFlat]
      DiagTensor (Rep.of (charRep (ℤ_[p] ⧸ Ideal.span {(p : ℤ_[p]) ^ P.exponent}) χ)))
    (hB : ∀ z : S.extensionLattice.Ambient, B z = p ^ e • P.wittPairing (S.wittFst z))
    (y : DiagTensor (Rep.of (charRep (ℤ_[p] ⧸ Ideal.span {(p : ℤ_[p]) ^ P.exponent}) χ)))
    (hy : B w (S'.wittFst (φ • x' - w')) + B x (S'.wittFst (w' - x')) = φ • y - y)
    (f : FrobGroup Γ → DiagTensor (Rep.of
      (charRep (ℤ_[p] ⧸ Ideal.span {(p : ℤ_[p]) ^ P.exponent}) χ)))
    (hf : ∀ n : FrobGroup Γ, f n = B (n • x) (n • S'.wittFst x') -
      n • (B x (S'.wittFst x') - y) - B x (S'.wittFst (n • x' - x')) - y) (g : k.subgroup) :
    φ • f (inr (g : Γ)) - f (inr (g : Γ)) ∈ smallPart P.exponent := by
  -- The left side is a signed sum of the pairings of the four safe moves.
  let g₀ : k.galMonoid := ⟨inr (g : Γ), g, rfl⟩
  -- As `g` commutes with `φ`, the defining equation of `y` rewrites the part of `f` that has `y`.
  have h_y : φ • (inr (g : Γ) • y - y) - (inr (g : Γ) • y - y) =
      inr (g : Γ) • (B w (S'.wittFst (φ • x' - w')) + B x (S'.wittFst (w' - x'))) -
        (B w (S'.wittFst (φ • x' - w')) + B x (S'.wittFst (w' - x'))) := by
    rw [hy]
    simp [smul_sub, smul_smul, (commute_phi _).eq]
    abel
  have h_moves : φ • f (inr (g : Γ)) - f (inr (g : Γ)) =
      B (g₀ • w - w) (S'.wittFst (g₀ • (φ • x' - w'))) -
        B (φ • x - w) (S'.wittFst (g₀ • φ • x' - φ • x')) -
        B (w - x) (S'.wittFst (g₀ • w' - w')) + B (g₀ • x - x) (S'.wittFst (g₀ • (w' - x'))) := by
    -- What is left after inserting `h_y` follows from the bilinearity of `B`.
    linear_combination (norm := skip) h_y
    simp +zetaDelta [k.galMonoid.smul_def, hB, hf,
      wittFst_smul_of_projTrivial (inr (g : Γ)) hx, wittFst_smul_of_projTrivial (inr (g : Γ)) hw,
      wittFst_smul_of_projTrivial (inr (g : Γ)) hx', wittFst_smul_of_projTrivial (inr (g : Γ)) hw',
      wittFst_smul_of_projTrivial (inr (g : Γ) * φ) hx', wittFst_phi_smul,
      smul_smul_frobGroup_comm, (commute_phi _).eq, smul_smul, smul_sub, smul_wittPairing,
      sub_eq_zero]
    abel
  rw [h_moves, hB, hB, hB, hB]
  exact add_mem (sub_mem (sub_mem (h_path.isSafeMoveSnd_start g₀) (h_path.isSafeMoveFst_start g₀))
    (h_path.isSafeMoveFst_end g₀))
    (h_path.isSafeMoveSnd_end g₀)

/-- A step of the pairing lemma. Let `x`, `x'` lie over `p ^ e₁ • c`, `p ^ e₂ • c'`, and suppose
that for all `g`, `h` in `Γ'` `p ^ e₃` times the pairing of `g x - x` and `g (h x' - x')` is small
(`IsSafeMoveSnd`). Here `wittFst` takes the component in the lattice Y and `wittPairing` is the
`W(C^♭)`-bilinear extension of `P.modPairing`. Let `B z` be `p ^ e₃` times the pairing with that
component of `z`, let `f` be the corrected cochain of `hf` and `p ^ e = p ^ (e₁ + e₂ + e₃) * r`. If
on `k.subgroup` each `f g` is the constant `1 ⊗ κ g` up to a small element, then on `k.subgroup` the
cup product of `S.cocycleMap c` and `S'.cocycleMap c'`, times `p ^ e`, is `r` times the coboundary
of `κ`. -/
lemma Pairing.nsmul_modPairing_eq_coboundary {e₁ e₂ e₃ r : ℕ} {c : S.paramLattice}
    {c' : S'.paramLattice} {x : S.extensionLattice.Ambient} {x' : S'.extensionLattice.Ambient}
    (hr : p ^ e = p ^ (e₁ + e₂ + e₃) * r)
    (hx : S.projTrivial.wittMap x = p ^ e₁ • DiagTensor.mk 1 c)
    (hx' : S'.projTrivial.wittMap x' = p ^ e₂ • DiagTensor.mk 1 c')
    (h_cocycles : ∀ h : k.galMonoid, P.IsSafeMoveSnd e₃ x (h • x' - x'))
    (B : S.extensionLattice.Ambient → DiagTensor (Rep.of (overZp S'.ρ)) →ₗ[WittCFlat]
      DiagTensor (Rep.of (charRep (ℤ_[p] ⧸ Ideal.span {(p : ℤ_[p]) ^ P.exponent}) χ)))
    (hB : ∀ z : S.extensionLattice.Ambient, B z = p ^ e₃ • P.wittPairing (S.wittFst z))
    (y : DiagTensor (Rep.of (charRep (ℤ_[p] ⧸ Ideal.span {(p : ℤ_[p]) ^ P.exponent}) χ)))
    (f : FrobGroup Γ → DiagTensor (Rep.of
      (charRep (ℤ_[p] ⧸ Ideal.span {(p : ℤ_[p]) ^ P.exponent}) χ)))
    (hf : ∀ n : FrobGroup Γ, f n = B (n • x) (n • S'.wittFst x') -
      n • (B x (S'.wittFst x') - y) - B x (S'.wittFst (n • x' - x')) - y)
    (κ : k.subgroup → QuotSpan ((p : ℤ_[p]) ^ P.exponent))
    (hκ : ∀ g : k.subgroup, f (inr (g : Γ)) - DiagTensor.mk 1 (κ g) ∈ smallPart P.exponent)
    (g h : k.subgroup) :
    p ^ e • P.modPairing ((S.cocycleMap c : Γ → S.Carrier) g)
      (S'.ρ g ((S'.cocycleMap c' : Γ → S'.Carrier) h)) =
      r • (charRep (QuotSpan ((p : ℤ_[p]) ^ P.exponent)) χ (g : Γ) (κ h) - κ (g * h) + κ g) := by
  -- Expand the coboundary of `f`, then replace `f` by the constants `1 ⊗ κ`: the error is a small
  -- constant, so it vanishes.
  have h_cup : DiagTensor.mk 1 (p ^ (e₁ + e₂ + e₃) • P.modPairing ((S.cocycleMap c).val g)
      (S'.ρ g ((S'.cocycleMap c').val h))) =
        B (inr g.val • x - x) (S'.wittFst (inr g.val • (inr h.val • x' - x'))) +
          (inr g.val • f (inr h.val) - f (inr (g * h).val) + f (inr g.val)) := by
    -- `nsmul_eq_mul` would turn the multiples into products before `smul_smul` can collect them.
    simp [hB, hf, wittFst_smul_of_projTrivial _ hx, wittFst_smul_of_projTrivial _ hx',
      smul_smul_frobGroup_comm, apply_mul (S.cocycleMap c).property,
      apply_mul (S'.cocycleMap c').property, pow_add, mul_comm, mul_left_comm, mul_assoc,
      -nsmul_eq_mul, smul_sub, smul_smul, smul_wittPairing]
    abel
  let δ (g : k.subgroup) := f (inr g.val) - DiagTensor.mk 1 (κ g)
  have h_δ : inr g.val • δ h - δ (g * h) + δ g ∈ smallPart P.exponent :=
    add_mem (sub_mem (smul_mem_smallPart g.val (hκ h)) (hκ (g * h))) (hκ g)
  have h_diff : DiagTensor.mk 1 (p ^ (e₁ + e₂ + e₃) • P.modPairing ((S.cocycleMap c).val g)
      (S'.ρ g ((S'.cocycleMap c').val h)) - (charRep _ χ g.val (κ h) - κ (g * h) + κ g)) =
        B (inr g.val • x - x) (S'.wittFst (inr g.val • (inr h.val • x' - x'))) +
          (inr g.val • δ h - δ (g * h) + δ g) := by
    rw [map_sub, h_cup]
    simp [δ, smul_sub]
    abel
  have h_small : B (inr g.val • x - x) (S'.wittFst (inr g.val • (inr h.val • x' - x'))) ∈
      smallPart P.exponent := by
    rw [hB]
    exact h_cocycles ⟨_, h, rfl⟩ ⟨_, g, rfl⟩
  have h_eq : p ^ (e₁ + e₂ + e₃) • P.modPairing ((S.cocycleMap c).val g)
      (S'.ρ g ((S'.cocycleMap c').val h)) = charRep _ χ g.val (κ h) - κ (g * h) + κ g := by
    refine eq_of_sub_eq_zero (TateTwist.eq_zero_of_mk_one_mem_smallPart ?_)
    simpa only [h_diff] using add_mem h_small h_δ
  rw [hr, mul_comm (p ^ (e₁ + e₂ + e₃)) r, mul_smul, h_eq]

/-- The pairing lemma. Let `x`, `w` lie over `p ^ e₁ • c` and `x'`, `w'` over `p ^ e₂ • c'`. Call a
move of one component safe if, with the other at rest, `p ^ e₃` times the pairing of the moved part
with the change of the other under each `g` in `Γ'` lies in the image of `W(𝔪^♭)`. Assume that the
moves by `h x' - x'`, `h` in `Γ'`, are safe with `x` at rest, and that four safe moves lead from
`(φ x, φ x')` by `w` and `w'` to `(x, x')` (`IsSafePath`). Then, for `e ≥ e₁ + e₂ + e₃` and any
topology on `Γ` for which `Γ → G_p` is an open embedding, the cup product of the cocycles
`S.cocycleMap c` and `p ^ e • S'.cocycleMap c'`, read in ℚ̄_p^×, is a coboundary. -/
lemma Pairing.IsScaledCupCoboundary.of_isSafePath {e₁ e₂ e₃ : ℕ} {c : S.paramLattice}
    {c' : S'.paramLattice}
    (x w : S.extensionLattice.Ambient) (x' w' : S'.extensionLattice.Ambient) (he : e₁ + e₂ + e₃ ≤ e)
    (hx : S.projTrivial.wittMap x = p ^ e₁ • DiagTensor.mk 1 c)
    (hw : S.projTrivial.wittMap w = p ^ e₁ • DiagTensor.mk 1 c)
    (hx' : S'.projTrivial.wittMap x' = p ^ e₂ • DiagTensor.mk 1 c')
    (hw' : S'.projTrivial.wittMap w' = p ^ e₂ • DiagTensor.mk 1 c')
    (h_cocycles : ∀ h : k.galMonoid, P.IsSafeMoveSnd e₃ x (h • x' - x'))
    (h_path : P.IsSafePath e₃ (φ • x) w x (φ • x') w' x') :
    P.IsScaledCupCoboundary e c c' := by
  -- Solve `(φ - 1) y = B w (φ x' - w') + B x (w' - x')` and correct the natural cochain by `y` to
  -- get `f`. The safe moves make `(φ - 1) (f g)` small, so `f g ≡ κ g ∈ ℤ/p^m(1)`, and on
  -- `k.subgroup` the cup product of `S.cocycleMap c` and `p ^ e • S'.cocycleMap c'` is a multiple
  -- of the coboundary of `κ`.
  -- By definition, the conclusion is about each topology on `Γ` with `Γ → G_p` an open embedding.
  intro (topΓ : TopologicalSpace Γ) (hj : IsOpenEmbedding Γ.overGp.toGp)
  obtain ⟨r, hr⟩ : p ^ (e₁ + e₂ + e₃) ∣ p ^ e := pow_dvd_pow p he
  let B (y : S.extensionLattice.Ambient) := p ^ e₃ • P.wittPairing (S.wittFst y)
  have h_dvd {T : PairingSide O} {z : Γ → T.Carrier} (hz : z ∈ crysCocycles T.ρ) :
      ∀ᶠ g in nearOne Γ, ∃ v : T.Carrier, z g = p ^ P.exponent • v :=
    eventually_eq_pow_smul T.inClass.isPotentiallyCrystalline hz P.exponent
  obtain ⟨y, hy⟩ : ∃ y, B w (S'.wittFst (φ • x' - w')) + B x (S'.wittFst (w' - x')) = φ • y - y :=
    TateTwist.exists_eq_phi_smul_sub _
  let f (n : FrobGroup Γ) := B (n • x) (n • S'.wittFst x') - n • (B x (S'.wittFst x') - y) -
    B x (S'.wittFst (n • x' - x')) - y
  -- As `(φ - 1) (f g)` is small, `f g` is a constant `1 ⊗ κ g` up to a small element.
  have h_const (g : k.subgroup) : ∃ t : QuotSpan ((p : ℤ_[p]) ^ P.exponent),
      f (inr (g : Γ)) - DiagTensor.mk 1 t ∈ smallPart P.exponent :=
    TateTwist.exists_sub_mk_one_mem_smallPart_of_phi_smul_sub_mem <|
      P.phi_smul_sub_mem_smallPart hx hw hx' hw' h_path B (fun _ ↦ rfl) y hy f (fun _ ↦ rfl) g
  choose κ hκ using h_const
  have h_coboundary (g h : k.subgroup) : P.modPairing ((S.cocycleMap c).val g)
    (S'.ρ g ((p ^ e • S'.cocycleMap c').val h)) =
      charRep _ χ g.val ((r • κ) h) - (r • κ) (g * h) + (r • κ) g := by
    simpa [smul_sub, -nsmul_eq_mul] using P.nsmul_modPairing_eq_coboundary hr hx hx' h_cocycles
      B (fun _ ↦ rfl) y f (fun _ ↦ rfl) κ hκ g h
  have h_smallB : ∀ᶠ g : Γ in nearOne Γ,
      B x (inr g • S'.wittFst x' - S'.wittFst x') ∈ smallPart P.exponent :=
    TateTwist.eventually_map_smul_sub_mem_smallPart (fun y ↦ h_dvd (coboundary_mem y)) (B x) _
  have h_restrict {Q : Γ → Prop} (hQ : ∀ᶠ g in nearOne Γ, Q g) :
      ∀ᶠ h : k.subgroup in 𝓝 1, Q h :=
    continuousAt_subtypeVal ((nearOne_eq_nhds_one hj).ge hQ)
  -- Near `1` the cochain `f` is small, so `κ` vanishes.
  have hκ_near : ∀ᶠ h : k.subgroup in 𝓝 1, (r • κ) h = 0 := by
    filter_upwards [h_restrict (h_dvd (S.cocycleMap c).property),
      h_restrict (h_dvd (S'.cocycleMap c').property), h_restrict h_smallB,
      h_restrict (eventually_smul_sub_mem_smallPart y)] with h ⟨z, hz⟩ ⟨z', hz'⟩ hB hy'
    -- The cocycle terms are multiples of `p ^ m`, which kills the target of `B x`.
    have h_f : f (inr h.val) = inr h.val • y - y -
        B x (inr h.val • S'.wittFst x' - S'.wittFst x') := by
      simp +zetaDelta [wittFst_smul_of_projTrivial _ hx, wittFst_smul_of_projTrivial _ hx',
        smul_smul_frobGroup_comm, hz, hz', TateTwist.pow_smul_eq_zero, smul_sub, smul_wittPairing]
      abel
    have hf_small : f (inr h.val) ∈ smallPart P.exponent := by
      simpa only [h_f] using sub_mem hy' hB
    have h_small : DiagTensor.mk 1 (κ h) ∈ smallPart P.exponent := by
      simpa using sub_mem hf_small (hκ h)
    simp [TateTwist.eq_zero_of_mk_one_mem_smallPart h_small]
  exact P.isCupCoboundary_of_eq_coboundary hj (S.cocycleMap c) (p ^ e • S'.cocycleMap c') (r • κ)
    hκ_near h_coboundary

end New.Lift

/-!
## Elements p^κ E^s killing the cokernel on Kisin modules

The tool is that the operators α (g − 1)/zτ, with g ∈ Γ' and τ the element `tau` of A_inf, preserve
the ideals J_l(i) (`New.Lift.KummerChart.PairingSide.mem_liftIdeal_of_eq_zTau_mul_smul_sub`), and
that at level one they may also be divided by E
(`New.Lift.KummerChart.PairingSide.mem_liftIdeal_of_eq_mul_smul_sub`). One works modulo p^{κ+1} and
drops the modulus by Nakayama's lemma
(`New.Lift.KummerChart.PairingSide.liftIdeal_le_of_p_pow_mem`). Here `k.letterFrob` is i ↦ i^p, and
`L.withOrders i (stdOrders l)` is the letter-i part of A_inf·φ^{l*}N
(`New.Lift.KummerChart.JumpLattice.mem_withOrders_stdOrders_iff`).
-/

namespace New.Lift.KummerChart

open Period Submodule FrobGroup Ideal JumpLattice

/-- The count of factors `p` in the cokernel bound with weights, for a prime `p`. Let
`c ≤ J (d ω' + v_p(ω'!))`, `n ≤ a / p ^ J + ω' / (p - 1)`, `(p - 1) a ≤ e (ω + κ)` and
`8 e ≤ p ^ (J + 1)`. If `κ ≥ 2 J d ω' + (2 J + 4) ω' / (p - 1) + 8 e ω / p ^ (J + 1)`, then
`c + n + v_p(n!) ≤ κ`. -/
lemma PairingSide.add_add_padicValNat_factorial_le {p : ℕ} [Fact p.Prime]
    {J d e ω ω' κ a c n : ℕ} (hc_le : c ≤ J * (d * ω' + padicValNat p ω'.factorial))
    (hn_le : (n : ℝ) ≤ a / p ^ J + ω' / (p - 1)) (ha_le : (p - 1) * a ≤ e * (ω + κ))
    (h_ram : 8 * e ≤ p ^ (J + 1))
    (hκ : (2 * J * d * ω' : ℝ) + (2 * J + 4) * ω' / (p - 1) + 8 * e * ω / p ^ (J + 1) ≤ κ) :
    c + n + padicValNat p n.factorial ≤ κ := by
  -- The sum is at most `J (d ω' + ω' / (p - 1)) + 2 n`, and
  -- `a / p ^ J ≤ 2 e ω / p ^ (J + 1) + κ / 4`.
  have hp_two : 2 ≤ p := (Fact.out : p.Prime).two_le
  have h_legendre : (padicValNat p ω'.factorial : ℝ) ≤ ω' / (p - 1) := by
    rw [le_div_iff₀' (sub_pos.2 (mod_cast hp_two)), ← Nat.cast_pred (by omega),
      Nat.padicValNat_def]
    exact_mod_cast (Nat.Prime.sub_one_mul_multiplicity_factorial (n := ω') Fact.out).trans_le
      (Nat.sub_le _ _)
  have h_steps : (c : ℝ) ≤ J * (d * ω' + ω' / (p - 1)) := by
    grw [← h_legendre]
    exact_mod_cast hc_le
  have h_removal : (padicValNat p n.factorial : ℝ) ≤ n := by
    rw [Nat.padicValNat_def]; exact_mod_cast multiplicity_factorial_le p n
  have h_double : p * a ≤ 2 * e * (ω + κ) :=
    calc p * a ≤ 2 * (p - 1) * a := Nat.mul_le_mul_right a (by omega)
      _ ≤ 2 * e * (ω + κ) := by linarith
  have h_start : (a : ℝ) / p ^ J ≤ 2 * e * ω / p ^ (J + 1) + κ / 4 :=
    calc (a : ℝ) / p ^ J = p * a / p ^ (J + 1) := by field
      _ ≤ 2 * e * (ω + κ) / p ^ (J + 1) := by
        gcongr ?_ / _
        exact_mod_cast h_double
      _ = 2 * e * ω / p ^ (J + 1) + 8 * e / p ^ (J + 1) * (κ / 4) := by ring
      _ ≤ 2 * e * ω / p ^ (J + 1) + κ / 4 := by
        grw [div_le_one_of_le₀ (a := (8 * e : ℝ)) (mod_cast h_ram) (by positivity), one_mul]
  exact_mod_cast calc (c : ℝ) + n + padicValNat p n.factorial
      ≤ J * (d * ω' + ω' / (p - 1)) +
          2 * (2 * e * ω / p ^ (J + 1) + κ / 4 + ω' / (p - 1)) := by linarith
    _ = (2 * J * d * ω' + (2 * J + 4) * ω' / (p - 1) + 8 * e * ω / p ^ (J + 1)) / 2 +
          κ / 2 := by ring
    _ ≤ κ := by linarith

variable {p : ℕ} [ThePrime p] [Γ : GroupOverGp p] {k : KummerChart Γ} {O : Coeffs}

/-- Let `Γ` act on the lattice `L` through the power `χ ^ c` of the cyclotomic character, and let
`i` be a letter, a unit of the field with `p ^ k.f` elements. Let `x` have the standard orders of
level `0` at `i`; equivalently, `x` lies in the letter-`i` part of `W(C^♭) ⊗ L` and in
`L.kisinAinf`, the `y` in `A_inf[1/τ] ⊗ L` with `μ (φ ^ n • y)` in `B_dR^+` for all `n ≥ 1` and all
`Γ'`-equivariant forms `μ` (`L.forms`). Then `tau ^ c • x` lies in `L.ainfLattice`, the lattice
`A_inf ⊗ L`. Here `τ = tau` is the element `[ε^{1/p}] − 1` of `A_inf`. -/
lemma JumpLattice.tau_pow_smul_mem_ainfLattice_of_eq_chi_pow_smul {L : JumpLattice O} (c : ℕ)
    {x : L.Ambient} {i : Letter} (hx : x ∈ L.withOrders i (stdOrders 0))
    (h_action : ∀ (g : Γ) (t : L.Carrier), L.ρ g t = χ g ^ (c : ℤ) • t) :
    tau ^ c • x ∈ L.ainfLattice := by
  -- The only jump of `χ ^ c` is `-c`, so the height is at most `c`; and `frame_theorem` gives
  -- `tau ^ L.jumpBound • L.kisinAinf ⊆ L.ainfLattice`.
  have h_height : L.jumpBound ≤ c := Nat.sInf_le <| by
    simp [hasJumps_of_cyclotomicGp_zpow c _ _, h_action, Units.smul_def, Multiset.mem_replicate]
  have h_tau : ∀ y ∈ L.kisinAinf, tau ^ L.jumpBound • y ∈ L.ainfLattice :=
    frame_theorem.tau_pow_smul_mem_ainfLattice
  rw [← Nat.sub_add_cancel h_height, pow_add, mul_smul]
  exact smul_mem _ _ (h_tau x (frobKisinAinf_zero.le (mem_withOrders_stdOrders_iff.1 hx).1))

/-- On a Kummer chart `k` of `Γ` with ring `𝔖 = k.S ⊂ A_inf`, let `L` be a lattice over the
coefficient ring `O` on which all of `Γ` acts trivially. Its Kisin module is `𝔖 ⊗ L`: the
`k.S`-span of the vectors `1 ⊗ t`. -/
lemma JumpLattice.kisinModule_eq_span_of_trivial {L : JumpLattice O}
    (h_triv : ∀ (g : Γ) (t : L.Carrier), L.ρ g t = t) :
    L.kisinModule = Submodule.span k.S (Set.range (DiagTensor.mk 1)) := by
  -- Each `1 ⊗ t` is invariant, so forms take values in `hodgeFil 0` and in `valueField 0` on it.
  have h_mk (t : L.Carrier) : DiagTensor.mk 1 t ∈ L.kisinModule := by
    have h_fixed (μ : L.Functional) (hμ : μ ∈ L.forms) :
        μ (DiagTensor.mk 1 t) ∈ hodgeFil 0 ∧ μ (DiagTensor.mk 1 t) ∈ valueField 0 :=
      mem_hodgeFil_zero_and_mem_valueField_zero_of_fixed fun g ↦ by simpa [h_triv] using hμ t g
    have h_saturate : DiagTensor.mk 1 t ∈ saturateBy (Submonoid.powers tau) L.ainfLattice :=
      mem_saturateBy_of_mem (mk_one_mem_ainfLattice t)
    have h_forms (n : ℕ) (μ : L.Functional) (hμ : μ ∈ L.forms) :
        μ (φ ^ (n + 1) • DiagTensor.mk 1 t) ∈ hodgeFil 0 := by
      simpa [h_triv] using (h_fixed μ hμ).1
    -- So `1 ⊗ t` lies in `kisinAinf`, and forms take values in `valueField 0` on it.
    exact ⟨⟨h_saturate, h_forms⟩, fun μ hμ ↦ (h_fixed μ hμ).2⟩
  refine le_antisymm (fun x hx ↦ ?_) (Submodule.span_le.2 (Set.range_subset_iff.2 h_mk))
  -- The height is `0`, so `x` lies in `A_inf ⊗ L`. The retraction `coordRetract` fixes `x` and
  -- replaces each coefficient `a` by `k.coord₀ a ∈ k.S`.
  have h_lat : x ∈ L.ainfLattice := by
    rw [← L.sum_letterProj x]
    refine sum_mem fun i _ ↦ ?_
    have h_std : L.letterProj i x ∈ L.withOrders i (stdOrders 0) :=
      letterProj_mem_withOrders (frobKisinAinf_zero.ge hx.1)
    simpa using tau_pow_smul_mem_ainfLattice_of_eq_chi_pow_smul 0 h_std (by simp [h_triv])
  rw [ainfLattice_eq_span_basis] at h_lat
  let v (j : Fin (Module.finrank ℤ_[p] L.Carrier)) : L.Ambient :=
    DiagTensor.mk 1 (Module.finBasis ℤ_[p] L.Carrier j)
  obtain ⟨a, h_sum : ∑ j, a j • v j = x⟩ := (Submodule.mem_span_range_iff_exists_fun Ainf).1 h_lat
  have hx_loc : x ∈ L.kisinLoc := hx.imp_left mem_saturateBy_of_mem
  have h_retract : x = ∑ j, k.coord₀ (a j) • v j :=
    (coordRetract_of_mem_kisinLoc hx_loc hx_loc.1).symm.trans
      (coordRetract_sum (fun _ ↦ (h_mk _).imp_left mem_saturateBy_of_mem) h_sum)
  rw [h_retract]
  exact sum_mem fun j _ ↦ smul_mem _ _ (Submodule.subset_span (Set.mem_range_self _))

/-- In a commutative ring, let `s * E ^ n` and `q ^ (κ + 1)` lie in an ideal `I`. Then
`s * (u * E + v * q) ^ (n + κ)` lies in `I`: each monomial `E ^ a * q ^ b` with
`a + b = n + κ` has `a ≥ n` or `b ≥ κ + 1`. -/
lemma mul_add_pow_mem_of_mul_pow_mem {R : Type*} [CommRing R] {I : Ideal R} {s E q u v : R}
    {n κ : ℕ} (hE : s * E ^ n ∈ I) (hq : q ^ (κ + 1) ∈ I) : s * (u * E + v * q) ^ (n + κ) ∈ I := by
  have hE_colon : (u * E) ^ n ∈ I.colon {s} := by
    simpa [mem_colon_singleton, mul_pow, mul_assoc, mul_comm s] using I.mul_mem_left (u ^ n) hE
  have hq_colon : (v * q) ^ (κ + 1) ∈ I.colon {s} := by
    simpa [mem_colon_singleton, mul_pow] using I.mul_mem_right s (I.mul_mem_left (v ^ (κ + 1)) hq)
  simpa [mem_colon_singleton, mul_comm] using
    Ideal.add_pow_mem_of_pow_mem_of_le _ hE_colon hq_colon (k := n + κ) (by omega)

namespace PairingSide

section

variable (S : PairingSide O) (r l : ℕ) (i : Letter)

/-- For c in the lattice C and a letter i, the image of 1⊗c, in the ambient module of the trivial
lattice, under the projector to the letter i. -/
def constantAt : S.paramLattice →ₗ[ℤ_[p]] S.trivialLattice.Ambient :=
  (S.trivialLattice.letterProj i).restrictScalars ℤ_[p] ∘ₗ
    DiagTensor.mk (ρ := Rep.of (overZp S.trivialLattice.ρ)) 1

/-- The ideal J_l(i) of A_inf generated by r and the elements a of A_inf that multiply the letter-i
part of A_inf ⊗ C into the image of the extension's module of standard exponents of level l. -/
def liftIdeal : Ideal Ainf :=
  Ideal.span {↑r} ⊔ (S.extensionLattice.withOrders i (stdOrders l)
    |>.map (S.projTrivial.wittMap.restrictScalars Ainf)
    |>.colon (S.trivialLattice.ainfLattice.map
      ((S.trivialLattice.letterProj i).restrictScalars Ainf)))

/-- p^κE^s kills the cokernel at the letter i: it multiplies the letter-i part of A_inf ⊗ C into
the image of the extension's module of standard exponents of level 0. -/
def KillsCokernel (κ s : ℕ) : Prop := ↑(p ^ κ * k.E ^ s) ∈ S.liftIdeal 0 0 i

end

/-- s lies in `New.Lift.KummerChart.PairingSide.liftIdeal` iff for some t in A_inf and every c in C,
(s − rt) times the letter-i part of 1⊗c lifts to an element with the standard exponents of level l
at i of the extension `S.extensionLattice` of C by Y, along the projection `S.projTrivial.wittMap`
from W(C^♭) ⊗ (Y × C) to W(C^♭) ⊗ C. -/
lemma mem_liftIdeal_iff {S : PairingSide O} {r l : ℕ} {i : Letter} {s : Ainf} :
    s ∈ S.liftIdeal r l i ↔
    ∃ t : Ainf, ∀ c : S.paramLattice.Carrier, ∃ x ∈ S.extensionLattice.withOrders i (stdOrders l),
      S.projTrivial.wittMap x = (s - r • t) • S.constantAt i c := by
  simp [liftIdeal, ainfLattice, Submodule.map_span, mem_span_singleton_sup, mem_colon,
    ← eq_sub_iff_add_eq', mul_comm, constantAt]

/-- The ideal `S.liftIdeal r l i` contains its modulus `r`; this is the case `r = p ^ κ`. -/
lemma p_pow_mem_liftIdeal_self {S : PairingSide O} {l : ℕ} {i : Letter} {κ : ℕ} :
    (p : Ainf) ^ κ ∈ S.liftIdeal (p ^ κ) l i :=
  Ideal.mem_sup_left (by simp)

/-- The `l`-th power of Frobenius sends the constant of `c ∈ C` at the letter `i` to its constant at
the letter `σ^l(i) = i ^ (p ^ l)`, where σ is `k.letterFrob`. -/
lemma phi_pow_smul_constantAt {S : PairingSide O} {l : ℕ} {i : Letter}
    (c : S.paramLattice.Carrier) :
    φ ^ l • S.constantAt i c = S.constantAt ((k.letterFrob ^ l) i) c := by
  simp [constantAt, smul_letterProj phi_pow_smul_letterTeich]

/-- Going up a level: suppose `s` lies in `S.liftIdeal r 0 i` and all elements of `S.jumpSet i` are
at most `n`. Then `s * E ^ n` lies in `S.liftIdeal r 1 i`. -/
lemma mul_E_pow_mem_liftIdeal_one {S : PairingSide O} {r : ℕ} {i : Letter} {n : ℕ} {s : Ainf}
    (h_mem : s ∈ S.liftIdeal r 0 i) (hn : ∀ u ∈ S.jumpSet i, u ≤ n) :
    s * k.E ^ n ∈ S.liftIdeal r 1 i := by
  obtain ⟨t, ht⟩ : ∃ t : Ainf, ∀ c : S.paramLattice.Carrier,
      ∃ x ∈ S.extensionLattice.withOrders i (stdOrders 0),
        S.projTrivial.wittMap x = (s - r • t) • S.constantAt i c :=
    mem_liftIdeal_iff.1 h_mem
  choose x hx hx_pr using ht
  -- Multiply the lifts by `E ^ n`: at `a = 0` the exponent `-u` rises to `n - u ≥ 0`.
  refine mem_liftIdeal_iff.2 ⟨t * k.E ^ n, fun c ↦
    ⟨k.frobEUnit 0 ^ (n : ℤ) • x c, frobEUnit_zpow_smul_mem_withOrders 0 n (hx c) ?_, ?_⟩⟩
  · rintro (_ | a) <;> simp +contextual [hn, stdOrders]
  · simp [frobEUnit_pow_smul, hx_pr, Chart.frobE]
    module

/-- Nakayama step: if p^c lies in the ideal J_l(i) with modulus p^{c+1}
(`New.Lift.KummerChart.PairingSide.liftIdeal`), then this ideal is contained in J_l(i) with modulus
0, the ideal of multipliers that lift constants exactly. -/
lemma liftIdeal_le_of_p_pow_mem {S : PairingSide O} {l : ℕ} {i : Letter} {c : ℕ}
    (h_mem : (p : Ainf) ^ c ∈ S.liftIdeal (p ^ (c + 1)) l i) :
    S.liftIdeal (p ^ (c + 1)) l i ≤ S.liftIdeal 0 l i := by
  -- `h_mem` puts the ideal `(p ^ c)` in `S.liftIdeal 0 l i ⊔ (p) * (p ^ c)`. As `p` lies in the
  -- Jacobson radical, Nakayama's lemma puts `(p) * (p ^ c) = (p ^ (c + 1))` in `S.liftIdeal 0 l i`.
  have h_split : S.liftIdeal (p ^ (c + 1)) l i =
      S.liftIdeal 0 l i ⊔ span {(p : Ainf)} • span {(p : Ainf) ^ c} := by
    simp [liftIdeal, sup_comm, span_singleton_mul_span_singleton, pow_succ']
  rw [h_split] at h_mem ⊢
  exact sup_le le_rfl (smul_le_of_le_smul_of_le_jacobson (fg_span_singleton _)
    (IsAdicComplete.le_jacobson _) (by simpa using h_mem))

/-- Nakayama at one letter: if `p ^ κ` lies in `S.liftIdeal (p ^ (κ + 1)) 0 i`, then `p ^ κ` kills
the cokernel at `i`. -/
lemma killsCokernel_of_p_pow_mem_liftIdeal {S : PairingSide O} {κ : ℕ} {i : Letter}
    (h_mem : (p : Ainf) ^ κ ∈ S.liftIdeal (p ^ (κ + 1)) 0 i) : S.KillsCokernel i κ 0 := by
  simpa [KillsCokernel] using liftIdeal_le_of_p_pow_mem h_mem h_mem

/-! ### Frobenius and the ideals -/

/-- The constant of c ∈ C at the letter i lies in the Kisin module of the trivial lattice C with all
φ^a E inverted, and has exponents `New.Lift.KummerChart.stdOrders` l at i. -/
lemma constantAt_mem_stdOrdersPart {S : PairingSide O} {l : ℕ} {i : Letter}
    (c : S.paramLattice.Carrier) :
    S.constantAt i c ∈ S.trivialLattice.stdOrdersPart l i := by
  -- The element `1 ⊗ c` lies in the Kisin module of the trivial lattice and is fixed by Frobenius.
  obtain ⟨h_mem, h_value⟩ : DiagTensor.mk 1 c ∈ S.trivialLattice.kisinModule :=
    (kisinModule_eq_span_of_trivial fun _ _ ↦ rfl).ge (Submodule.subset_span ⟨c, rfl⟩)
  exact letterProj_mem_stdOrdersPart ⟨by simpa [frobKisinAinf] using h_mem, h_value⟩

/-- For every modulus `r`, the element `φ ^ l • s` lies in `S.liftIdeal r l` at the letter
`(k.letterFrob ^ l) i = i ^ p ^ l` iff `s` lies in `S.liftIdeal r 0 i`. -/
lemma phi_pow_smul_mem_liftIdeal_iff {S : PairingSide O} {r : ℕ} {i : Letter} {s : Ainf} (l : ℕ) :
    φ ^ l • s ∈ S.liftIdeal r l ((k.letterFrob ^ l) i) ↔ s ∈ S.liftIdeal r 0 i := by
  -- `φ ^ l` carries the letter and the standard exponents at level 0 to those at level `l`.
  have h_std (x : S.extensionLattice.Ambient) :
      φ ^ l • x ∈ S.extensionLattice.withOrders ((k.letterFrob ^ l) i) (stdOrders l) ↔
        x ∈ S.extensionLattice.withOrders i (stdOrders 0) := by
    simp [mem_withOrders_stdOrders_iff, frobKisinAinf, phi_pow_smul_mem_letterPart_iff]
  -- `φ ^ l` also carries the defining equation of a lift from the letter `i` to the new letter.
  have h_lift (t : Ainf) (c : S.paramLattice.Carrier) (x : S.extensionLattice.Ambient) :
      S.projTrivial.wittMap (φ ^ l • x) =
          (φ ^ l • s - r • φ ^ l • t) • S.constantAt ((k.letterFrob ^ l) i) c ↔
        S.projTrivial.wittMap x = (s - r • t) • S.constantAt i c := by
    simp [smul_left_cancel_iff, ← phi_pow_smul_constantAt, smul_comm r, ← smul_sub,
      ← frobGroup_smul_smul, -nsmul_eq_mul]
  -- So substitute `φ ^ l • t` for the witness at level `l` and `φ ^ l • x` for each lift.
  rw [mem_liftIdeal_iff, mem_liftIdeal_iff, (MulAction.surjective (φ ^ l)).exists]
  refine exists_congr fun t ↦ forall_congr' fun c ↦ ?_
  rw [(MulAction.surjective (φ ^ l)).exists]
  simp only [h_std, h_lift]

/-- For the letters `i` and `σ(i) = k.letterFrob i` and the coordinate `z = k.z`, the element
`p ^ c * z ^ (p * a)` lies in the ideal `S.liftIdeal r 1 σ(i)` iff `p ^ c * z ^ a` lies in
`S.liftIdeal r 0 i`. -/
lemma p_pow_mul_z_pow_mem_liftIdeal_iff {S : PairingSide O} {r : ℕ} {i : Letter} {a c : ℕ} :
    (p : Ainf) ^ c * (k.z : Ainf) ^ (p * a) ∈ S.liftIdeal r 1 (k.letterFrob i) ↔
      (p : Ainf) ^ c * (k.z : Ainf) ^ a ∈ S.liftIdeal r 0 i := by
  have h_frob : φ ^ 1 • (p ^ c * k.z.val ^ a : Ainf) = p ^ c * k.z.val ^ (p * a) := by
    simp [↓phi_pow_smul_z, ↓smul_mul', ↓smul_pow', pow_mul]
  rw [← h_frob, ← phi_pow_smul_mem_liftIdeal_iff 1, pow_one k.letterFrob]

/-- Let S be a side with parameter lattice C, and let f in the ring `k.S` of the Kummer chart lie in
the ideal J_l(i) with modulus r. For some t in `k.S`, (f − rt)y lifts along `S.projTrivial.wittMap`,
for every y in `S.trivialLattice.stdOrdersPart l i` (the elements of `kisinLoc`, the Kisin module
with all φ^a E inverted, with the standard exponents of level l at i), to an element of
`S.extensionLattice.stdOrdersPart l i`. -/
lemma exists_lift_of_mem_liftIdeal {S : PairingSide O} {r l : ℕ} {i : Letter} {f : k.S}
    (h_mem : (f : Ainf) ∈ S.liftIdeal r l i) :
    ∃ t : k.S, ∀ y ∈ S.trivialLattice.stdOrdersPart l i, ∃ x ∈ S.extensionLattice.stdOrdersPart l i,
      S.projTrivial.wittMap x = (f - r • t).val • y := by
  -- Write `f = t * r + s` with `s` an exact multiplier and lift `s • y`. The retraction
  -- `coordRetract`, induced by the `k.S`-linear map `k.coord₀ : Ainf → k.S`, sends `a • x` to
  -- `k.coord₀ a • x` for `x` in `kisinLoc`; apply it to the lift.
  obtain ⟨t, s, hs, hf : t * r + s = f⟩ := mem_span_singleton_sup.1 h_mem
  refine ⟨k.coord₀ t, fun y ⟨hy_loc, hy_exp⟩ ↦ ?_⟩
  -- The action on `S.trivialLattice` is trivial, so `y` lies in the lattice.
  have hy_std : y ∈ S.trivialLattice.withOrders i (stdOrders 0) :=
    mem_withOrders_of_le hy_exp (by grind)
  have hy_lat : y ∈ S.trivialLattice.ainfLattice := by
    simpa using tau_pow_smul_mem_ainfLattice_of_eq_chi_pow_smul 0 hy_std (by simp)
  have hy_proj : S.trivialLattice.letterProj i y = y :=
    mem_letterPart_iff_letterProj.1 (mem_withOrders_iff.1 hy_exp).2.1
  obtain ⟨x, hx, hx_pr⟩ : ∃ x ∈ S.extensionLattice.withOrders i (stdOrders l),
      S.projTrivial.wittMap x = s • y :=
    hs ⟨y, ⟨y, hy_lat, hy_proj⟩, rfl⟩
  refine ⟨coordRetract ⟨x, (mem_withOrders_iff.1 hx).1⟩,
    ⟨coe_mem _, coordRetract_mem_withOrders _ hx⟩, ?_⟩
  calc S.projTrivial.wittMap (coordRetract _).val
      = (coordRetract ⟨s • y, smul_mem _ s hy_loc.1⟩).val :=
        S.projTrivial.wittMap_coordRetract _ _ hx_pr
    _ = k.coord₀ s • y := coordRetract_smul s hy_loc _
    _ = (f - r • k.coord₀ t) • y := by
      simp [mul_comm t, eq_sub_of_add_eq' hf, k.coord₀_coe, ← nsmul_eq_mul]

/-- Let `x` lie in the Kisin module of the extension with all `φ^a E` inverted and have the standard
orders of level one at the letter `i`, that is at least `0` at `a = 0` and `-u` at `a ≥ 1`. Then for
`g` in `Γ'` the difference `g x - x` has exponent at least `1` at `a = 0` and at least `-u` at
`a ≥ 1`. An order is prescribed at `φ^a E` for each jump `u` in the jump set
`S.jumpSet (i.stepBack a)` at the letter whose `p ^ a`-th power is `i`. -/
lemma smul_sub_mem_withOrders_of_stdOrders_one {S : PairingSide O} {i : Letter}
    {x : S.extensionLattice.Ambient} (hx_loc : x ∈ S.extensionLattice.kisinLoc)
    (hx_exp : x ∈ S.extensionLattice.withOrders i (stdOrders 1)) (g : k.galMonoid) :
    g • x - x ∈ S.extensionLattice.withOrders i fun (a : ℕ) (u : ℤ) ↦ if a < 1 then 1 else -u := by
  obtain ⟨hx_span, -, hx_val : ∀ a : ℕ, ∀ u ∈ S.extensionLattice.jumpSet (i.stepBack a),
      ∀ μ ∈ S.extensionLattice.formsOfType (i.stepBack a) u,
        valueAt a μ x ∈ hodgeFil (stdOrders 1 a u)⟩ := mem_withOrders_iff.1 hx_exp
  refine mem_withOrders_of_mem_hodgeFil (smul_sub_mem_withOrders hx_exp g) ?_
  rintro (_ | a) u hu h_lt μ hμ
  · -- The value of `x` lies in `valueField 0` and in `hodgeFil 0`, on which `g` is trivial modulo
    -- `hodgeFil 1` because `g` is trivial on `k.S` modulo `E`.
    have h_field : valueAt 0 μ x ∈ valueField 0 := valueAt_mem_valueField hμ.1 hx_loc
    have h_dvd (s : k.S) : (k.E : Ainf) ∣ g • s - s :=
      dvd_of_mul_left_dvd (zTau_mul_E_dvd_smul_sub g s)
    have h_gain : g • valueAt 0 μ x - valueAt 0 μ x ∈ hodgeFil 1 := by
      simpa using smul_sub_mem_hodgeFil_of_valueField g ![1] h_field (hx_val 0 u hu μ hμ)
        (by simpa [Chart.frobE] using h_dvd)
    rwa [valueAt_smul_sub hx_span hμ.1]
  · -- At `a ≥ 1` the exponent is not raised.
    simp [stdOrders] at h_lt

/-- At level one the standard exponents allow one division by `E`: `stdOrders 1 a u` is at most
`(if a < 1 then 1 else -u)` lowered by `1` at `a = 0`. That is, the exponents raised by one at
`a = 0` and then lowered by one there are at least the standard exponents. -/
lemma stdOrders_one_le_add (a : ℕ) (u : ℤ) :
    stdOrders 1 a u ≤ (if a < 1 then 1 else -u) + if 0 = a then -1 else 0 := by
  cases a <;> simp [stdOrders]

/-- An operator `α (g - 1) / d` preserves the ideals. Let `g` lie in `Γ'`, the subgroup of the
Kummer chart `k`, and let multiplication by `d` in `Ainf` be injective on `W(C^♭) ⊗ S.paramLattice`,
the ambient module of `S.trivialLattice`. Let `d` divide `g t - t` for all `t` in the ring `k.S`.
For all `x` in `S.extensionLattice.stdOrdersPart l i` let `g x - x` be `d` times an element of
`withOrders i (stdOrders l)`: this is the `Ainf`-module of elements with the standard orders of
level `l` at the letter `i`, and `stdOrdersPart l i` its `k.S`-submodule in the Kisin module with
all `φ^a E` inverted. If `f` in `k.S` lies in `S.liftIdeal r l i` and `d s = α (g f - f)`, then `s`
lies in the same ideal. -/
lemma mem_liftIdeal_of_mul_eq_mul_smul_sub {S : PairingSide O} {r l : ℕ} {i : Letter} {f : k.S}
    {d s : Ainf} (α : Ainf) (g : k.galMonoid) (hd : IsSMulRegular S.trivialLattice.Ambient d)
    (h_dvd : ∀ t : k.S, d ∣ g • t - t)
    (h_div_orders : ∀ x ∈ S.extensionLattice.stdOrdersPart l i,
      ∃ y ∈ S.extensionLattice.withOrders i (stdOrders l), d • y = g • x - x)
    (hf : (f : Ainf) ∈ S.liftIdeal r l i) (h_eq : d * s = α * (g • f - f)) :
    s ∈ S.liftIdeal r l i := by
  -- Lift `f - r • t` times a constant to some `x`. Since `g` fixes the constant,
  -- `α (g x - x) / d` lifts `s - r α v` times it, where `g t - t = d v`.
  obtain ⟨t, h_lift⟩ : ∃ t : k.S, ∀ y ∈ S.trivialLattice.stdOrdersPart l i,
      ∃ x ∈ S.extensionLattice.stdOrdersPart l i, S.projTrivial.wittMap x = (f - r • t).val • y :=
    exists_lift_of_mem_liftIdeal hf
  obtain ⟨v, hv⟩ : d ∣ g • t - t := h_dvd t
  refine mem_liftIdeal_iff.2 ⟨α * v, fun c ↦ ?_⟩
  obtain ⟨x, hx_mem, hx_pr : S.projTrivial.wittMap x = (f - r • t).val • S.constantAt i c⟩ :=
    h_lift (S.constantAt i c) (constantAt_mem_stdOrdersPart c)
  obtain ⟨y, hy_mem, hy : d • y = g • x - x⟩ := h_div_orders x hx_mem
  refine ⟨α • y, smul_mem _ α hy_mem, hd ?_⟩
  have h_diff : S.projTrivial.wittMap (g • x - x) =
      (g • (f : Ainf) - f - r • (g • (t : Ainf) - t)) • S.constantAt i c := by
    simp [hx_pr, k.galMonoid.smul_def, frobGroup_smul_smul, constantAt, gal_smul_letterProj,
      smul_sub]
    module
  have h_scalar : α * (g • (f : Ainf) - f - r • (g • (t : Ainf) - t)) =
      d * (s - r • (α * v)) := by
    simp only [nsmul_eq_mul]
    linear_combination -h_eq - r * α * hv
  calc d • S.projTrivial.wittMap (α • y)
      = α • S.projTrivial.wittMap (d • y) := by simp [smul_comm d α]
    _ = d • (s - r • (α * v)) • S.constantAt i c := by
      rw [hy, h_diff, smul_smul, h_scalar, mul_smul]

/-- Operators preserve the ideals at every level. Let `f` in `k.S` lie in `S.liftIdeal r l i`, the
ideal generated by `r` and by the elements that multiply the constants at the letter `i` into the
image of the extension of C by Y at level `l`. If `zτ (s + β f) = α (g f - f)` with `g` in `Γ'` and
`s`, `α`, `β` in `Ainf`, then `s` lies in the same ideal. Here `zτ = k.zTau` is the product of the
coordinate `z = k.z` and `τ = [ε^{1/p}] − 1`, ε a system of p-power roots of 1. -/
lemma mem_liftIdeal_of_eq_zTau_mul_smul_sub {S : PairingSide O} {r l : ℕ} {i : Letter} {f : k.S}
    {s : Ainf} (α β : Ainf) (g : k.galMonoid) (hf : (f : Ainf) ∈ S.liftIdeal r l i)
    (h_eq : k.zTau * (s + β * f) = α * (g • f - f)) :
    s ∈ S.liftIdeal r l i := by
  have h_regular : IsSMulRegular S.trivialLattice.Ambient k.zTau := fun y y' h ↦
    smul_left_cancel k.zTauUnit (by simpa [zTauUnit_smul] using h)
  -- Division of `g x - x` by `zTau` keeps the exponents.
  have h_div (x : S.extensionLattice.Ambient) (hx : x ∈ S.extensionLattice.stdOrdersPart l i) :
      ∃ y ∈ S.extensionLattice.withOrders i (stdOrders l), k.zTau • y = g • x - x :=
    ⟨k.zTauUnit⁻¹ • (g • x - x),
      zTauUnit_inv_smul_sub_mem_withOrders hx.1 (smul_sub_mem_withOrders hx.2 g),
      by rw [← zTauUnit_smul, smul_inv_smul]⟩
  have h_sum : s + β * f ∈ S.liftIdeal r l i :=
    mem_liftIdeal_of_mul_eq_mul_smul_sub α g h_regular
      (fun t ↦ dvd_of_mul_right_dvd (zTau_mul_E_dvd_smul_sub g t)) h_div hf h_eq
  exact (add_mem_cancel_right (mul_mem_left _ β hf)).1 h_sum

/-- The derivation step. Let `f` in `k.S` lie in `S.liftIdeal r 1 i`, the ideal generated by `r` and
by the elements that multiply the constants at the letter `i` into the image of the extension of C
by Y at level one. If `zτE (s + β f) = α (g f - f)` with `g` in `Γ'` and `s`, `α`, `β` in `Ainf`,
then `s` lies in the same ideal. Here `zτ = k.zTau` is the product of the coordinate `z = k.z` and
`τ = [ε^{1/p}] − 1`, ε a compatible system of p-power roots of unity, and `E = k.E` is the generator
of ker θ given by the chart. -/
lemma mem_liftIdeal_of_eq_mul_smul_sub {S : PairingSide O} {r : ℕ} {i : Letter} {f : k.S} {s : Ainf}
    (α β : Ainf) (g : k.galMonoid) (hf : (f : Ainf) ∈ S.liftIdeal r 1 i)
    (h_eq : k.zTau * k.E * (s + β * f) = α * (g • f - f)) :
    s ∈ S.liftIdeal r 1 i := by
  have h_unit {L : JumpLattice O} (y : L.Ambient) :
      (k.zTauUnit * k.frobEUnit 0) • y = (k.zTau * k.E) • y := by
    simp [frobEUnit, Chart.frobE, mul_smul, zTauUnit_smul, zTau]
  have h_regular : IsSMulRegular S.trivialLattice.Ambient (k.zTau * k.E) := fun y y' h ↦
    smul_left_cancel (k.zTauUnit * k.frobEUnit 0) (by simpa only [h_unit] using h)
  have h_div (x : S.extensionLattice.Ambient) (hx : x ∈ S.extensionLattice.stdOrdersPart 1 i) :
      ∃ y ∈ S.extensionLattice.withOrders i (stdOrders 1), (k.zTau * k.E) • y = g • x - x := by
    obtain ⟨hx_loc, hx_exp⟩ := hx
    -- The difference `g x - x` gains one exponent at `a = 0`.
    have h_gain : g • x - x ∈
        S.extensionLattice.withOrders i fun (a : ℕ) (u : ℤ) ↦ if a < 1 then 1 else -u :=
      smul_sub_mem_withOrders_of_stdOrders_one hx_loc hx_exp g
    -- Division by `zTau` keeps the exponents, and division by `E` uses up the gain.
    have h_quot : k.frobEUnit 0 ^ (-1 : ℤ) • k.zTauUnit⁻¹ • (g • x - x) ∈
        S.extensionLattice.withOrders i (stdOrders 1) :=
      frobEUnit_zpow_smul_mem_withOrders 0 (-1)
        (zTauUnit_inv_smul_sub_mem_withOrders hx_loc h_gain)
        fun a u _ ↦ stdOrders_one_le_add a u
    exact ⟨_, h_quot, by simp [← h_unit, mul_smul]⟩
  have h_sum : s + β * f ∈ S.liftIdeal r 1 i :=
    mem_liftIdeal_of_mul_eq_mul_smul_sub α g h_regular (zTau_mul_E_dvd_smul_sub g) h_div hf h_eq
  exact (add_mem_cancel_right (mul_mem_left _ β hf)).1 h_sum

/-! ### Monomials in p, z and E that lie in the ideals -/

/-- The Galois difference of a monomial lowers its power of `z` by one after division by `zτE`. -/
private lemma exists_monomial_lowering (c n : ℕ) :
    let f : k.S := p ^ c * k.z ^ (n + 1)
    ∃ (g : k.galMonoid) (α β : Ainf),
      k.zTau * k.E * (↑(p ^ (c + padicValNat p (n + 1)) * k.z ^ n : k.S) + β * f) =
        α * (g • (f : Ainf) - f) := by
  intro f
  obtain ⟨t, ht : toGp t.val • k.z.val = WittVector.teichmuller p epsTilt ^ 1 * k.z.val⟩ :=
    k.exists_smul_z 1
  obtain ⟨α, β, h_lift : tau * k.E * (p ^ padicValNat p (n + 1) + β * k.z) =
      α * (WittVector.teichmuller p epsTilt ^ (n + 1) - 1)⟩ :=
    k.exists_tau_mul_E_eq_mul_epsTilt_pow_sub_one n.add_one_ne_zero
  have h_smul : toGp t.val • f.val =
      p ^ c * (WittVector.teichmuller p epsTilt ^ (n + 1) * k.z.val ^ (n + 1)) := by
    simp [f, ht, mul_pow]
  refine ⟨⟨_, t, rfl⟩, α, β, ?_⟩
  change _ = α * (toGp t.val • f.val - f)
  simp only [h_smul, f, zTau]
  push_cast
  linear_combination ↑p ^ c * k.z.val ^ (n + 1) * h_lift

/-- Passing from `n!` to `(n + 1)!` adds the valuation of `n + 1` to the cost. -/
lemma padicValNat_factorial_succ {p : ℕ} [Fact p.Prime] (n : ℕ) :
    padicValNat p (n + 1).factorial = padicValNat p (n + 1) + padicValNat p n.factorial := by
  simp only [Nat.factorial_succ, Nat.padicValNat_def,
    Nat.multiplicity_mul n.succ_ne_zero n.factorial_ne_zero]

/-- Going down a level, on a Kummer chart `k` with ring `k.S ⊂ A_inf` and coordinate `z = k.z`: if
`p^c z^n` lies in `S.liftIdeal r 1 (σ i)`, where `σ i = i^p` is `k.letterFrob i` for the letter `i`
(a unit of the field with `p ^ k.f` elements), if `p a ≤ n` and `c + v_p(n!) ≤ κ + v_p((p a)!)`,
then `p^κ z^a` lies in `S.liftIdeal r 0 i`. -/
lemma mem_liftIdeal_zero_of_mem_liftIdeal_one_letterFrob {S : PairingSide O} {r : ℕ} {i : Letter}
    {a n : ℕ} (c κ : ℕ) (h_exponent : p * a ≤ n)
    (h_mem : ((p ^ c * k.z ^ n : k.S) : Ainf) ∈ S.liftIdeal r 1 (k.letterFrob i))
    (h_cost : c + padicValNat p n.factorial ≤ κ + padicValNat p (p * a).factorial) :
    (p : Ainf) ^ κ * (k.z : Ainf) ^ a ∈ S.liftIdeal r 0 i := by
  -- Induction from `n` down to `p * a`: `mem_liftIdeal_of_eq_mul_smul_sub` lowers the power of `z`
  -- from `n + 1` to `n` at the cost of `p ^ v(n + 1)`, and `p_pow_mul_z_pow_mem_liftIdeal_iff`
  -- passes from `z ^ (p * a)` at level one to `z ^ a`.
  induction h_exponent generalizing c with
  | refl =>
    have h_zero : (p : Ainf) ^ c * k.z.val ^ a ∈ S.liftIdeal r 0 i :=
      p_pow_mul_z_pow_mem_liftIdeal_iff.1 h_mem
    exact mem_of_dvd _ (mul_dvd_mul_right (pow_dvd_pow _ (by omega)) _) h_zero
  | @step n _ ih =>
    obtain ⟨g, α, β, h_der⟩ := exists_monomial_lowering (k := k) c n
    -- The cost of the step is `v(n + 1)`, and `v((n + 1)!) = v(n + 1) + v(n!)`.
    rw [padicValNat_factorial_succ] at h_cost
    exact ih _ (mem_liftIdeal_of_eq_mul_smul_sub α β g h_mem h_der) (by omega)

/-- Trading `E` for `z` at level one, on a Kummer chart `k` with ring `k.S ⊂ A_inf`, coordinate
`z = k.z` and generator `E = k.E` of ker θ: if `p^c z^a E^n` lies in `S.liftIdeal r 1 i`, if
`c + d n + v_p(n!) ≤ b` with `d = k.differentBound` and `a + n ≤ κ`, then `p^b z^κ` lies in the same
ideal. `d` is `0` if the ramification index `e` of the chart is `1`, else `v_p(e) + 1`. -/
lemma mem_liftIdeal_of_mul_E_pow {S : PairingSide O} {r : ℕ} {i : Letter} {a c n κ b : ℕ}
    (h_mem : ((p ^ c * k.z ^ a * k.E ^ n : k.S) : Ainf) ∈ S.liftIdeal r 1 i)
    (h_cost : c + k.differentBound * n + padicValNat p n.factorial ≤ b) (h_exponent : a + n ≤ κ) :
    (p : Ainf) ^ b * (k.z : Ainf) ^ κ ∈ S.liftIdeal r 1 i := by
  -- One step trades a factor `E` for a factor `z` at the cost of `p ^ cost 0 (n + 1)`.
  induction n generalizing a c with
  | zero =>
    have h_base : (p : Ainf) ^ c * (k.z : Ainf) ^ a ∈ S.liftIdeal r 1 i := by simpa using h_mem
    exact mem_of_dvd _ (mul_dvd_mul (pow_dvd_pow _ (by omega)) (pow_dvd_pow _ (by omega))) h_base
  | succ n ih =>
    -- Choose `g` with `g E = ω E` and `zτ q = ω ^ (n + 1) - 1`, where `υ q = p ^ cost + E b₁`.
    obtain ⟨g, ω, υ, q, hE, -, h_div, hq⟩ :
        ∃ (g : k.galMonoid) (ω : Ainfˣ) (υ q : Ainf),
          g • (k.frobE 0).val = ω.val * (k.frobE 0).val ∧
          (∀ s : k.S, (k.frobE 0).val ∣ g • s.val - s.val) ∧
          (k.frobE 0).val ∣ υ * q - p ^ cost 0 (n + 1) ∧
          k.zTau * q = (ω : Ainf) ^ (n + 1) - 1 :=
      exists_smul_frobE_eq_mul_and_zTau_mul_eq 0 n.cast_add_one_ne_zero
    obtain ⟨b₁, hb₁⟩ := h_div
    have hE' : g • k.E.val = ω * k.E := by simpa [Chart.frobE] using hE
    have hb₁' : υ * q - p ^ cost 0 (n + 1) = k.E * b₁ := by simpa [Chart.frobE] using hb₁
    -- `g` multiplies `z` by `1 + τ E v`, hence `z ^ a` by `1 + τ E v b₂`.
    obtain ⟨v, hv⟩ : k.zTau * k.E ∣ g • k.z - k.z := zTau_mul_E_dvd_smul_sub g k.z
    have hz : g • (k.z : Ainf) = k.z * (1 + tau * k.E * v) := by
      rw [zTau] at hv
      linear_combination hv
    obtain ⟨b₂, hb₂⟩ : (1 + tau * k.E * v) - 1 ∣ (1 + tau * k.E * v) ^ a - 1 :=
      sub_one_dvd_pow_sub_one _ a
    have h_smul : g • (↑(p ^ c * k.z ^ a * k.E ^ (n + 1) : k.S) : Ainf) =
        p ^ c * (k.z.val ^ a * (1 + tau * k.E * v * b₂)) * (ω ^ (n + 1) * k.E.val ^ (n + 1)) := by
      simp [hE', hz, mul_pow, eq_add_of_sub_eq hb₂, add_comm]
    have hq' : k.z.val * tau * q = (ω : Ainf) ^ (n + 1) - 1 := by
      simpa [zTau, mul_comm tau] using hq
    -- The derivation by `g`, with multiplier `z υ`, trades one `E` for `p ^ cost z`.
    let β : Ainf := k.z * b₁ + υ * v * b₂ * ω ^ (n + 1)
    have h_der : k.zTau * k.E *
        (↑(p ^ (c + cost 0 (n + 1)) * k.z ^ (a + 1) * k.E ^ n : k.S) +
          β * ↑(p ^ c * k.z ^ a * k.E ^ (n + 1) : k.S)) =
        k.z * υ * (g • (↑(p ^ c * k.z ^ a * k.E ^ (n + 1) : k.S) : Ainf) -
          ↑(p ^ c * k.z ^ a * k.E ^ (n + 1) : k.S)) := by
      simp only [h_smul, zTau, β]
      push_cast
      -- The `b₂` terms cancel; what is left is `υ * hq'` rewritten by `hb₁'`.
      linear_combination ↑p ^ c * k.z.val ^ (a + 1) * k.E.val ^ (n + 1) *
        (υ * hq' - tau * k.z.val * hb₁')
    have h_step :
        ↑(p ^ (c + cost 0 (n + 1)) * k.z ^ (a + 1) * k.E ^ n : k.S) ∈ S.liftIdeal r 1 i :=
      mem_liftIdeal_of_eq_mul_smul_sub _ β g h_mem h_der
    -- The cost of the step is `v(n + 1) + d`, and `v((n + 1)!) = v(n + 1) + v(n!)`.
    have h_step_cost : cost 0 (n + 1) = padicValNat p (n + 1) + k.differentBound := by
      rw [cost, ← Nat.cast_succ, padicValInt.of_nat, Nat.padicValNat_def]; simp
    rw [mul_add, mul_one, padicValNat_factorial_succ] at h_cost
    exact ih h_step (by omega) (by omega)

/-- Lowering by one the power of the coordinate `z = k.z` of the Kummer chart `k`: for a side `S`
and a letter `i`, if `p ^ c * z ^ n` lies in `S.liftIdeal r 0 i` and `1 ≤ n`, then so does
`p ^ (c + v_p(n) + 1) * z ^ (n - 1)`. -/
lemma p_pow_mul_z_pow_pred_mem_liftIdeal {S : PairingSide O} {r c n : ℕ} {i : Letter}
    (hn_pos : 1 ≤ n) (h_mem : (p : Ainf) ^ c * k.z.val ^ n ∈ S.liftIdeal r 0 i) :
    (p : Ainf) ^ (c + padicValNat p n + 1) * k.z.val ^ (n - 1) ∈ S.liftIdeal r 0 i := by
  -- Take `t` in `Γ'` with `t z = [ε] z` and put `v = v_p(n)`. As `E ≡ p` modulo `z`, there is an
  -- identity `τ (p ^ (v + 1) + z β') = α ([ε] ^ n - 1)`; multiplied by `p ^ c z ^ n` it reads
  -- `zτ (p ^ (c + v + 1) z ^ (n - 1) + β' p ^ c z ^ n) = α (t - 1) (p ^ c z ^ n)`.
  obtain ⟨m, rfl⟩ : ∃ m : ℕ, n = m + 1 := Nat.exists_eq_add_of_le' hn_pos
  let f : k.S := p ^ c * k.z ^ (m + 1)
  obtain ⟨g, α, β, h_lower⟩ := exists_monomial_lowering (k := k) c m
  obtain ⟨e, he⟩ : k.z ∣ k.E - p := k.z_dvd_E_sub_p
  have hE : (k.E : Ainf) - p = k.z * e := by exact_mod_cast congrArg Subtype.val he
  have h_der : k.zTau * ((p : Ainf) ^ (c + padicValNat p (m + 1) + 1) * k.z.val ^ m +
      (p ^ padicValNat p (m + 1) * e + β * k.E) * f) = α * (g • (f : Ainf) - f) := by
    dsimp only [f]
    push_cast at h_lower ⊢
    simp only [pow_add, pow_succ] at h_lower ⊢
    linear_combination h_lower - k.zTau * (p : Ainf) ^ c * (p : Ainf) ^ padicValNat p (m + 1) *
      k.z.val ^ m * hE
  rw [Nat.add_sub_cancel]
  exact mem_liftIdeal_of_eq_zTau_mul_smul_sub α _ g (by simpa [f] using h_mem) h_der

/-- Let `S : PairingSide O` be a pairing side and `i` a letter. This lemma repeatedly lowers the
power of the coordinate `z = k.z` of the Kummer chart `k`. If `p ^ c * z ^ n` lies in
`S.liftIdeal r 0 i`, `m ≤ n` and `c + n + v_p(n!) ≤ κ + m + v_p(m!)`, then `p ^ κ * z ^ m` lies in
the same ideal. -/
lemma p_pow_mul_z_pow_mem_liftIdeal_of_le {S : PairingSide O} {r c κ m n : ℕ} {i : Letter}
    (h_exponent : m ≤ n) (h_mem : (p : Ainf) ^ c * k.z.val ^ n ∈ S.liftIdeal r 0 i)
    (h_cost : c + n + padicValNat p n.factorial ≤ κ + m + padicValNat p m.factorial) :
    (p : Ainf) ^ κ * k.z.val ^ m ∈ S.liftIdeal r 0 i := by
  induction h_exponent generalizing c with
  | refl => exact mem_of_dvd _ (mul_dvd_mul_right (pow_dvd_pow _ (by omega)) _) h_mem
  | @step n _ ih =>
    -- The step costs `v_p(n + 1) + 1`, and `v_p((n + 1)!) = v_p(n + 1) + v_p(n!)`.
    have h_pred : (p : Ainf) ^ (c + padicValNat p (n + 1) + 1) * k.z.val ^ n ∈
        S.liftIdeal r 0 i :=
      p_pow_mul_z_pow_pred_mem_liftIdeal n.succ_pos h_mem
    rw [padicValNat_factorial_succ] at h_cost
    exact ih h_pred (by omega)

/-- Passing to the letter before, on a Kummer chart `k` with coordinate `z = k.z` in `Ainf`, the
ring A_inf: for a pairing side `S`, let every element of `S.jumpSet (k.letterFrob j)` be at most
`ω`. If `p ^ c * z ^ n` lies in `S.liftIdeal r 0 (k.letterFrob j)`, then
`p ^ (c + d * ω + v_p(ω!)) * z ^ ((n + ω) / p)` lies in `S.liftIdeal r 0 j`. Here `d` is
`k.differentBound`: `0` if the ramification index `e` is `1`, else `v_p(e) + 1`. -/
lemma p_pow_mul_z_pow_div_mem_liftIdeal {S : PairingSide O} {r c n ω : ℕ} {j : Letter}
    (h_wt : ∀ u ∈ S.jumpSet (k.letterFrob j), u ≤ ω)
    (h_mem : (p : Ainf) ^ c * k.z.val ^ n ∈ S.liftIdeal r 0 (k.letterFrob j)) :
    (p : Ainf) ^ (c + k.differentBound * ω + padicValNat p ω.factorial) * k.z.val ^ ((n + ω) / p)
      ∈ S.liftIdeal r 0 j := by
  -- Multiply by `E ^ ω` to reach level one, trade each factor `E` for a factor `z`, and come
  -- down by Frobenius, which costs nothing more.
  have h_one : (↑((p : k.S) ^ c * k.z ^ n * k.E ^ ω) : Ainf) ∈
      S.liftIdeal r 1 (k.letterFrob j) := by
    simpa using mul_E_pow_mem_liftIdeal_one h_mem h_wt
  have h_traded : (p : Ainf) ^ (c + k.differentBound * ω + padicValNat p ω.factorial) *
      k.z.val ^ (n + ω) ∈ S.liftIdeal r 1 (k.letterFrob j) :=
    mem_liftIdeal_of_mul_E_pow h_one le_rfl le_rfl
  exact mem_liftIdeal_zero_of_mem_liftIdeal_one_letterFrob _ _ (Nat.mul_div_le (n + ω) p)
    (h_traded)
    (by simp only [Nat.padicValNat_def, multiplicity_mul_div_factorial, le_refl])

/-- Let `k` be a Kummer chart with coordinate `z = k.z`, an element of `Ainf`, the ring A_inf. Let
`S` be a pairing side (`PairingSide O`). For each `κ`, some power of `z` lies in
`S.liftIdeal (p ^ κ) 0 i` for every letter `i`, a unit of the field with p^f elements. -/
lemma exists_forall_z_pow_mem_liftIdeal (S : PairingSide O) (κ : ℕ) :
    ∃ a : ℕ, ∀ i : Letter, k.z.val ^ a ∈ S.liftIdeal (p ^ κ) 0 i := by
  -- By `frame_theorem`, `τ ^ jumpBound` multiplies `ainfLattice` into `kisinAinf`; the lift of
  -- `τ ^ jumpBound` times a constant is the letter-`i` part of `τ ^ jumpBound • (1 ⊗ (0, c))`.
  have h_tau (i : Letter) : tau ^ S.extensionLattice.jumpBound ∈ S.liftIdeal (p ^ κ) 0 i :=
    mem_liftIdeal_iff.2 ⟨0, fun c ↦
      ⟨_, letterProj_mem_withOrders (frobKisinAinf_zero.ge
        (frame_theorem.tau_pow_smul_mem_kisinAinf _ (mk_one_mem_ainfLattice (0, c)))),
        by simp [constantAt]⟩⟩
  -- The ideals contain powers of `p` and `τ`, and `z` lies in the radical of `(p, τ)`.
  have h_radical : span {↑p, tau} ≤ radical (⨅ i : Letter, S.liftIdeal (p ^ κ) 0 i) :=
    Ideal.span_le.2 (Set.pair_subset ⟨κ, mem_iInf.2 fun _ ↦ p_pow_mem_liftIdeal_self⟩
      ⟨_, mem_iInf.2 h_tau⟩)
  simpa [mem_radical_iff] using radical_le_radical_iff.2 h_radical
    (Ainf.mem_radical_of_not_isUnit (a := k.z) k.not_isUnit_z not_p_dvd_tau)

/-- Let `S` be a side, and for every letter `i` let every element of `S.jumpSet i`, the jump set of
`S` at `i`, be at most `ω`. Then some power `z ^ a` of the coordinate `z = k.z` of the Kummer chart
`k` with `(p - 1) * a ≤ e * (ω + κ)`, where `e = k.e` is the ramification index, lies in
`S.liftIdeal (p ^ (κ + 1)) 0 i` for every letter `i`. -/
lemma exists_z_pow_mem_liftIdeal {S : PairingSide O} {ω : ℕ}
    (h_jumps : ∀ i : Letter, ∀ u ∈ S.jumpSet i, u ≤ ω) (κ : ℕ) :
    ∃ a : ℕ, (∀ i : Letter, k.z.val ^ a ∈ S.liftIdeal (p ^ (κ + 1)) 0 i) ∧
      (p - 1) * a ≤ k.e * (ω + κ) := by
  -- Take the least `a` with `z ^ a` in the ideals. As `z ^ e ∈ (E, p)`, the power
  -- `z ^ (a + e * (ω + κ))` lies in the ideals of level one; coming down gives
  -- `z ^ ((a + e * (ω + κ)) / p)`, so this exponent is at least `a`.
  obtain ⟨a, h_min⟩ :=
    exists_minimal_of_wellFoundedLT _ (exists_forall_z_pow_mem_liftIdeal S (κ + 1))
  obtain ⟨u, v, h_span⟩ := Ideal.mem_span_pair.1 k.z_pow_mem_span
  have h_z : u.val * k.E.val + v.val * p = k.z.val ^ k.e := by exact_mod_cast congrArg (·.1) h_span
  refine ⟨a, h_min.prop, ?_⟩
  have h_up (i : Letter) :
      k.z.val ^ (a + k.e * (ω + κ)) ∈ S.liftIdeal (p ^ (κ + 1)) 1 (k.letterFrob i) := by
    rw [pow_add k.z.val, pow_mul, ← h_z]
    exact mul_add_pow_mem_of_mul_pow_mem
      (mul_E_pow_mem_liftIdeal_one (h_min.prop _) (h_jumps _)) p_pow_mem_liftIdeal_self
  have h_mul_le : a * p ≤ a + k.e * (ω + κ) := Nat.mul_le_of_le_div p _ _ (h_min.le fun i ↦ by
    simpa using mem_liftIdeal_zero_of_mem_liftIdeal_one_letterFrob 0 0 (Nat.mul_div_le _ p)
      (by simpa using h_up i) (by simp [Nat.padicValNat_def, multiplicity_mul_div_factorial]))
  rw [Nat.sub_one_mul, Nat.mul_comm p a]
  omega

/-- Let `S` be a pairing side. Let every element of `S.jumpSet i` be at most `ω`, for every letter
`i`, and let `e * ω ≤ p - 2`, where `e = k.e` is the ramification index of the Kummer chart `k`.
Then `S.KillsCokernel i 0 0` holds at each letter `i`. That is, `1 = p ^ 0 * E ^ 0`, with `E = k.E`
the generator of the kernel of θ, multiplies the letter-`i` part of `Ainf ⊗ C` (C the parameter
lattice of `S`) into the image of the extension's module of standard exponents of level `0`. So the
cokernel vanishes. -/
lemma killsCokernel_zero_zero_of_small_jumps {S : PairingSide O} {ω : ℕ}
    (h_wt : ∀ i : Letter, ∀ u ∈ S.jumpSet i, u ≤ ω) (h_small : k.e * ω ≤ p - 2) (i : Letter) :
    S.KillsCokernel i 0 0 := by
  -- Some `z ^ a` with `(p - 1) a ≤ e ω` lies in the ideals modulo `p`; here this forces `a = 0`.
  obtain ⟨a, h_mem, h_le : (p - 1) * a ≤ k.e * ω⟩ := exists_z_pow_mem_liftIdeal h_wt 0
  have h_two : 2 ≤ p := (Fact.out : p.Prime).two_le
  obtain rfl : a = 0 := Nat.lt_one_iff.1 (Nat.lt_of_mul_lt_mul_left (a := p - 1) (by omega))
  -- Nakayama's lemma drops the modulus `p`.
  exact killsCokernel_of_p_pow_mem_liftIdeal (by simpa using h_mem i)

/-- Let the Kummer chart `k` be unramified (`k.E = k.z + p` and `k.e = 1`) and `p ≥ 5`. If at every
letter `j` all elements of `S.jumpSet j`, the jump set of the lattice Y of `S`, are at most
`(p - 3) (s + t)`, then `p ^ s * k.E ^ t` kills the cokernel at the letter `i`: it multiplies the
constants at `i` into the image of the elements of the extension with the standard exponents of
level `0`. -/
lemma killsCokernel_of_isUnramified {S : PairingSide O} {i : Letter} (s t : ℕ)
    (h_jumps : ∀ j : Letter, ∀ u ∈ S.jumpSet j, u ≤ ↑((p - 3) * (s + t))) (h_unram : k.IsUnramified)
    (hp : 5 ≤ p) : S.KillsCokernel i s t := by
  -- All `p ^ (s + t - m) * z ^ m` lie in the ideal modulo `p ^ (s + t + 1)`. By Nakayama the
  -- modulus can be dropped, and `p ^ s * (z + p) ^ t` is a combination of these monomials.
  obtain ⟨b, hb_mem, hb_le⟩ := exists_z_pow_mem_liftIdeal h_jumps (s + t)
  obtain ⟨hE, he, -⟩ := h_unram
  -- Legendre's formula gives `(p - 1) v_p(b!) ≤ b`, yielding `b + v_p(b!) ≤ s + t`.
  have legendre : (p - 1) * padicValNat p b.factorial ≤ b :=
    Nat.padicValNat_def (p := p) ▸
      (Nat.Prime.sub_one_mul_multiplicity_factorial Fact.out).trans_le (Nat.sub_le _ _)
  have val_le : b + padicValNat p b.factorial ≤ s + t := by
    simp only [he, one_mul] at hb_le
    zify [show 1 ≤ p by omega, show 3 ≤ p by omega] at hb_le legendre hp ⊢
    nlinarith [Nat.cast_nonneg (α := ℤ) (padicValNat p b.factorial)]
  -- Lowering `z ^ max b m` to `z ^ m` costs `b + v_p(b!) - (m + v_p(m!)) ≤ s + t - m` if `m < b`.
  have monomial_mem (m : ℕ) :
      p ^ (s + t - m) * k.z.val ^ m ∈ S.liftIdeal (p ^ (s + t + 1)) 0 i := by
    refine p_pow_mul_z_pow_mem_liftIdeal_of_le (c := 0) (le_max_right b m)
      (mem_of_dvd _ (by simp [pow_dvd_pow]) (hb_mem i)) ?_
    rcases max_cases b m with ⟨h, -⟩ | ⟨h, -⟩ <;>
      · rw [h]
        omega
  apply liftIdeal_le_of_p_pow_mem (c := s + t) (by simpa using monomial_mem 0)
  suffices h_sum : ∑ m ∈ Finset.range (t + 1), p ^ s * (k.z.val ^ m * p ^ (t - m) * t.choose m) ∈
      S.liftIdeal (p ^ (s + t + 1)) 0 i by
    simpa [hE, add_pow, Finset.mul_sum] using h_sum
  refine sum_mem fun m _ ↦ mem_of_dvd _ ?_ (monomial_mem m)
  grw [add_tsub_le_assoc]
  exact ⟨t.choose m, by ring⟩

/-- Coming back through `J` letters, for a side `S` on a Kummer chart `k` of a group `Γ` over G_p,
with coordinate `z = k.z`. Let `z ^ a` lie in `S.liftIdeal r 0 j` for every letter `j`. Let the jump
sets `S.jumpSet j` be bounded by `ω` at the letters `j = (k.letterFrob ^ t) i = i ^ p ^ t` with
`1 ≤ t ≤ J`. Then some `p ^ c * z ^ n` with `c ≤ J (d ω + v_p(ω!))` and
`n ≤ a / p ^ J + ω / (p - 1)` lies in `S.liftIdeal r 0 i`, where `d = k.differentBound`. -/
lemma exists_p_pow_mul_z_pow_mem_liftIdeal_and_le {S : PairingSide O} {r a ω J : ℕ}
    (ha_mem : ∀ j : Letter, k.z.val ^ a ∈ S.liftIdeal r 0 j) {i : Letter}
    (h_next : ∀ t ∈ Finset.Icc 1 J, ∀ u ∈ S.jumpSet ((k.letterFrob ^ t) i), u ≤ ω) :
    ∃ c n : ℕ, (p : Ainf) ^ c * k.z.val ^ n ∈ S.liftIdeal r 0 i ∧
      c ≤ J * (k.differentBound * ω + padicValNat p ω.factorial) ∧
      (n : ℝ) ≤ a / p ^ J + ω / (p - 1) := by
  have hp : (1 : ℝ) < p := mod_cast (Fact.out : p.Prime).one_lt
  have hp_sub : (0 : ℝ) < p - 1 := sub_pos.2 hp
  induction J generalizing i with
  | zero => exact ⟨0, a, by simpa using ha_mem i, by simp, by simp [div_nonneg, hp_sub.le]⟩
  | succ J ih =>
    -- Come back to `k.letterFrob i` from the `J` letters after it, then to `i` by one more step.
    have h_later : ∀ t ∈ Finset.Icc 1 J, ∀ u ∈ S.jumpSet ((k.letterFrob ^ t) (k.letterFrob i)),
      u ≤ ω :=
      fun t ht ↦ h_next (t + 1) (by grind)
    have h_first : ∀ u ∈ S.jumpSet (k.letterFrob i), u ≤ ω := h_next 1 (by simp)
    obtain ⟨c, n, h_mem, hc_le, hn_le⟩ := ih h_later
    refine ⟨c + k.differentBound * ω + padicValNat p ω.factorial, (n + ω) / p,
      p_pow_mul_z_pow_div_mem_liftIdeal h_first h_mem, by linarith, ?_⟩
    calc (((n + ω) / p : ℕ) : ℝ) ≤ (n + ω) / p := mod_cast Nat.cast_div_le
      _ ≤ (a / p ^ J + ω / (p - 1) + ω) / p := by gcongr
      _ = a / p ^ (J + 1) + ω / (p - 1) := by field

/-- Let the jump sets `S.jumpSet j` be bounded by `ω` at every letter `j` and by `ω'` at the `J`
letters `(k.letterFrob ^ t) i = i ^ p ^ t` with `1 ≤ t ≤ J`, and let `8 e ≤ p ^ (J + 1)` for the
ramification index `e = k.e`. If `κ ≥ 2 J d ω' + (2 J + 4) ω' / (p - 1) + 8 e ω / p ^ (J + 1)` with
`d = k.differentBound`, then `p ^ κ` kills the cokernel at `i`: it multiplies the constants at `i`
into the image of the elements of the extension of C by Y with the standard exponents of level
`0`. -/
lemma killsCokernel_zero_of_jumps_le {S : PairingSide O} {ω ω' J κ : ℕ} {i : Letter}
    (h_jumps : ∀ j : Letter, ∀ u ∈ S.jumpSet j, u ≤ ω)
    (h_next : ∀ t ∈ Finset.Icc 1 J, ∀ u ∈ S.jumpSet ((k.letterFrob ^ t) i), u ≤ ω')
    (h_ram : 8 * k.e ≤ p ^ (J + 1))
    (hκ : (2 * J * k.differentBound * ω' : ℝ) + (2 * J + 4) * ω' / (p - 1) +
      8 * k.e * ω / p ^ (J + 1) ≤ κ) :
    S.KillsCokernel i κ 0 := by
  -- Start from a power `z ^ a` in the ideals modulo `p ^ (κ + 1)`, come back through the `J`
  -- letters, remove the power of `z` that is left, and use Nakayama's lemma.
  obtain ⟨a, ha_mem, ha_le⟩ : ∃ a : ℕ,
      (∀ j : Letter, k.z.val ^ a ∈ S.liftIdeal (p ^ (κ + 1)) 0 j) ∧
        (p - 1) * a ≤ k.e * (ω + κ) :=
    exists_z_pow_mem_liftIdeal h_jumps κ
  obtain ⟨c, n, h_mem, hc_le, hn_le⟩ : ∃ c n : ℕ,
      (p : Ainf) ^ c * k.z.val ^ n ∈ S.liftIdeal (p ^ (κ + 1)) 0 i ∧
      c ≤ J * (k.differentBound * ω' + padicValNat p ω'.factorial) ∧
      (n : ℝ) ≤ a / p ^ J + ω' / (p - 1) :=
    exists_p_pow_mul_z_pow_mem_liftIdeal_and_le ha_mem h_next
  have h_cost : c + n + padicValNat p n.factorial ≤ κ :=
    add_add_padicValNat_factorial_le hc_le hn_le ha_le h_ram hκ
  have h_removed : (p : Ainf) ^ κ * k.z.val ^ 0 ∈ S.liftIdeal (p ^ (κ + 1)) 0 i :=
    p_pow_mul_z_pow_mem_liftIdeal_of_le n.zero_le h_mem (by omega)
  exact killsCokernel_of_p_pow_mem_liftIdeal (by simpa using h_removed)

end PairingSide

end New.Lift.KummerChart

end