import Mathlib
import Development.AbelianVarietyTheory.Definitions.Foundations.MatrixMeasurableSpace
open ValuativeRel GlobalTheory.SplitWeil Matrix

namespace GlobalTheory

theorem exists_finite_integer_residues (k : Type) [Field k] [ValuativeRel k] [TopologicalSpace k]
    [IsNonarchimedeanLocalField k] [CharZero k] (n : ℕ) (hn : 0 < n) :
    ∃ (ι : Type) (_ : Finite ι) (x : ι → k), (∀ i, x i ∈ 𝒪[k]) ∧
      ∀ y ∈ 𝒪[k], ∃ i, ∃ u ∈ 𝒪[k], y = x i + (n : k) * u := by
  let U : Set k := ((𝒪[k] : Subring k) : Set k)
  have hUo : IsOpen U := Valuation.isOpen_integer
  have hUc : IsCompact U := isCompact_iff_compactSpace.mpr (inferInstance : CompactSpace 𝒪[k])
  have hc : (n : k) ≠ 0 := by exact_mod_cast hn.ne'
  let V : U → Set k := fun x => (fun y => (y - (x : k)) * (n : k)⁻¹) ⁻¹' U
  have hVo : ∀ x, IsOpen (V x) := fun x =>
    hUo.preimage ((continuous_id.sub continuous_const).mul continuous_const)
  have hcov : U ⊆ ⋃ x, V x := by
    intro y hy
    refine Set.mem_iUnion.2 ⟨⟨y, hy⟩, ?_⟩
    show (y - y) * (n : k)⁻¹ ∈ U
    rw [sub_self, zero_mul]
    exact (𝒪[k]).zero_mem
  obtain ⟨t, ht⟩ := hUc.elim_finite_subcover V hVo hcov
  refine ⟨t, inferInstance, fun i => ((i : U) : k), fun i => (i : U).2, ?_⟩
  intro y hy
  have := ht hy
  simp only [Set.mem_iUnion] at this
  obtain ⟨x, hxt, hyx⟩ := this
  refine ⟨⟨x, hxt⟩, (y - (x : k)) * (n : k)⁻¹, hyx, ?_⟩
  field_simp
  ring

theorem matrix_integers_mod_nat_finite : ∀ (k : Type) [Field k] [ValuativeRel k] [TopologicalSpace k]
    [IsNonarchimedeanLocalField k] [CharZero k] (Y Y' : Type) [Fintype Y] [Fintype Y'] (n : ℕ), 0 < n →
    ∃ R : Set (Matrix Y Y' k), R.Finite ∧ ∀ t : Matrix Y Y' k, (∀ r q, t r q ∈ 𝒪[k]) →
      ∃ s ∈ R, ∃ u : Matrix Y Y' k, (∀ r q, u r q ∈ 𝒪[k]) ∧ t = s + n • u := by
  intro k _ _ _ _ _ Y Y' _ _ n hn
  obtain ⟨ι, hι, x, -, hx⟩ := exists_finite_integer_residues k n hn
  refine ⟨Set.range (fun f : Y → Y' → ι => Matrix.of fun r q => x (f r q)), Set.finite_range _, ?_⟩
  intro t ht
  have key := fun r q => hx (t r q) (ht r q)
  choose f u hu hf using key
  refine ⟨Matrix.of fun r q => x (f r q), ⟨f, rfl⟩, Matrix.of fun r q => u r q, hu, ?_⟩
  ext r q
  simp only [Matrix.add_apply, Matrix.smul_apply, Matrix.of_apply, nsmul_eq_mul]
  exact hf r q

end GlobalTheory
