import Development.AbelianVarietyTheory.Definitions.Divisors.ZetaActRefl
import Development.AbelianVarietyTheory.Definitions.Divisors.IsTrSelf
import Formalism.LocalToGlobal.TorsionIntegrality.EisensteinTranslationProducts.TranslateProduct
import ReciprocityTheory.ReductiveGroups.UnramifiedIntegrals.ModDefs
open scoped UpperHalfPlane MatrixGroups Matrix ModularForm ComplexConjugate
open NumberField GlobalTheory.QFam GlobalTheory.WpFam GlobalTheory.LatVal ReciprocityTheory.ChartRestriction.L1 Formalism.L2.Th1.F
open GlobalTheory.CMVal GlobalTheory.HeckeGal
open ModularForm (E₄ E₆)

namespace GlobalTheory.RelLin

theorem main : ∀ (N : ℕ) [NeZero N] (R : (Fin 2 → ZMod N) → (Fin 2 → ZMod N) → Prop),
    (∀ x, ∃ y, R x y) → (∀ x y x' y', R x y → R x' y' → R (x - x') (y - y')) →
    (∀ x y, R x y → (x = 0 ↔ y = 0)) → ∃ A : GL (Fin 2) (ZMod N), ∀ x, R x (vmul x A) := by
  intro N _ R h1 h2 h3
  choose f hf using h1
  have huniq : ∀ x y y', R x y → R x y' → y = y' := by
    intro x y y' hy hy'
    have h := h3 _ _ (h2 x y x y' hy hy')
    exact sub_eq_zero.mp (h.mp (sub_self x))
  have hsub : ∀ x x', f (x - x') = f x - f x' :=
    fun x x' => huniq _ _ _ (hf (x - x')) (h2 _ _ _ _ (hf x) (hf x'))
  let g : (Fin 2 → ZMod N) →+ (Fin 2 → ZMod N) := AddMonoidHom.ofMapSub f hsub
  let L : (Fin 2 → ZMod N) →ₗ[ZMod N] (Fin 2 → ZMod N) := g.toZModLinearMap N
  have hL : ∀ x, L x = f x := fun x => rfl
  have hinj : Function.Injective f := by
    intro x x' hxx
    have : f (x - x') = 0 := by rw [hsub, hxx, sub_self]
    exact sub_eq_zero.mp ((h3 _ _ (hf (x - x'))).mpr this)
  let M : Matrix (Fin 2) (Fin 2) (ZMod N) := LinearMap.toMatrixRight' L
  have hM : ∀ x, x ᵥ* M = f x := by
    intro x
    rw [← hL, ← Matrix.toLinearMapRight'_apply]
    simp [M]
  have hU : IsUnit M := by
    rw [← Matrix.vecMul_surjective_iff_isUnit]
    have hsurj : Function.Surjective f := Finite.injective_iff_surjective.mp hinj
    intro y
    obtain ⟨x, rfl⟩ := hsurj y
    exact ⟨x, hM x⟩
  refine ⟨hU.unit, fun x => ?_⟩
  have : vmul x hU.unit = f x := by
    simp [vmul, hM]
  rw [this]
  exact hf x

end GlobalTheory.RelLin
