Skip to content

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

Python
52.0 KB
Raw Blame
module

public import TauCeti.NumberTheory.Padics.Cardinality
import TauCeti.RingTheory.WittVector.ArtinSchreier
import TauCeti.RingTheory.WittVector.Complete
public import Mathlib.FieldTheory.IsAlgClosed.Classification
public import Mathlib.RingTheory.WittVector.Compare
public import Mathlib.Algebra.Polynomial.Degree.IsMonicOfDegree
public import Mathlib.Topology.Algebra.Nonarchimedean.Completion
public import TauCeti.RingTheory.Huber.Pair
public import TauCeti.RingTheory.Perfectoid.Integral.Basic
public import TauCeti.RingTheory.Perfectoid.PreTilt.Map
public import TauCeti.RingTheory.WittVector.Cyclotomic
import Mathlib.Algebra.CharP.Pi
import Mathlib.Algebra.Order.Star.Rat
import Mathlib.RingTheory.Henselian
import Mathlib.RingTheory.PiTensorProduct
import Mathlib.RingTheory.RegularLocalRing.Defs
import Mathlib.RingTheory.TotallySplit
import Mathlib.Topology.Connected.Separation
import Mathlib.Topology.MetricSpace.Ultra.TotallySeparated
import TauCeti.RingTheory.Perfectoid.Cyclotomic.Basic
import TauCeti.RingTheory.Perfectoid.Cyclotomic.SpecializationKernel
import TauCeti.RingTheory.Perfectoid.Padic
public import Lib.PadicHodge.PeriodRings.AxTheorem

/-!
# The ring A_inf, the elements ε, μ, τ, ξ, the kernel of θ and adic completeness

`G_p` is the absolute Galois group of `ℚ_p`, and `O_C` is the ring of integers of `ℂ_p`. Fontaine's
ring `A_inf = W(O^♭)` is built from the tilt `O^♭` of `O_C`, together with Fontaine's map
`θ : A_inf → O_C`, the Frobenius `φ`, and an action of `ℕ × G_p`.

## Main definitions and results

* `New.Period.OFlat`, `New.Period.CFlat`: the tilt O^♭ of O_C and its fraction field;
  `New.Period.Ainf`, `New.Period.WittCFlat`: their rings of Witt vectors; `New.Period.theta`:
  Fontaine's θ : A_inf → O_C.
* `New.Period.epsPow`: a homomorphism s ↦ ε^s from ℚ to O^♭ that untilts to primitive roots of
  unity; `New.Period.tau` = [ε^(1/p)] − 1, and Tau Ceti's cyclotomic period elements
  `New.Period.mu` = [ε] − 1 and `New.Period.xi` = Σ_{i<p} [ε^(1/p)]^i, with ξ τ = μ.
* `O_C` is a ring of integral elements of `ℂ_p` (`New.valRingCp.isRingOfIntegralElements`), hence
  an integral perfectoid ring in Tau Ceti's sense.
* `New.Period.FrobGal` = ℕ × G_p acts on O^♭ and A_inf, (n, g) as φⁿ g. Groups acting on O^♭ also
  act on C^♭ and W(C^♭). `New.Period.frobEnd` is φ.
* `New.Period.ker_theta_eq_span_xi`: the kernel of `θ` is generated by `ξ` (Tau Ceti's
  `TauCeti.Huber.IsRingOfIntegralElements.ker_fontaineTheta_eq_span_cyclotomicXi`).
* `New.Period.mu_dvd_of_theta_frobEnd`: `μ` divides every element killed by all `θ φ ^ j`.
  `New.Period.tau_dvd_of_theta_frobEnd` gives the same for `τ` when only `j ≥ 1` is assumed.
* `New.Period.Ainf.isAdicComplete_span_pair`: `A_inf` is adically complete for the ideal of any two
  non-units.

Notions from other files:
* `New.actionOfHoms`: The action of a monoid M on a ring B by ring endomorphisms given by a family
  f(m) with f(1) the identity and f(ab) = f(a)∘f(b).
* `PreTilt.map` (Tau Ceti): For a ring homomorphism f: R → R', the induced ring homomorphism
  between the inverse limits of R/p and R'/p along x ↦ x^p.
* `New.shiftDiff`: For π in R, the operator (x_j) ↦ (x_j − π x_{j+1}) on sequences in an R-module.
* `New.Variety.IsAbsIntegrallyClosed`: A ring is absolutely integrally closed if every monic
  polynomial of positive degree over it has a root.
* `PreTilt.untilt`: The multiplicative map x ↦ x^♯ from the tilt of a ring R to R.
* `New.ThePrime p`: The class saying that the natural number p is prime.

## Relation to the literature

Known; see `Lib.PadicHodge.PeriodRings.DeRhamPeriods` for sources.
-/

@[expose] public section

noncomputable section

namespace New.Period

/-! ## Fontaine's ring A_inf from the tilt of O_C, with Frobenius and Galois actions -/

section Ainf

open MulSemiringAction Variety Polynomial PreTilt IsOfFinOrder nonZeroDivisors WittVector Perfection
  NeZero Ideal.Quotient Fact ZMod ValuationRing Cardinal Complex IsPrimitiveRoot

/-- The complex numbers and the algebraic closure of ℚ_p have the same cardinality. -/
lemma _root_.New.mk_complex_eq_mk_padicAlgCl {p : ℕ} [Fact p.Prime] : #ℂ = #(PadicAlgCl p) :=
  mk_complex.trans (TauCeti.Padic.cardinalMk_eq_continuum_of_isAlgebraic p (PadicAlgCl p)).symm

variable {p : ℕ} [ThePrime p]

open TauCeti.Huber TauCeti.Perfectoid in
/-- `O_C` is a ring of integral elements of the perfectoid field `ℂ_p`: as a subring of `ℂ_p` it is
Tau Ceti's power-bounded subring `ℂ_p°` (`TauCeti.Huber.powerBoundedSubring_eq_integer`). -/
lemma _root_.New.valRingCp.isRingOfIntegralElements : IsRingOfIntegralElements (valRingCp p) := by
  have h_eq : powerBoundedSubring ℂ_[p] = valRingCp p := powerBoundedSubring_eq_integer
  exact h_eq ▸ isRingOfIntegralElements_powerBoundedSubring ℂ_[p]

/-- `O_C` is an integral perfectoid ring; in particular it is `p`-adically complete
(`TauCeti.Perfectoid.IsIntegralPerfectoid.isAdicComplete_span_natCast`). -/
instance : TauCeti.Perfectoid.IsIntegralPerfectoid p OC :=
  valRingCp.isRingOfIntegralElements.isIntegralPerfectoid

/-! ### The rings -/

/-- The monoid ℕ × G_p, with G_p the absolute Galois group of Q_p; on the period rings with a
Frobenius φ, the pair (n, g) acts as φ^n g. -/
abbrev FrobGal : Type := Multiplicative ℕ × Gp p

/-- The ring O^♭, the inverse limit of O_C/p along x ↦ x^p, where O_C is the ring of integers of
C_p. -/
@[instance_reducible]
def OFlat : Type := PreTilt OC p
  deriving CommRing, CharP _ p, PerfectRing _ p, IsDomain, ValuationRing

/-- The ring A_inf of p-typical Witt vectors over the tilt O^♭ of the ring of integers of C_p. -/
abbrev Ainf : Type := WittVector p OFlat

/-- The fraction field C^♭ of the tilt O^♭ of the ring of integers of C_p. -/
@[instance_reducible]
def CFlat : Type := FractionRing OFlat
  deriving Field, Algebra OFlat, IsFractionRing OFlat, FaithfulSMul OFlat, CharP _ p

/-- The ring W(C^♭) of p-typical Witt vectors over the fraction field C^♭ of O^♭. -/
@[instance_reducible]
def WittCFlat : Type := WittVector p CFlat
  deriving CommRing, IsDomain

/-- Fontaine's ring homomorphism θ from A_inf to the ring of integers of C_p, sending the
Teichmüller lift [x] to x^♯. -/
abbrev theta : Ainf →+* OC := fontaineTheta OC p

@[simp]
lemma theta_teichmuller (x : OFlat) : theta (WittVector.teichmuller p x) = x.untilt :=
  fontaineTheta_teichmuller x

/-- For a ℚ≥0-module G, the monoid Multiplicative G is perfect: its p-th power map is multiplication
by p on G, which is bijective. -/
instance {G : Type*} [AddCommMonoid G] [Module ℚ≥0 G] : PerfectRing (Multiplicative G) p where
  bijective_frobenius := mod_cast MulAction.bijective₀ (G₀ := ℚ≥0) (α := G) (a := p) out

/-! ### The elements ε, τ, μ, ξ -/

