import Mathlib
import Development.AbelianVarietyTheory.Proofs.DivisorProofs.ParP
import Formalism.PeriodIntegrals.UnitaryGroupMassFormula.AdelicLocalCompactness.AdeleLC
open NumberField IsDedekindDomain Matrix Polynomial Filter GlobalTheory.CuspRep GlobalTheory.PRep Formalism.UG Formalism.BasicNotions GlobalTheory.UnitaryBC Formalism.L2.Host GlobalTheory.BCT
open scoped Classical TensorProduct
attribute [local instance] GlobalTheory.LocalData.complRel GlobalTheory.LocalData.isLocalField

namespace GlobalTheory.IntMatOpen

open IsDedekindDomain.HeightOneSpectrum

def intLat (E : Type) [Field E] [NumberField E] (w : Pl E) (a b : ℕ) :
    AddSubgroup (Matrix (Fin a) (Fin b) (w.adicCompletion E)) where
  carrier := {X | ∀ i j, Valued.v (X i j) ≤ 1}
  add_mem' {X Y} hX hY i j := (Valued.v.map_add (X i j) (Y i j)).trans (max_le (hX i j) (hY i j))
  zero_mem' i j := by simp
  neg_mem' {X} hX i j := by simpa using hX i j

theorem coe_intLat (E : Type) [Field E] [NumberField E] (w : Pl E) (a b : ℕ) :
    (intLat E w a b : Set (Matrix (Fin a) (Fin b) (w.adicCompletion E))) =
      Set.pi Set.univ fun _ : Fin a => Set.pi Set.univ fun _ : Fin b =>
        (w.adicCompletionIntegers E : Set (w.adicCompletion E)) := by
  ext X
  constructor
  · intro h i _ j _
    exact h i j
  · intro h i j
    exact h i trivial j trivial

theorem intMat_open_compact : ∀ (E : Type) [Field E] [NumberField E] (w : Pl E) (a b : ℕ), ∃ Λ : AddSubgroup (Matrix (Fin a) (Fin b) (w.adicCompletion E)), IsOpen (Λ : Set (Matrix (Fin a) (Fin b) (w.adicCompletion E))) ∧ IsCompact (Λ : Set (Matrix (Fin a) (Fin b) (w.adicCompletion E))) ∧ intMat a b w = AddSubgroup.toSubgroup Λ := by
  intro E _ _ w a b
  refine ⟨intLat E w a b, ?_, ?_, ?_⟩
  · rw [coe_intLat]
    exact isOpen_set_pi Set.finite_univ fun i _ => isOpen_set_pi Set.finite_univ fun j _ =>
      Valued.isOpen_valuationSubring _
  · rw [coe_intLat]
    exact isCompact_univ_pi fun i => isCompact_univ_pi fun j =>
      PI.AdicCompletionValuation.isCompact_adicCompletionIntegers E w
  · have hS : {X : Multiplicative (Matrix (Fin a) (Fin b) (w.adicCompletion E)) |
        ∀ i j, Valued.v (Multiplicative.toAdd X i j) ≤ 1} =
        ((AddSubgroup.toSubgroup (intLat E w a b) : Subgroup _) : Set _) := by
      ext X; rfl
    unfold intMat
    rw [hS, Subgroup.closure_eq]

end GlobalTheory.IntMatOpen
