import Mathlib
import CompanionTheory.SpectralGeometry.LocalGlobalProofs.AdelicAnalysis.GaussQ

noncomputable section

namespace GlobalTheory.CompanionTheory.SW.BB

open HeckeCharacterZeroLocus.SiegelWeilU GlobalTheory.CompanionTheory.SW GlobalTheory.CompanionTheory.SW.BB NumberField IsDedekindDomain MeasureTheory Topology
open scoped TensorProduct ENNReal NNReal Matrix

theorem isometry_map_ringHom {ι R S K : Type} [Fintype ι] [CommRing R] [CommRing S] [CommRing K]
    (φ : R →+* S) (α : K →+* R) (ψ : K →+* S) (hφ : ∀ x, φ (α x) = ψ x)
    (A : Matrix ι ι R) (B : Matrix ι ι K)
    (h : Aᵀ * B.map α * A = B.map α) :
    (A.map φ)ᵀ * B.map ψ * A.map φ = B.map ψ := by
  have hB : B.map ψ = (B.map α).map φ := by
    ext i j
    simp [hφ]
  have := congrArg (fun X => X.map φ) h
  simp only [Matrix.map_mul] at this
  rw [hB, ← Matrix.transpose_map]
  simpa using this

theorem ginf_gfin_isometry (F E : Type) [Field F] [NumberField F] [Field E] [Algebra F E]
    (σ : E →ₐ[F] E) (M : ℕ) (J : Matrix (Fin M) (Fin M) E) (d : ℕ)
    (b : Module.Basis (Fin d) F E) (B : Matrix (Fin M × Fin d) (Fin M × Fin d) F)
    (ρ : InfinitePlace F → (F →+* ℝ)) (e : Ainf F ≃+* (InfinitePlace F → ℝ))
    (he : ∀ x w, e (algebraMap F (Ainf F) x) w = ρ w x)
    (hB : ∀ h : HA (AF F) σ J, (gmat (AF F) σ J b h)ᵀ * B.map (algebraMap F (AF F)) *
      gmat (AF F) σ J b h = B.map (algebraMap F (AF F))) :
    (∀ ω w, (ginf e σ J b ω w)ᵀ * B.map (ρ w) * ginf e σ J b ω w = B.map (ρ w)) ∧
      ∀ ω, (gfin σ J b ω)ᵀ * B.map (algebraMap F (Af F)) * gfin σ J b ω =
        B.map (algebraMap F (Af F)) := by
  refine ⟨fun ω w => ?_, fun ω => ?_⟩
  · exact isometry_map_ringHom
      ((Pi.evalRingHom (fun _ : InfinitePlace F => ℝ) w).comp
        ((e : Ainf F →+* (InfinitePlace F → ℝ)).comp (fstA F : AF F →+* Ainf F)))
      (algebraMap F (AF F)) (ρ w)
      (fun x => by
        have h1 : fstA F (algebraMap F (AF F) x) = algebraMap F (Ainf F) x :=
          (fstA F).commutes x
        simpa [h1] using he x w)
      (gmat (AF F) σ J b ω⁻¹) B (hB ω⁻¹)
  · exact isometry_map_ringHom (sndA F : AF F →+* Af F)
      (algebraMap F (AF F)) (algebraMap F (Af F))
      (fun x => (sndA F).commutes x)
      (gmat (AF F) σ J b ω⁻¹) B (hB ω⁻¹)

end GlobalTheory.CompanionTheory.SW.BB