/-- Every homomorphism a from the additive group ℚ to the multiplicative monoid of C_p with a(1) = 1
lifts to the tilt: some homomorphism χ: ℚ → O^♭ has χ(s)^♯ = a(s) for all s. -/
lemma exists_tilt_lift_of_character (a : Multiplicative ℚ →* ℂ_[p])
    (ha : a (Multiplicative.ofAdd 1) = 1) :
    ∃ χ : Multiplicative ℚ →* OFlat, ∀ s : Multiplicative ℚ, (χ s).untilt = a s := by
  -- The values of `a` are roots of unity, so they lie in `OC`.
  have h_mem (s : Multiplicative ℚ) : a s ∈ valRingCp p := by
    have h_den : s ^ s.toAdd.den = .ofAdd 1 ^ s.toAdd.num := by
      exact congrArg Multiplicative.ofAdd (by
        change s.toAdd.den • s.toAdd = s.toAdd.num • (1 : ℚ)
        rw [nsmul_eq_mul, zsmul_eq_mul, Rat.den_mul_eq_num, mul_one])
    have h_fin : IsOfFinOrder (a s ^ s.toAdd.den) := by simp [← map_pow, h_den, ha]
    exact mem_valRingCp.mpr (h_fin.of_pow s.toAdd.den_nz).norm_eq_one.le
  -- Send `s` to the compatible sequence `a (s / p ^ n)` of `p`-power roots of `a s` in `OC`,
  -- then reduce the sequence modulo `p`.
  let roots : Multiplicative ℚ →* Perfection OC p :=
    liftMonoidHom p (Multiplicative ℚ) OC (a.codRestrict _ h_mem)
  refine ⟨(mapMonoidHom p (Ideal.Quotient.mk (Ideal.span {(p : OC)})).toMonoidHom).comp roots,
    fun s ↦ ?_⟩
  -- Untilting the reduction of a compatible sequence returns its zeroth term.
  change ((PreTilt.untilt (O := OC) (p := p)
    (mapMonoidHom p (Ideal.Quotient.mk (Ideal.span {(p : OC)})).toMonoidHom (roots s)) : OC) :
      ℂ_[p]) = a s
  exact (congrArg _ (teichmuller₀_mapMonoidHom_idealQuotientMk (x := roots s))).trans
    (by simp [roots])

/-- The map s ↦ ε^s: a chosen homomorphism from ℚ to the multiplicative monoid of O^♭ with
(ε^s)^♯ a primitive root of unity of order the denominator of s. -/
def epsPow : Multiplicative ℚ →* OFlat :=
  -- Transport the complex roots of unity along a chosen abstract field isomorphism.
  let ι : ℂ ≃+* PadicAlgCl p :=
    (TauCeti.Padic.nonempty_ringEquiv_complex p (PadicAlgCl p)).some.symm
  (exists_tilt_lift_of_character
    { toFun s := algebraMap (PadicAlgCl p) ℂ_[p] (ι (exp (2 * Real.pi * I * s.toAdd)))
      map_one' := by simp
      map_mul' := by simp [mul_add, exp_add] }
    (by simp)).choose

lemma isPrimitiveRoot_untilt_epsPow (s : Multiplicative ℚ) :
    IsPrimitiveRoot (epsPow s).untilt s.toAdd.den := by
  -- the untilt is the image of `exp (2 π i s)` under injective ring maps
  rw [← coe_submonoidClass_iff, epsPow, (exists_tilt_lift_of_character _ _).choose_spec s]
  · simp [map_of_injective, RingHom.injective, EquivLike.injective, isPrimitiveRoot_exp_rat]
  · simp

/-- The element ε^{1/p} of O^♭, for the compatible system ε = (1, ζ_p, ζ_{p²}, …) of
`New.Period.epsPow`. -/
def epsRoot : OFlat := epsPow (Multiplicative.ofAdd p⁻¹)

/-- The element ε = (1, ζ_p, ζ_{p²}, …) of O^♭, defined as the p-th power of the chosen element
ε^{1/p}. -/
def epsTilt : OFlat := epsRoot ^ p

@[simp]
lemma epsPow_one : epsPow (Multiplicative.ofAdd 1) = epsTilt := by
  simp [epsTilt, epsRoot, ← map_pow, ← ofAdd_nsmul]

/-- `ζ_p = (ε^{1/p})^♯` is a primitive `p`-th root of unity. -/
lemma isPrimitiveRoot_untilt_epsRoot : IsPrimitiveRoot epsRoot.untilt p := by
  simpa [epsRoot, NeZero.ne] using isPrimitiveRoot_untilt_epsPow (Multiplicative.ofAdd (p : ℚ)⁻¹)

@[simp]
lemma untilt_epsTilt : epsTilt.untilt = 1 := by simpa using isPrimitiveRoot_untilt_epsPow (.ofAdd 1)

/-- The element τ = [ε^{1/p}] − 1 of A_inf, where the brackets denote the Teichmüller lift. -/
def tau : Ainf := WittVector.teichmuller p epsRoot - 1

/-- The element μ = [ε] − 1 of A_inf, where the brackets denote the Teichmüller lift: Tau Ceti's
cyclotomic period element `cyclotomicMu p ε`. -/
def mu : Ainf := TauCeti.WittVector.cyclotomicMu p epsTilt

/-- The element ξ of A_inf equal to the sum of [ε^{1/p}]^i for 0 ≤ i < p, so that ξτ = μ: Tau Ceti's
cyclotomic period element `cyclotomicXi p ε`. -/
def xi : Ainf := TauCeti.WittVector.cyclotomicXi p epsTilt

lemma mu_eq : mu = WittVector.teichmuller p epsTilt - 1 := TauCeti.WittVector.cyclotomicMu_def ..

/-- The `p`-th root of ε in the perfect ring `O^♭` is ε^{1/p}. -/
@[simp]
lemma frobeniusEquiv_symm_epsTilt : (frobeniusEquiv OFlat p).symm epsTilt = epsRoot :=
  (frobeniusEquiv OFlat p).symm_apply_apply epsRoot

lemma xi_eq_sum : xi = ∑ i ∈ Finset.range p, WittVector.teichmuller p epsRoot ^ i := by
  rw [xi, TauCeti.WittVector.cyclotomicXi_def, frobeniusEquiv_symm_epsTilt]

/-- In `A_inf`, ξ·τ = μ, where μ = [ε] − 1, τ = [ε^{1/p}] − 1 and ξ = Σ_{0≤i<p} [ε^{1/p}]^i, the
brackets denoting Teichmüller lifts. -/
lemma xi_mul_tau : xi * tau = mu := by rw [xi_eq_sum, tau, geom_sum_mul, mu_eq, epsTilt, map_pow]

/-- Let `g` be a monic polynomial of degree `d` over `O_C / p`, and let `w`, `b` be in `O^♭`. Then
some `a` in `O^♭` is near `w`, in that `g (w.coeff n)` divides `(w - a).coeff n ^ d`, and either
the `n`-th coordinate of `a` is a root of `g`, or `d = 0` and `a = b`. -/
lemma OFlat.exists_coeff_root_near (n : ℕ) (w : OFlat) {d : ℕ} (b : OFlat) {g : (ModP OC p)[X]}
    (hg : IsMonicOfDegree g d) :
    ∃ a : OFlat, ((d = 0 ∧ a = b) ∨ g.IsRoot (a.coeff n)) ∧
      g.eval (w.coeff n) ∣ (w - a).coeff n ^ d := by
  induction d generalizing b g with
  | zero =>
    -- a monic polynomial of degree `0` is `1`; take `a = b`
    obtain rfl : g = 1 := by simpa using hg
    exact ⟨b, .inl ⟨rfl, rfl⟩, by simp⟩
  | succ d ih =>
    obtain ⟨h_deg, h_monic⟩ := hg
    -- Split off a root: monic polynomials of positive degree over `O_C / p` have roots, so its
    -- Frobenius is onto and every element is the `n`-th coordinate of some `b`.
    have h_aic : IsAbsIntegrallyClosed (OC ⧸ Ideal.span {(p : OC)}) := .of_surjective mk_surjective
    obtain ⟨r, hr⟩ := h_aic.exists_root g h_monic (by omega)
    obtain ⟨b, rfl⟩ : ∃ b : OFlat, b.coeff n = r := coeff_surjective (h_aic.exists_pow_eq p) n r
    obtain ⟨q, rfl⟩ : X - C (b.coeff n) ∣ g := dvd_iff_isRoot.mpr hr
    -- By induction `q` has a root `a` near `w` (or `d = 0` and `a = b`).
    obtain ⟨a, ha, h_dvd⟩ :=
      ih b ((isMonicOfDegree_X_sub_one _).of_mul_left ⟨by omega, h_monic⟩)
    have h_eval :
        ((X - C (b.coeff n)) * q).eval (w.coeff n) ∣ (w - b).coeff n * (w - a).coeff n ^ d := by
      simpa [← map_sub] using mul_dvd_mul_left _ h_dvd
    -- Both `b` and `a` give roots of `(X - b) * q`.
    have h_root_a : ((X - C (b.coeff n)) * q).IsRoot (a.coeff n) := by
      obtain ⟨-, rfl⟩ | h_root := ha
      · simp
      · simp [h_root.eq_zero]
    -- As `OFlat` is a valuation ring, keep whichever of `a`, `b` is nearer to `w`.
    obtain h_near | h_near : w - a ∣ w - b ∨ w - b ∣ w - a := dvd_total (w - a) (w - b)
    · exact ⟨b, .inr (by simp), by grw [h_eval, h_near, pow_succ']⟩
    · exact ⟨a, .inr h_root_a, by grw [h_eval, h_near, pow_succ']⟩

/-- The sequence `s` with `s 0 = 0` and `s (m + 1) = a m (s m)`, for a family of maps `a m` of
`O^♭`. -/
private def OFlat.iterateSeq (a : ℕ → OFlat → OFlat) : ℕ → OFlat
  | 0 => 0
  | m + 1 => a m (OFlat.iterateSeq a m)

private lemma OFlat.coeff_add_pow_pow (x : OFlat) (m n : ℕ) :
    x.coeff (m + n) ^ p ^ n = x.coeff m := coeffMonoidHom_pow_p_pow' x m n

/-- The tilt O^♭ is absolutely integrally closed: every monic polynomial of positive degree over
it has a root. The root is built coordinate by coordinate from roots modulo `p`. -/
lemma OFlat.isAbsIntegrallyClosed : IsAbsIntegrallyClosed OFlat := by
  refine ⟨fun f hf h_deg ↦ ?_⟩
  -- Choose `s (m + 1)` near `s m` such that `f (s (m + 1))` has `m`-th coordinate `0`. The root has
  -- as its `n`-th coordinate that of `s (n + d + 1)`, where `d` is the degree of `f`.
  set d : ℕ := f.natDegree
  have key (n : ℕ) (w : OFlat) :
      ∃ a : OFlat, (f.eval a).coeff n = 0 ∧ (f.eval w).coeff n ∣ (w - a).coeff n ^ d := by
    simpa [hf.natDegree_map, d, h_deg.ne'] using
      exists_coeff_root_near n w 0 ⟨rfl, hf.map (coeff n)⟩
  choose a h_root h_near using key
  let s : ℕ → OFlat := OFlat.iterateSeq a
  have h_s_succ (m : ℕ) : s (m + 1) = a m (s m) := rfl
  have h_root_s (m : ℕ) : (f.eval (s (m + 1))).coeff m = 0 := by rw [h_s_succ, h_root]
  have h_near_s (m : ℕ) : (f.eval (s m)).coeff m ∣ (s m - s (m + 1)).coeff m ^ d := by
    rw [h_s_succ]
    exact h_near m (s m)
  -- with `m = n + d`, the `(m + 1)`-th coordinate of `s (m + 1) - s (m + 2)` is killed by the power
  -- `d * p`, so by the power `p ^ (d + 1)`, which moves it `d + 1` coordinates down
  have h_stable (n : ℕ) : (s (n + d + 1) - s (n + d + 2)).coeff n = 0 := by
    set δ : OFlat := s (n + d + 1) - s (n + d + 2)
    refine zero_dvd_iff.mp ?_
    calc
      0 = (f.eval (s (n + d + 1))).coeff (n + d + 1) ^ p := by rw [PreTilt.coeff_pow_p, h_root_s]
      _ ∣ (δ.coeff (n + d + 1) ^ d) ^ p := pow_dvd_pow_of_dvd (h_near_s (n + d + 1)) p
      _ ∣ (δ.coeff (n + d + 1) ^ p ^ d) ^ p := by grw [← Nat.lt_pow_self out]
      _ = δ.coeff n := by rw [← pow_mul, ← pow_succ, add_assoc, coeff_add_pow_pow]
  have h_compat (n : ℕ) : (s (n + 1 + d + 1)).coeff (n + 1) ^ p = (s (n + d + 1)).coeff n := by
    rw [PreTilt.coeff_pow_p, add_right_comm n 1, eq_comm, ← sub_eq_zero, ← map_sub, h_stable]
  let root : OFlat := ⟨fun n ↦ (s (n + d + 1)).coeff n, h_compat⟩
  refine ⟨root, Perfection.ext fun n ↦ ?_⟩
  -- the `n`-th coordinate of the root is that of `s (n + d + 1)`, and the `n`-th coordinate of
  -- `f (s (n + d + 1))` is a power of the `(n + d)`-th one, which is `0`
  calc (f.eval root).coeff n
    _ = (f.eval (s (n + d + 1))).coeff n := by simp only [← eval₂_hom]; rfl
    _ = (f.eval (s (n + d + 1))).coeff (n + d) ^ p ^ d := (coeff_add_pow_pow _ n d).symm
    _ = (0 : OFlat).coeff n := by simp [h_root_s, NeZero.ne p]

variable {A R N S : Type*} [CommRing A] [MulSemiringAction FrobGal A] [SMul N A] [CommRing R]
  [CharP R p] [CommRing S] {M : Type*} [Monoid M] (n : ℕ) (g : Gp p) (x : OFlat)

/-! ### Frobenius, the Galois action and the ℤ_p-algebra structures -/

/-- For a ring A with an action of ℕ × G_p, the ring endomorphism given by the generator of ℕ
paired with the identity of G_p, the Frobenius φ. -/
def frobEnd : A →+* A := toRingHom FrobGal A (Multiplicative.ofAdd 1, 1)

/-- `W(R)` is a `ℤ_p = W(𝔽_p)`-algebra for every ring `R` of characteristic `p`. -/
instance : Algebra ℤ_[p] (WittVector p R) :=
  ((WittVector.map (castHom dvd_rfl R)).comp (equiv p).symm).toAlgebra

/-- For an `A`-algebra `S`, the Witt vectors `W(S)` are a `W(A)`-algebra through `W` of the
structure map. -/
instance (priority := low) [Algebra A S] : Algebra (WittVector p A) (WittVector p S) :=
  (WittVector.map (algebraMap ..)).toAlgebra

/-- Frobenius and `G_p` act on `O^♭`. -/
instance actOFlat : MulSemiringAction FrobGal OFlat := by
  -- `(n, g)` acts by the map induced by `g` on the tilt, followed by `x ↦ x ^ p ^ n`
  apply actionOfHoms _
    fun m ↦ (iterateFrobenius _ p m.1.toAdd).comp (PreTilt.map p (toRingHom _ _ m.2))
  · simp [show toRingHom (Gp p) OC 1 = RingHom.id OC by aesop, RingHom.ext_iff]
  · have hab (a b : Gp p) :
        toRingHom (Gp p) OC (a * b) = (toRingHom (Gp p) OC a).comp (toRingHom (Gp p) OC b) := by
      aesop (add simp mul_smul)
    simp [iterateFrobenius_def, hab, PreTilt.map_comp, pow_add, pow_mul', RingHom.ext_iff]

/-- An action of `FrobGal` on `A` induces a `MulSemiringAction` of `Gp p` on `A`. It is obtained by
composing with the right inclusion of `Gp p` into `FrobGal`. -/
instance (priority := 100) FrobGal.galAct : MulSemiringAction (Gp p) A :=
  compHom (M := FrobGal) _ (.inr ..)

@[instance 100]
lemma FrobGal.smulCommClass_gal [SMulCommClass FrobGal N A] : SMulCommClass (Gp p) N A :=
  SMul.comp.smulCommClass _

/-- The pair (n, g) of `FrobGal` acts on `A` as g followed by the n-th iterate of the Frobenius
φ. -/
@[local simp]
lemma FrobGal.smul_def (x : A) : (Multiplicative.ofAdd n, g) • x = frobEnd^[n] (g • x) := by
  -- `φ` is the action of `(ofAdd 1, 1)` and `g` that of `(1, g)`; the pair `(ofAdd n, g)` is
  -- their product `(ofAdd 1, 1) ^ n * (1, g)`
  have h_frob : ⇑(frobEnd : A →+* A) = fun y : A ↦ ((Multiplicative.ofAdd 1, 1) : FrobGal) • y :=
    rfl
  have h_gal : g • x = ((1, g) : FrobGal) • x := rfl
  have h_pair : ((Multiplicative.ofAdd n, g) : FrobGal) =
      (Multiplicative.ofAdd 1, 1) ^ n * (1, g) := by simp [← ofAdd_nsmul]
  rw [h_frob, h_gal, smul_iterate_apply, smul_smul, h_pair]

/-- The action of `g` in `G_p` commutes with the Frobenius φ. -/
@[simp]
lemma smul_frobEnd (x : A) : g • frobEnd x = frobEnd (g • x) := by
  -- `g` acts as `(1, g)` and `φ` as `(ofAdd 1, 1)`, and these two elements of `FrobGal` commute
  change ((1, g) : FrobGal) • ((Multiplicative.ofAdd 1, 1) : FrobGal) • x =
    ((Multiplicative.ofAdd 1, 1) : FrobGal) • ((1, g) : FrobGal) • x
  simp only [smul_smul, Prod.mk_mul_mk, one_mul, mul_one]

/-- For n ∈ ℕ and x in O^♭, the untilt (x^{1/p^n})^♯ in O_C of the p^n-th root of x. -/
def OFlat.untiltRoot : OC := untilt ((frobeniusEquiv (PreTilt OC p) p).symm^[n] x)

/-- Modulo p, the untilt of the p^n-th root of x is the n-th coordinate of x. -/
lemma OFlat.mk_untiltRoot : ↑(untiltRoot n x) = x.coeff n := by simp [untiltRoot]

open algebraMap

/-- For a ring homomorphism f : R → S of rings of characteristic p, the induced map W(f) of Witt
vectors commutes with the maps from ℤ_p. -/
lemma wittVector_map_algebraMap [CharP S p] (f : R →+* S) (a : ℤ_[p]) :
    WittVector.map (p := p) f a = algebraMap ℤ_[p] (WittVector p S) a := by
  -- Both sides are `W` of a ring map `𝔽_p → S` applied to `a` in `W(𝔽_p) = ℤ_p`, and any two ring
  -- maps out of `𝔽_p` agree.
  have h_comp : f.comp (castHom dvd_rfl R) = castHom dvd_rfl S := (f.comp _).ext_zmod _
  change WittVector.map f (WittVector.map (castHom dvd_rfl R) ((equiv p).symm a)) =
    WittVector.map (castHom dvd_rfl S) ((equiv p).symm a)
  ext i
  simp [← h_comp]

instance [MulSemiringAction M R] : SMulCommClass M ℤ_[p] (WittVector p R) :=
  ⟨fun _ ↦ map_smul (AlgHom.mk _ (wittVector_map_algebraMap _))⟩

instance [MulSemiringAction M Ainf] [MulSemiringAction M S] [Algebra ℤ_[p] S] [Algebra Ainf S]
    [IsScalarTower ℤ_[p] Ainf S] [SMulCommClass M ℤ_[p] Ainf] [SMulDistribClass M Ainf S] :
    SMulCommClass M ℤ_[p] S where
  smul_comm := by simp [← algebraMap_smul Ainf, smul_distrib_smul]

instance [CharP S p] [Algebra R S] : IsScalarTower ℤ_[p] (WittVector p R) (WittVector p S) :=
  .of_algHom ⟨_, wittVector_map_algebraMap _⟩

lemma OFlat.frobEnd_apply : frobEnd x = x ^ p := by
  -- `φ = (ofAdd 1, 1)` acts by the identity of `G_p` on the tilt followed by `x ↦ x ^ p`
  have h_frob : frobEnd x = PreTilt.map p (toRingHom (Gp p) OC 1) x ^ p ^ 1 := rfl
  simp [h_frob, show toRingHom (Gp p) OC 1 = RingHom.id OC by aesop]

variable {G : Type*} [Group G] [MulSemiringAction G OFlat] [MulSemiringAction FrobGal S]

instance [SMul S A] [SMulDistribClass FrobGal S A] : SMulDistribClass (Gp p) S A :=
  ⟨fun g ↦ smul_distrib_smul ((1, g) : FrobGal)⟩

@[simp]
lemma frobEnd_algebraMap [Algebra S A] [SMulDistribClass FrobGal S A] (x : S) :
    frobEnd (x : A) = frobEnd x := smul_algebraMap_eq_algebraMap_smul ..

instance : MulSemiringAction G CFlat := IsFractionRing.mulSemiringAction _ OFlat _

deriving instance Algebra ℤ_[p], Algebra Ainf, IsScalarTower ℤ_[p] Ainf, MulSemiringAction G,
  SMulCommClass G ℤ_[p] for @WittCFlat p _

instance : SMulDistribClass G Ainf WittCFlat :=
  smulDistribClass_of_tower fun _ : Ainf ↦ ext fun _ ↦ smul_algebraMap_eq_algebraMap_smul ..

instance : CharP (IsLocalRing.ResidueField OFlat) p := .of_ringHom_of_ne_zero (mk _) _ out

instance : IsAlgClosed CFlat := (OFlat.isAbsIntegrallyClosed.of_isLocalization _⁰).isAlgClosed

end Ainf

/-!
## The kernel of θ on A_inf and divisibility by ξ, μ and τ

Witt-vector surjectivity and the lifting of divisibility from the constant coefficient follow from
Tau Ceti: a claim is checked modulo `p`, on the constant coefficient in `O^♭`, and then lifted.
-/

section ThetaKernel

open WittVector IsLocalRing MulSemiringAction Variety ZMod Set

variable {p : ℕ} [ThePrime p]

/-- The ℤ_p-algebra homomorphism A_inf = W(O^♭) → W(k), for k the residue field of O^♭, that
applies the residue map O^♭ → k to each Witt coordinate. -/
noncomputable def toWittResidue : Ainf →ₐ[ℤ_[p]] WittVector p (ResidueField OFlat) :=
  ⟨map (residue OFlat), wittVector_map_algebraMap (residue OFlat)⟩

variable {k : Type*} [CommRing k] [CharP k p] [PerfectRing k p] {a c : WittVector p k}

/-! ### Witt vectors over a perfect ring: lifting from the reduction modulo `p` -/

/-- For k perfect of characteristic p, the prime p divides a Witt vector `a` in W(k) if and only
if its zeroth coordinate vanishes. -/
lemma Witt.p_dvd_iff : ↑p ∣ a ↔ constantCoeff a = 0 := by
  simp [← Ideal.mem_span_singleton, ← ker_constantCoeff]

omit [PerfectRing k p] in
/-- A Witt vector `a` in W(k), for `k` of characteristic `p`, is a unit if and only if its zeroth
coordinate is a unit in k. -/
lemma Ainf.isUnit_iff_isUnit_constantCoeff : IsUnit a ↔ IsUnit (constantCoeff a) :=
  ⟨fun h ↦ h.map constantCoeff, fun h ↦ ⟨mkUnit h.unit_spec.symm, rfl⟩⟩

open Ideal Period.Witt Function RingHom PadicComplex Pi OFlat NeZero Fact SModEq IsUltrametricDist

/-- Artin–Schreier–Witt equations: let k be a non-zero perfect, absolutely integrally closed ring of
characteristic p, and let φ be the Frobenius of W(k). Then for all a, s in W(k) the equation
φ(y) − sy = a has a solution y in W(k). -/
lemma Witt.artin_schreier_witt [Nontrivial k] [h : IsAbsIntegrallyClosed k] (s a : WittVector p k) :
    ∃ y : WittVector p k, WittVector.frobenius y - s * y = a := by
  -- Modulo `p` the left side is `x ↦ x ^ p - s₀ * x`, with `s₀` the reduction of `s`; this map is
  -- onto since `k` is absolutely integrally closed.
  rw [frobenius_eq_map_frobenius]
  exact WittVector.surjective_map_sub_mul_map s (_root_.frobenius k p) 1
    (h.exists_pow_sub_mul_eq p _) a

/-- In W(k), the power p ^ m divides `a - c` if and only if `a` and `c` have the same first
`m` Witt coordinates. -/
lemma Witt.pow_dvd_sub_iff_coeff_eq {m : ℕ} :
    (p : WittVector p k) ^ m ∣ a - c ↔ ∀ i < m, a.coeff i = c.coeff i := by
  rw [← mem_span_singleton, mem_span_p_pow_iff_le_coeff_eq_zero,
    le_coeff_eq_iff_le_sub_coeff_eq_zero]

/-- In W(k), `a` lies in the ideal (p, c) if and only if the zeroth coordinate of `c` divides that
of `a`. -/
lemma Witt.mem_span_pair_iff : a ∈ span {↑p, c} ↔ constantCoeff c ∣ constantCoeff a := by
  simp [span_insert, ← ker_constantCoeff, sup_comm, map_span, mem_span_singleton,
    ← comap_map_of_surjective', constantCoeff_surjective]

/-- Let I be an ideal of W(k), k perfect of characteristic p, such that px ∈ I implies x ∈ I. If
c ∈ I and its zeroth Witt coordinate divides that of every element of I, then c generates I. -/
lemma Witt.dvd_of_mem_of_constantCoeff_dvd {I : Ideal (WittVector p k)} (hc : c ∈ I)
    (h_sat : ∀ x : WittVector p k, (p : WittVector p k) * x ∈ I → x ∈ I)
    (h_mod_p : ∀ a ∈ I, constantCoeff c ∣ constantCoeff a) :
    ∀ a ∈ I, c ∣ a := by
  intro a ha
  exact mem_span_singleton.mp
    (WittVector.eq_span_singleton_of_coeff_zero_dvd c hc h_sat h_mod_p ▸ ha)

variable (g : Gp p) (m : FrobGal) (t : OFlat) (a : Ainf)

/-! ### The actions of Frobenius and Galois, units, and generators of the kernel of `θ` -/

/-- On `A_inf = W(O^♭)` the Frobenius `φ` of the action of `ℕ × G_p` is the Frobenius of Witt
vectors, since `φ` acts on `O^♭` as `x ↦ x ^ p`. -/
lemma frobEnd_eq_frobenius : frobEnd a = WittVector.frobenius a := by
  ext n
  -- `φ` acts on the Witt coordinates
  change frobEnd (a.coeff n) = (WittVector.frobenius a).coeff n
  rw [OFlat.frobEnd_apply, coeff_frobenius_charP]

lemma smul_teichmuller : m • teichmuller p t = teichmuller p (m • t) :=
  map_teichmuller p (toRingHom FrobGal OFlat m) t

@[simp]
lemma frobEnd_teichmuller : frobEnd (teichmuller p t) = teichmuller p t ^ p := by
  rw [show frobEnd (teichmuller p t) = teichmuller p (frobEnd t) from smul_teichmuller _ t,
    OFlat.frobEnd_apply, map_pow]

lemma iterate_frobEnd_teichmuller (j : ℕ) (x : OFlat) :
    frobEnd^[j] (teichmuller p x) = teichmuller p (x ^ p ^ j) := by
  induction j with
  | zero => simp
  | succ j ih => simp [iterate_succ_apply', ih, ← map_pow, ← pow_mul, ← pow_succ]

/-- The untilt of `φ ^ n g t` is `(g t^♯) ^ p ^ n`. -/
lemma untilt_ofAdd_smul (n : ℕ) (g : Gp p) (t : OFlat) :
    ((Multiplicative.ofAdd n, g) • t).untilt = (g • t.untilt) ^ p ^ n := by
  -- `(n, g)` acts on `O^♭` by the map that `g` induces on the tilt, then by `x ↦ x ^ p ^ n`
  change (PreTilt.map p (toRingHom (Gp p) OC g) t ^ p ^ n).untilt = _
  rw [map_pow, PreTilt.untilt_natural, toRingHom_apply]

lemma untilt_frobGal_smul : (m • t).untilt = (m.2 • t.untilt) ^ p ^ m.1.toAdd := by
  simpa using untilt_ofAdd_smul m.1.toAdd m.2 t

@[simp]
lemma theta_smul : theta (g • a) = g • theta a := by
  -- `g` acts on Witt coordinates by `PreTilt.map`, raised to the power `p ^ 0 = 1`.
  have h_act : g • a = a.map (PreTilt.map p (toRingHom _ _ g)) := WittVector.ext fun n ↦ pow_one _
  rw [h_act, WittVector.theta_natural, toRingHom_apply]

lemma constantCoeff_frobEnd : constantCoeff (frobEnd a) = constantCoeff a ^ p := by
  rw [frobEnd_eq_frobenius, constantCoeff_apply, constantCoeff_apply, coeff_frobenius_charP]

lemma constantCoeff_iterate_frobEnd (n : ℕ) :
    constantCoeff (frobEnd^[n] a) = constantCoeff a ^ p ^ n := by
  induction n with
  | zero => simp
  | succ n ih => rw [iterate_succ_apply', constantCoeff_frobEnd, ih, ← pow_mul, ← pow_succ]

variable {c a δ y : Ainf}

open Ainf Multiplicative

/-- Let `a ∈ A_inf` divide each of its conjugates `g' • a` under the Galois group `G_p`. Then
for every `g ∈ G_p` the conjugate `g • a` is associated to `a`. -/
lemma associated_smul_of_dvd (h : ∀ g : Gp p, a ∣ g • a) : Associated (g • a) a := by
  -- apply `g` to `a ∣ g⁻¹ • a`
  have h_inv : g • a ∣ g • (g⁻¹ • a) := map_dvd (toRingHom (Gp p) Ainf g) (h g⁻¹)
  rw [smul_inv_smul] at h_inv
  exact associated_of_dvd_dvd h_inv (h g)

/-- `ℤ_p = W(𝔽_p)` acts faithfully on `W(k)`, for every perfect ring `k` of characteristic `p`. -/
instance : FaithfulSMul ℤ_[p] (WittVector p k) := by
  simpa [faithfulSMul_iff_algebraMap_injective, algebraMap_toAlgebra] using
    map_injective _ (castHom_injective k)

/-- Let c ∈ A_inf with θ(c) = 0, and let c₀ ∈ O^♭ be its reduction modulo p. If c₀^♯ divides p
in the integers of C_p, then c generates the kernel of θ. -/
lemma dvd_of_theta_eq_zero_of_untilt_dvd {c a : Ainf} (hc : theta c = 0)
    (hc_dvd : (constantCoeff c).untilt ∣ (p : OC)) (ha : theta a = 0) :
    c ∣ a := by
  -- Apply `dvd_of_mem_of_constantCoeff_dvd` to the ideal `ker θ`, saturated for `p` as `p ≠ 0` in
  -- the domain `OC`.
  have h_sat : ∀ x : Ainf, (p : Ainf) * x ∈ ker theta → x ∈ ker theta := by simp [ne p]
  refine dvd_of_mem_of_constantCoeff_dvd (I := ker theta) (mem_ker.mpr hc) h_sat
    (fun x hx ↦ ?_) a ha
  -- modulo `p`, `θ x` is the untilt of the reduction of `x`, and `θ x = 0`
  have h_dvd : ↑p ∣ (constantCoeff x).untilt := by
    simp [← Quotient.eq_zero_iff_dvd, ← mk_fontaineTheta, mem_ker.mp hx]
  -- divisibility in `O^♭` can be read on the untilts
  exact PreTilt.untilt_dvd_untilt_iff.mp (hc_dvd.trans h_dvd)

/-- `A_inf = W(O^♭)` acts faithfully on `W(C^♭)`, as `O^♭` embeds in its fraction field `C^♭`. -/
instance : FaithfulSMul Ainf WittCFlat := by
  simpa [faithfulSMul_iff_algebraMap_injective, algebraMap_toAlgebra] using
    map_injective _ (IsFractionRing.injective OFlat CFlat)

/-- If `p` does not divide `a` in `A_inf`, then `a` becomes a unit in the Witt vectors `W(C^♭)` of
the fraction field `C^♭` of `O^♭`. -/
lemma isUnit_algebraMap_wittCFlat_of_not_p_dvd (h : ¬↑p ∣ a) :
    IsUnit (algebraMap Ainf WittCFlat a) := by
  -- The constant coefficient `a₀` of `a` is not zero, so it is a unit of the field `C^♭`; and a
  -- Witt vector over a perfect field is a unit when its constant coefficient is.
  have h_ne : constantCoeff a ≠ 0 := mt p_dvd_iff.mpr h
  simp_all [WittCFlat, algebraMap_toAlgebra, isUnit_iff_isUnit_constantCoeff]

/-- A Witt vector over a domain of characteristic `p` whose coordinates are fixed by `x ↦ x ^ p` is
a `p`-adic integer. -/
lemma exists_algebraMap_eq_of_frobenius_eq {k : Type*} [CommRing k] [IsDomain k] [CharP k p]
    (a : WittVector p k) (h_frobenius : WittVector.frobenius a = a) :
    ∃ c : ℤ_[p], algebraMap ℤ_[p] (WittVector p k) c = a := by
  obtain ⟨c, hc⟩ := TauCeti.WittVector.frobenius_eq_self_iff.mp h_frobenius
  refine ⟨c, ?_⟩
  simpa [TauCeti.WittVector.padicConstants_apply, algebraMap_toAlgebra] using hc

/-- The Frobenius `φ` is bijective on `A_inf`, because `O^♭` is a perfect ring. -/
lemma frobEnd_bijective : Bijective (frobEnd : Ainf → Ainf) := by
  rw [funext frobEnd_eq_frobenius]
  exact frobenius_bijective p OFlat

/-! ### The elements `ξ`, `μ`, `τ` under `φ`, `θ` and reduction, and the kernel of `θ` -/

/-- Fontaine's `θ : A_inf → O_C` is onto, because `O_C` is absolutely integrally closed. -/
lemma theta_surjective : Surjective theta := fontaineTheta_surjective_of_isAbsIntegrallyClosed

@[simp]
lemma frobEnd_tau : frobEnd tau = mu := by simp [tau, mu_eq, epsTilt]

/-- `θ τ = ζ_p - 1` is not zero, where `ζ_p = (ε^{1/p})^♯` is a primitive `p`-th root of unity. -/
@[simp]
lemma theta_tau_ne_zero : theta tau ≠ 0 := by
  simp [tau, sub_eq_zero, isPrimitiveRoot_untilt_epsRoot.ne_one (Fact.out : p.Prime).one_lt]

lemma iterate_frobEnd_mu (j : ℕ) : frobEnd^[j] mu = teichmuller p (epsTilt ^ p ^ j) - 1 := by
  simp [mu_eq, ← iterate_frobEnd_teichmuller]

@[simp]
lemma theta_iterate_frobEnd_mu (j : ℕ) : theta (frobEnd^[j] mu) = 0 := by
  -- `(ε ^ p ^ j)^♯ = (ε^♯) ^ p ^ j = 1`
  simp [iterate_frobEnd_mu]

/-- `θ μ = 0`, since `μ = [ε] - 1` and `ε^♯ = 1`. -/
lemma theta_mu : theta mu = 0 := by simpa using theta_iterate_frobEnd_mu 0

/-- `θ ξ = 0`, because `θ ξ * θ τ = θ μ = 0` and `θ τ ≠ 0`. -/
@[simp]
lemma theta_xi : theta xi = 0 := by
  exact (mul_eq_zero.mp (by rw [← map_mul, xi_mul_tau, theta_mu])).resolve_right theta_tau_ne_zero

/-- `τ` reduces to zero in the Witt vectors of the residue field of `O^♭`. -/
lemma toWittResidue_tau : toWittResidue tau = 0 := by
  -- `τ` is not a unit: otherwise `μ = φ τ` and `θ μ` are units, but `θ μ = 0`.
  have h_tau : ¬IsUnit tau := by
    intro h_unit
    have h_mu : IsUnit mu := by simpa using h_unit.map frobEnd
    exact (h_mu.map theta).ne_zero theta_mu
  -- so the constant coefficient `ε^{1/p} - 1` of `τ` is not a unit, and `ε^{1/p}` has residue `1`
  have h_coeff : ¬IsUnit (constantCoeff tau) := mt isUnit_iff_isUnit_constantCoeff.mpr h_tau
  rw [tau, map_sub, map_one, constantCoeff_apply, teichmuller_coeff_zero] at h_coeff
  have h_res : residue OFlat epsRoot = 1 := by
    have h_zero : residue OFlat (epsRoot - 1) = 0 := by
      rwa [← residue_ne_zero_iff_isUnit, not_not] at h_coeff
    rwa [map_sub, map_one, sub_eq_zero] at h_zero
  have h_teich : toWittResidue (teichmuller p epsRoot) = teichmuller p (residue OFlat epsRoot) :=
    map_teichmuller p (residue OFlat) epsRoot
  simp [tau, h_teich, h_res]

variable {t g}

/-- If `g⁻¹` acts on the integers of `ℚ̄_p` as `x ↦ x ^ p ^ n` modulo the maximal ideal, then
`φ ^ n g` acts trivially on the Witt vectors of the residue field of `O^♭`. -/
lemma toWittResidue_smul_of_isFrob {n : ℕ} (h_isFrob : IsFrob (intQpBar p) (p ^ n) g⁻¹) (a : Ainf) :
    toWittResidue ((ofAdd n, g) • a) = toWittResidue a := by
  -- `g⁻¹ • y ≡ y ^ p ^ n` modulo the maximal ideal: true on the integers of `ℚ̄_p`, and a closed
  -- condition on `ℂ_p` (balls are open and closed)
  have h_frob (y : ℂ_[p]) : dist y 0 ≤ 1 → dist (g⁻¹ • y - y ^ p ^ n) 0 < 1 := by
    induction y using UniformSpace.Completion.induction_on with
    | hp => exact isClosed_frobenius_congruence (continuous_const_smul g⁻¹) (p ^ n)
    | ih y =>
      intro h_le
      have h_norm : ‖g⁻¹ • y - y ^ p ^ n‖ < 1 :=
        isFrob_intQpBar_iff.mp h_isFrob y (by simpa using h_le)
      -- the embedding of `ℚ̄_p` in `ℂ_p` commutes with `g⁻¹`, powers and differences
      simpa [↓UniformSpace.Completion.algEquiv_smul_coe, coe_eq, ← map_pow, ← map_sub] using h_norm
  refine WittVector.ext fun i ↦ ?_
  let x : OFlat := a.coeff i
  -- the `i`-th coordinates are the residues of `(φ ^ n g) • x` and `x`; suppose that their
  -- difference is a unit of `O^♭`
  suffices h_res : residue OFlat ((ofAdd n, g) • x) = residue OFlat x from h_res
  rw [← sub_eq_zero, ← map_sub]
  by_contra h_ne
  have h_unit : IsUnit ((ofAdd n, g) • x - x) := (residue_ne_zero_iff_isUnit _).mp h_ne
  -- it is the constant coefficient of a difference of Teichmüller lifts, which is then a unit
  have hx : IsUnit (teichmuller p ((ofAdd n, g) • x) - teichmuller p x) := by
    rwa [isUnit_iff_isUnit_constantCoeff, map_sub]
  -- so its image under `θ` has norm at least `1`, against `h_frob` at the point `y₀ = g • x^♯`
  let y₀ : ℂ_[p] := ((g • x.untilt : OC) : ℂ_[p])
  have h_norm_ge : 1 ≤ dist (g⁻¹ • y₀ - y₀ ^ p ^ n) 0 := by
    simpa [y₀, norm_sub_rev, untilt_frobGal_smul, valRingCp.dvd_iff_norm_le,
      isUnit_iff_dvd_one] using hx.map theta
  exact (h_frob y₀ (by simp [y₀, ← mem_valRingCp])).not_ge h_norm_ge

/-- `p` does not divide `τ`: otherwise the reduction `ε^{1/p} - 1` of `τ` modulo `p` is zero, so
`ε^{1/p} = 1` and `θ τ = 0`. -/
lemma not_p_dvd_tau : ¬↑p ∣ tau := by
  intro h_dvd
  rw [tau, p_dvd_iff, map_sub, map_one, sub_eq_zero] at h_dvd
  have h_eps : epsRoot = 1 := by simpa using h_dvd
  exact theta_tau_ne_zero (by simp [tau, h_eps])

/-- The reduction `ε - 1` of `μ` modulo `p` is not zero. -/
lemma constantCoeff_mu_ne_zero : constantCoeff mu ≠ 0 := by
  simp [← frobEnd_tau, constantCoeff_frobEnd, ← p_dvd_iff, not_p_dvd_tau, ne p,
    -constantCoeff_apply]

/-- Fontaine's description of the kernel of `θ : A_inf → O_C`: it is generated by `ξ` (Tau Ceti's
`TauCeti.Huber.IsRingOfIntegralElements.ker_fontaineTheta_eq_span_cyclotomicXi`), since
`ζ_p = (ε^{1/p})^♯` is a primitive `p`-th root of unity. -/
lemma ker_theta_eq_span_xi : ker theta = span {xi} := by
  have h_sum := isPrimitiveRoot_untilt_epsRoot.geom_sum_eq_zero (Fact.out : p.Prime).one_lt
  rw [← frobeniusEquiv_symm_epsTilt] at h_sum
  exact valRingCp.isRingOfIntegralElements.ker_fontaineTheta_eq_span_cyclotomicXi h_sum

/-- For `a ∈ A_inf`, `θ a = 0` if and only if `ξ` divides `a`. -/
lemma theta_eq_zero_iff_xi_dvd : theta a = 0 ↔ xi ∣ a := by
  rw [← mem_ker, ker_theta_eq_span_xi, mem_span_singleton]

/-- `p` does not divide `ξ`: otherwise it divides `ξ τ = μ`, whose reduction modulo `p` is not
zero. -/
@[simp] lemma not_p_dvd_xi : ¬↑p ∣ xi := by
  intro h
  exact constantCoeff_mu_ne_zero (p_dvd_iff.mp (by simpa [← xi_mul_tau] using h.mul_right tau))

/-- In `O^♭` every non-zero element divides a power of any given non-unit. -/
lemma OFlat.exists_dvd_pow {u : OFlat} (hu : ¬IsUnit u) (ht : t ≠ 0) : ∃ n : ℕ, t ∣ u ^ n := by
  -- Units, zero and divisibility in `OFlat` can be read on the untilts in `OC`.
  simp_all [OFlat, ← zero_dvd_iff, ← PreTilt.untilt_dvd_untilt_iff, OC.exists_dvd_pow,
    ← theta_teichmuller, isUnit_iff_dvd_one]

/-! ### Adic separation of `O^♭` and divisibility by `μ` and `τ` -/

/-- If `r` is nilpotent, then `shiftDiff R r` is bijective on sequences in `R`: it is `1` minus the
nilpotent operator `r • shift`. -/
lemma existsUnique_shiftDiff_eq_of_pow_eq_zero {R : Type} [CommRing R] {r : R} {N : ℕ}
    (hr : r ^ N = 0) (b : ℕ → R) :
    ∃! a : ℕ → R, shiftDiff R r a = b := by
  have h_nil : IsNilpotent (r • LinearMap.funLeft R R Nat.succ : Module.End R (ℕ → R)) :=
    ⟨N, by simp [smul_pow, hr]⟩
  -- `shiftDiff R r` is the unit `1 - r • shift` of `Module.End R (ℕ → R)`
  exact ((Module.End.isUnit_iff _).mp h_nil.isUnit_one_sub).existsUnique b

/-- If `t ∈ O^♭` is not a unit, then each coordinate `PreTilt.coeff k t` of `t` in `O_C / p` is
nilpotent. -/
lemma OFlat.exists_pow_coeff_eq_zero (h : ¬IsUnit t) (k : ℕ) :
    ∃ N : ℕ, PreTilt.coeff k t ^ N = 0 := by
  -- The untilt of a nonunit is a nonunit, so a power of it is divisible by `p`.
  have h_untilt : ¬IsUnit t.untilt := by
    simpa [OFlat, isUnit_iff_dvd_one, ← PreTilt.untilt_dvd_untilt_iff] using h
  obtain ⟨N, hN⟩ := OC.exists_dvd_pow h_untilt
    (Nat.cast_ne_zero.mpr (Fact.out : Nat.Prime p).ne_zero)
  have h_zero : PreTilt.coeff 0 t ^ N = 0 := by
    rw [← PreTilt.mk_untilt_eq_coeff_zero, ← map_pow (Ideal.Quotient.mk _)]
    exact Ideal.Quotient.eq_zero_iff_mem.mpr (Ideal.mem_span_singleton.mpr hN)
  -- The `p ^ k`-th power of coordinate `k` is the zeroth coordinate.
  have h_pow : PreTilt.coeff k t ^ p ^ k = PreTilt.coeff 0 t := by
    simpa only [zero_add, iterate_frobenius, map_pow] using
      (PreTilt.coeff_iterate_frobenius 0 k t)
  exact ⟨p ^ k * N, by rwa [pow_mul, h_pow]⟩

/-- If `t ∈ O^♭` is not a unit, then `O^♭` is `t`-adically separated. -/
lemma OFlat.isHausdorff_span_singleton_of_not_isUnit (h : ¬IsUnit t) :
    IsHausdorff (span {t}) OFlat := by
  -- An element `x` divisible by all powers of `t` has all coordinates zero, since each coordinate
  -- of `t` is nilpotent.
  choose N hN using exists_pow_coeff_eq_zero h
  refine ⟨fun x hx ↦ Perfection.ext fun k ↦ ?_⟩
  have h_coeff_dvd : PreTilt.coeff k (t ^ N k) ∣ PreTilt.coeff k (x - 0) :=
    map_dvd (PreTilt.coeff k) ((TauCeti.sModEq_span_singleton_pow_iff ..).mp (hx (N k)))
  rw [map_pow, hN k, zero_dvd_iff, sub_zero] at h_coeff_dvd
  exact h_coeff_dvd.trans (map_zero (PreTilt.coeff k)).symm

/-- If `t ∈ O^♭` is not a unit, then the map `(x_j) ↦ (x_j - t x_{j+1})` on sequences in `O^♭` is
surjective. -/
lemma OFlat.shiftDiff_surjective_of_not_isUnit (h : ¬IsUnit t) :
    Surjective (shiftDiff OFlat t) := by
  -- Solve the equation in each coordinate, where `t` is nilpotent; by uniqueness the solutions
  -- are compatible under Frobenius, so they form a sequence in `O^♭`.
  intro b
  choose N hN using exists_pow_coeff_eq_zero h
  have h_exists (k : ℕ) : ∃! u : ℕ → ModP OC p,
      shiftDiff (ModP OC p) (PreTilt.coeff k t) u = fun n ↦ PreTilt.coeff k (b n) :=
    existsUnique_shiftDiff_eq_of_pow_eq_zero (hN k) _
  choose u hu h_unique using h_exists
  have h_frob (k : ℕ) : u (k + 1) ^ p = u k := by
    apply h_unique k
    -- raise the equation for `k + 1` to the power `p`
    simpa [funext_iff, shiftDiff, sub_pow_char, mul_pow] using congrArg (· ^ p) (hu (k + 1))
  -- for each `n`, the coordinates `u k n` form an element of the tilt
  let y : ℕ → OFlat := fun n ↦ ⟨fun k ↦ u k n, fun k ↦ congrFun (h_frob k) n⟩
  exact ⟨y, funext fun n ↦ Perfection.ext fun k ↦ congrFun (hu k) n⟩

/-- If a ∈ A_inf satisfies θ(φ^j a) = 0 for all j ≥ 0, then μ divides a in A_inf. -/
lemma mu_dvd_of_theta_frobEnd {a : Ainf} (h_theta : ∀ j : ℕ, theta (frobEnd^[j] a) = 0) :
    mu ∣ a := by
  have hε : IsPrimitiveRoot
      (PreTilt.untilt ((frobeniusEquiv OFlat p).symm epsTilt)) p := by
    rw [frobeniusEquiv_symm_epsTilt]
    exact isPrimitiveRoot_untilt_epsRoot
  have hφ : (WittVector.frobeniusEquiv p OFlat : Ainf → Ainf) = frobEnd := by
    funext x
    rw [WittVector.frobeniusEquiv_apply, ← frobEnd_eq_frobenius]
  have h_theta' (j : ℕ) : fontaineTheta OC p
      ((⇑(WittVector.frobeniusEquiv p OFlat))^[j] a) = 0 := by
    rw [hφ]
    exact h_theta j
  -- The library uses the integers for the norm valuation on `ℂ_[p]`, which are `OC`.
  have hp_nonunit : Fact ¬IsUnit (p : OC) := inferInstance
  have hcomplete : IsAdicComplete (span {(p : OC)}) OC := inferInstance
  have h_mu : TauCeti.Perfectoid.mu p epsTilt ∣ a :=
    @PreTilt.mu_dvd_of_forall_fontaineTheta_iterate_eq_zero p _ (ℂ_[p]) _ _ _ _
      hp_nonunit hcomplete epsTilt hε a h_theta'
  simpa only [mu_eq, TauCeti.Perfectoid.mu_eq] using h_mu

/-- If a in A_inf satisfies θ(φ^j a) = 0 for all j ≥ 1, then τ = [ε^{1/p}] − 1 divides a in
A_inf. -/
lemma tau_dvd_of_theta_frobEnd (h_theta : ∀ j : ℕ, theta (frobEnd^[j + 1] a) = 0) :
    tau ∣ a := by
  -- `φ a` is killed by every `θ ∘ φ ^ j`, so `φ τ = μ` divides `φ a`; then apply the bijection `φ`.
  have h_phi : frobEnd tau ∣ frobEnd a := by simpa using mu_dvd_of_theta_frobEnd h_theta
  exact (map_dvd_iff (MulEquiv.ofBijective (frobEnd : Ainf →+* Ainf) frobEnd_bijective)).mp h_phi

/-! ### Primes and adic completeness of `A_inf` -/

/-- `p` is a prime element of `A_inf`, because `A_inf / p = O^♭` is a domain. -/
lemma Ainf.prime_p : Prime (p : Ainf) :=
  -- `p ∣ x` means that the constant coefficient of `x` in the domain `O^♭` is zero
  (span_singleton_prime (p_ne_zero p OFlat)).mp
    (ker_constantCoeff (k := OFlat) ▸ ker_isPrime constantCoeff)

/-- If `p` does not divide `δ`, every non-unit of `A_inf` lies in the radical of `(p, δ)`. -/
lemma Ainf.mem_radical_of_not_isUnit (h : ¬IsUnit a) (hδ : ¬↑p ∣ δ) :
    a ∈ radical (span {↑p, δ}) := by
  -- The constant coefficient `a₀` of `a` is a non-unit of `O^♭` and that of `δ` is not zero, so
  -- `δ₀ ∣ a₀ ^ n` for some `n`, which says `a ^ n ∈ (p, δ)`.
  have h_a0 : ¬IsUnit (constantCoeff a) := mt isUnit_iff_isUnit_constantCoeff.mpr h
  have h_δ0 : constantCoeff δ ≠ 0 := mt p_dvd_iff.mpr hδ
  obtain ⟨n, hn⟩ : ∃ n : ℕ, constantCoeff δ ∣ constantCoeff a ^ n := OFlat.exists_dvd_pow h_a0 h_δ0
  exact ⟨n, by rwa [mem_span_pair_iff, map_pow]⟩

/-- For every `n : ℕ` and `x ∈ A_inf` the equation `φ c - ξ ^ n * c = x` has a solution `c ∈ A_inf`,
by the Artin–Schreier–Witt equations over the absolutely integrally closed ring `O^♭`. -/
lemma Ainf.exists_frobEnd_sub_xi_pow_mul_eq (n : ℕ) (x : Ainf) :
    ∃ c : Ainf, frobEnd c - xi ^ n * c = x := by
  have h_aic : IsAbsIntegrallyClosed OFlat := OFlat.isAbsIntegrallyClosed
  simpa only [frobEnd_eq_frobenius] using artin_schreier_witt (xi ^ n) x

/-- Multiplication by a prime `q` can be cancelled against a power of `q` in the ideal
`(q ^ (n + 1), d)` when `q` does not divide `d`. -/
lemma _root_.Prime.mul_mem_span_pair_pow_succ_iff {R : Type*} [CommRing R] [IsDomain R]
    {q d x : R} (hq : Prime q) (hd : ¬q ∣ d) (n : ℕ) :
    q * x ∈ Ideal.span {q ^ (n + 1), d} ↔ x ∈ Ideal.span {q ^ n, d} := by
  -- Membership of `x` in `(q ^ n, d)` means `d ∣ x + b * q ^ n` for some `b`.
  simp only [Ideal.mem_span_insert', Ideal.mem_span_singleton]
  refine exists_congr fun b ↦ ?_
  have h_factor : q * x + b * q ^ (n + 1) = q * (x + b * q ^ n) := by
    rw [pow_succ]
    ring
  rw [h_factor]
  exact ⟨fun h ↦ (hq.left_dvd_or_dvd_right_of_dvd_mul h).resolve_left hd,
    fun h ↦ dvd_mul_of_dvd_right h q⟩

/-- Let a, c be non-units of A_inf and δ, y ∈ A_inf with δ not divisible by p. If for every m
there is x with y − δx ∈ (a, c)^m, then δ divides y. -/
lemma dvd_of_forall_exists_sub_mem_span_pow (ha : ¬IsUnit a) (hc : ¬IsUnit c) (hδ : ¬↑p ∣ δ)
    (h_approx : ∀ m : ℕ, ∃ x : Ainf, y - δ * x ∈ span {a, c} ^ m) :
    δ ∣ y := by
  -- Apply `dvd_of_mem_of_constantCoeff_dvd` to the ideal `I = ⋂ m, (p ^ m, δ)`, which contains `δ`.
  refine dvd_of_mem_of_constantCoeff_dvd (I := ⨅ m : ℕ, span {↑(p ^ m), δ}) (by aesop) ?_ ?_ y
    (mem_iInf.mpr fun m ↦ ?_)
  · -- The intersection `I` is `p`-saturated by cancelling `p` against each higher power.
    simp only [mem_iInf, Nat.cast_pow]
    intro x hx m
    exact (Ainf.prime_p.mul_mem_span_pair_pow_succ_iff hδ m).1 (hx (m + 1))
  · -- `I ⊆ (p, δ)`: take `m = 1`
    intro x hx
    simpa [mem_span_pair_iff] using mem_iInf.mp hx 1
  · -- `y ∈ (p ^ m, δ)`: the non-units `a`, `c` lie in the radical of `(p, δ)`, which is contained
    -- in the radical of `(p ^ m, δ)`; so a power of `(a, c)` lies in `(p ^ m, δ)`
    have hp_mem_rad : (p : Ainf) ∈ radical (span {↑(p ^ m), δ}) :=
      mem_radical_iff.mpr ⟨m, subset_span (by simp)⟩
    have hδ_mem_rad : δ ∈ radical (span {↑(p ^ m), δ}) :=
      mem_radical_iff.mpr ⟨1, subset_span (by simp)⟩
    have h_rad : radical (span {↑p, δ}) ≤ radical (span {↑(p ^ m), δ}) :=
      radical_le_radical_iff.mpr (span_le.mpr (pair_subset hp_mem_rad hδ_mem_rad))
    have h_ac : span {a, c} ≤ radical (span {↑(p ^ m), δ}) := span_le.mpr <| pair_subset
      (h_rad (mem_radical_of_not_isUnit ha hδ)) (h_rad (mem_radical_of_not_isUnit hc hδ))
    obtain ⟨N, hN⟩ : ∃ N : ℕ, span {a, c} ^ N ≤ span {↑(p ^ m), δ} :=
      exists_pow_le_of_le_radical_of_fg h_ac (Submodule.fg_span (by simp))
    obtain ⟨x, hx⟩ := h_approx N
    have h_δx : δ * x ∈ span {↑(p ^ m), δ} := mul_mem_right x _ (subset_span (by simp))
    exact (Submodule.sub_mem_iff_left _ h_δx).mp (hN hx)

/-- For a non-unit `a`, the map `(x j) ↦ (x j - a * x (j + 1))` on sequences in `A_inf` is onto. -/
lemma Ainf.shiftDiff_surjective (h : ¬IsUnit a) : Surjective (shiftDiff Ainf a) := by
  -- View sequences in `Ainf` as Witt vectors over `ℕ → OFlat`. TauCeti lifts the solution of
  -- the shift equation modulo `p` from `OFlat.shiftDiff_surjective_of_not_isUnit`.
  intro b
  have h_perfect : PerfectRing (ℕ → OFlat) p := ⟨(bijective_frobenius _ p).comp_left⟩
  let shift : (ℕ → OFlat) →+* (ℕ → OFlat) := .pi fun n ↦ evalRingHom _ (n + 1)
  have h_mod_p : Surjective (shiftDiff OFlat (constantCoeff a)) :=
    OFlat.shiftDiff_surjective_of_not_isUnit (mt isUnit_iff_isUnit_constantCoeff.mpr h)
  -- the Witt vector over `ℕ → O^♭` whose `i`-th coordinate is `n ↦ (b n).coeff i`
  let B : WittVector p (ℕ → OFlat) := WittVector.mk p fun i n ↦ (b n).coeff i
  obtain ⟨y, hy⟩ := WittVector.surjective_map_sub_mul_map
    (algebraMap Ainf (WittVector p (ℕ → OFlat)) a) 1 shift h_mod_p B
  -- the components of the solution `y` form the required sequence
  refine ⟨fun n ↦ y.map (evalRingHom _ n), funext fun n ↦ ?_⟩
  -- the `n`-th component of `hy` is the `n`-th equation `y n - a * y (n + 1) = b n`; the two sides
  -- agree only after unfolding `WittVector.map` coordinatewise, hence `using!`
  simpa [B] using! congrArg (WittVector.map (evalRingHom _ n)) hy

/-- `ξ` is a prime element of `A_inf`: it generates the kernel of `θ`, whose target `O_C` is a
domain. -/
lemma Ainf.prime_xi : Prime xi :=
  (span_singleton_prime (show xi ≠ 0 from fun h ↦ not_p_dvd_xi (by simp [h]))).mp
    (ker_theta_eq_span_xi ▸ ker_isPrime theta)

/-- Each `g ∈ G_p` commutes with `φ` and `θ`, so `τ` divides every conjugate `g' • τ` by
`tau_dvd_of_theta_frobEnd`; hence `g • τ` is associated to `τ`. -/
lemma associated_smul_tau : Associated (g • tau) tau := by
  refine associated_smul_of_dvd g fun g' ↦ tau_dvd_of_theta_frobEnd fun j ↦ ?_
  rw [← Commute.iterate_right (smul_frobEnd g'), theta_smul, iterate_succ_apply, frobEnd_tau,
    theta_iterate_frobEnd_mu, smul_zero]

/-- Every `m = (n, g)` in `FrobGal = ℕ × G_p`, acting as φⁿ g, maps `ξ` into the ideal `(p, ξ)`. -/
lemma smul_xi_mem_span : m • xi ∈ span {↑p, xi} := by
  -- For `m = (n, g)`: `ξ` divides `g • ξ` as `θ` commutes with `G_p`, and `m • ξ = φ ^ n (g • ξ)`,
  -- whose constant coefficient is a power of that of `g • ξ`.
  obtain ⟨n, g⟩ := m
  have h_xi_dvd : xi ∣ g • xi := by rw [← theta_eq_zero_iff_xi_dvd, theta_smul, theta_xi, smul_zero]
  have h_act : (n, g) • xi = frobEnd^[n.toAdd] (g • xi) := FrobGal.smul_def n.toAdd g xi
  rw [mem_span_pair_iff, h_act, constantCoeff_iterate_frobEnd]
  exact dvd_pow (map_dvd constantCoeff h_xi_dvd) (pow_ne_zero _ (Fact.out : p.Prime).ne_zero)

/-- If a and c are non-units of A_inf, then A_inf is complete and separated for the adic
topology of the ideal (a, c). -/
lemma Ainf.isAdicComplete_span_pair (ha : ¬IsUnit a) (hc : ¬IsUnit c) :
    IsAdicComplete (span {a, c}) Ainf := by
  -- Limits exist because `shiftDiff` is onto for both generators.
  refine { isPrecomplete_of_shiftDiff_surjective
    (shiftDiff_surjective ha) (shiftDiff_surjective hc) with haus' := fun x hx ↦ ?_ }
  -- Separation: write a nonzero `x` in all powers of `(a, c)` as `p ^ n * y` with `p ∤ y`.
  by_contra hx₀
  obtain ⟨n, y, hy, rfl⟩ : ∃ (n : ℕ) (y : Ainf), y.coeff 0 ≠ 0 ∧ x = ↑p ^ n * y :=
    exists_eq_pow_p_mul x hx₀
  have hy_p : ¬↑p ∣ y := by rwa [p_dvd_iff]
  have hδ : ¬↑p ∣ xi * y := prime_p.not_dvd_mul not_p_dvd_xi hy_p
  -- `0` approximates `x` to every order, so any `δ` with `p ∤ δ` divides `x`; take `δ = ξ * y`
  have h_mem (m : ℕ) : ↑p ^ n * y - xi * y * 0 ∈ span {a, c} ^ m := by simpa [zero] using hx m
  have h_dvd : xi * y ∣ ↑p ^ n * y := dvd_of_forall_exists_sub_mem_span_pow ha hc hδ fun m ↦
    ⟨0, h_mem m⟩
  -- cancelling `y` gives `ξ ∣ p ^ n`, that is `θ (p ^ n) = 0`, which is false
  have h_xi : xi ∣ ↑p ^ n := (mul_dvd_mul_iff_right (right_ne_zero_of_mul hx₀)).mp h_dvd
  have h_theta : theta (↑p ^ n) = 0 := theta_eq_zero_iff_xi_dvd.mpr h_xi
  exact pow_ne_zero n (NeZero.ne (p : OC)) (by simpa using h_theta)

lemma Ainf.isAdicComplete_span_singleton (h : ¬IsUnit a) : IsAdicComplete (span {a}) Ainf := by
  simpa using isAdicComplete_span_pair h h

/-- `A_inf` is complete and separated for the `(p, ξ)`-adic topology. -/
instance : IsAdicComplete (span {↑p, xi}) Ainf :=
  Ainf.isAdicComplete_span_pair prime_p.not_isUnit prime_xi.not_isUnit

end ThetaKernel

end New.Period

end