import Mathlib
import Development.AbelianVarietyTheory.PublishedTheorems.AutomorphicForms₂.SiegelToroidalIntegral
import Development.AbelianVarietyTheory.PublishedTheorems.Divisors₂.ToroidalCompactificationBis
import Development.AbelianVarietyTheory.PublishedTheorems.Divisors₂.InterNumDetNonposSplitTorus
import Development.AbelianVarietyTheory.PublishedTheorems.Divisors₂.GrothendieckDeformation
import Development.AbelianVarietyTheory.Definitions.Divisors.NormNegCmConstantEqAtAllEmbeddings
import Formalism.LocalRingCardinality.DataParamsT
import Development.AbelianVarietyTheory.Definitions.Divisors.ToKnownTheoremsOf
import Development.AbelianVarietyTheory.Definitions.Divisors.CuspIso
import Development.AbelianVarietyTheory.Definitions.Divisors.WellChosen
import Development.AbelianVarietyTheory.Definitions.Divisors.MeanLogLeOfBounds
import Development.AbelianVarietyTheory.Definitions.Divisors.WedgeNrmLeOfWedgeNormLe
import Development.AbelianVarietyTheory.Definitions.Divisors.IsHomWeightHomWeight
import Development.AbelianVarietyTheory.Definitions.Divisors.MemLevEigenIffTransl
import Formalism.LocalToGlobal.IndefiniteForms.IndefiniteTree.RealCubicMeans.LogMeanShares.LogMeanStatements.HSClaim
import Development.AbelianVarietyTheory.Definitions.Divisors.GenRatios
import Development.AbelianVarietyTheory.Definitions.Divisors.BadElt
import Development.AbelianVarietyTheory.Proofs.DivisorProofs.CardLeOfDetEqZero
import Development.AbelianVarietyTheory.Proofs.GenericRegularity.NumericalConsequencesOfPins
import Development.AbelianVarietyTheory.Proofs.DivisorProofs.AntitoneWeightLogBoundStatement
import Development.AbelianVarietyTheory.Proofs.DivisorProofs.FlatConstantAbsLeNineExplicitStatement
import Development.AbelianVarietyTheory.Proofs.DivisorProofs.KeepsCuspLatticeNorm
import Development.AbelianVarietyTheory.Proofs.DivisorProofs.OrbitSeparationRegularDeterminantStatement
import Development.AbelianVarietyTheory.Proofs.DivisorProofs.GoodWeightAntitoneGapStatement

open CategoryTheory AlgebraicGeometry NumberField
open ReciprocityTheory.ChartRestriction.G ReciprocityTheory.ChartRestriction.G.Geo.Tor Formalism.L2.Pj Formalism.BasicNotions Formalism.MainNotions Formalism.L2.Theta
open GlobalTheory GlobalTheory.CompHS GlobalTheory.CovTop GlobalTheory.HSApp GlobalTheory.DegVal GlobalTheory.DegCmp
open GlobalTheory.AllWt (Psi wtOf cuspOn cuspW latOn latW normOn petOn GoodOn GoodW rankOn degOn rankW)
open GlobalTheory.CompHt (hodgeWt)
open GlobalTheory.LevDesc (TypeFrame grpHR grpGHR latN levDet secRing transl pull KeepsCusp)
open GlobalTheory.IndefiniteRowSideFullHecke.LevelStructureAutomorphisms (LevelAut)
open GlobalTheory.BadCount
open scoped TensorProduct

namespace GlobalTheory.ShortDet

theorem le_choose {f r p q : ℕ} (hf : 8 ≤ f) (hr : 100 ≤ r) (hp : 1 ≤ p) (hq : 1 ≤ q) (h : p + q = r) :
    8 * f * r + 10 ≤ (f * p * q + 1).choose 2 := by
  have h1 : r ≤ p * q + 1 := by
    obtain ⟨a, rfl⟩ := Nat.exists_eq_add_of_le hp
    obtain ⟨b, rfl⟩ := Nat.exists_eq_add_of_le hq
    nlinarith [Nat.zero_le (a * b)]
  rw [Nat.choose_two_right, Nat.add_sub_cancel, mul_assoc f, mul_assoc 8, Nat.le_div_iff_mul_le two_pos]
  generalize p * q = s at h1
  have h2 : f * r ≤ 2 * (f * s) := by
    rw [mul_left_comm]; exact Nat.mul_le_mul_left _ (by omega)
  have h3 : 8 * 99 ≤ f * s := Nat.mul_le_mul hf (by omega)
  generalize f * s = N at h2 h3
  nlinarith

section Weight

variable {E : Type} [Field E] [NumberField E] [IsCMField E] {H : ReciprocityTheory.ChartRestriction.G.Geo.Tor.Host E} (Dw : Datum H)

theorem antitone_smul_hodgeWt {s : ℤ} (hs : 0 ≤ s) (τ : Psi H) : Antitone ((s • hodgeWt Dw) τ) := fun i j h => by
  have : (i : ℕ) ≤ j := h
  simp only [hodgeWt, CompHt.barWt, Pi.smul_apply, smul_eq_mul]
  split_ifs <;> omega

theorem gap_smul_hodgeWt (hp : 1 ≤ Dw.p) (hq : 1 ≤ Dw.q) (s : ℤ) (τ : Psi H) : gap ((s • hodgeWt Dw) τ) (Dw.p - 1) = s := by
  have h : Dw.p - 1 + 1 < Dw.p + Dw.q := by omega
  simp only [gap, dif_pos h, hodgeWt, CompHt.barWt, Pi.smul_apply, smul_eq_mul]
  split_ifs <;> omega

theorem size_smul_hodgeWt {s : ℤ} (hs : 0 ≤ s) :
    ∑ τ, ∑ k, |((s • hodgeWt Dw) τ k : ℝ)| ≤ Module.finrank ℚ E * ((Dw.p + Dw.q : ℕ) * s) := by
  have h0 : (0 : ℝ) ≤ s := by exact_mod_cast hs
  refine (Finset.sum_le_card_nsmul _ _ (((Dw.p + Dw.q : ℕ) : ℝ) * s) fun τ _ => ?_).trans ?_
  · refine (Finset.sum_le_card_nsmul _ _ (s : ℝ) fun k _ => ?_).trans (by simp)
    simp only [hodgeWt, CompHt.barWt, Pi.smul_apply, smul_eq_mul]
    split_ifs <;> simp [h0, abs_of_nonneg h0]
  · rw [nsmul_eq_mul, ← NumberField.Embeddings.card E ℂ]
    exact mul_le_mul_of_nonneg_right (by exact_mod_cast Fintype.card_subtype_le _) (by positivity)

end Weight

set_option maxHeartbeats 1600000 in

theorem exists_integral_short : Hypotheses2 → GlobalTheory.Published.GrothendieckDeformation → GlobalTheory.HSCore.Quoted → GlobalTheory.Published.SiegelToroidalIntegral → GlobalTheory.Published.ToroidalForFanKS → GlobalTheory.Published.SemiAbelianLieSeminegative → ∃ C : ℝ, 0 ≤ C ∧ ∀ (D : D7) (T : CoreJ D), LawsJ T → ∀ j : ℕ, 1 ≤ (T.Q.Dw j).p → 1 ≤ (T.Q.Dw j).q → 2 < Module.finrank ℚ D.host.E / 2 → InR D j → ∀ (Y : Deep T.toCore j) (e : ℕ) (o : ℝ), Y.Good e o → ∀ Lb : ℝ, 1 ≤ Lb → Real.log Y.d.l₂.M ≤ 30 * Lb → fieldSz D.host.E ≤ 3 * Lb → Real.log (D.R.f * D.R.r) ≤ Lb → o ≤ 391 * (D.R.f * D.R.r * Lb) ^ 2 → ∀ c₁ : ℝ, GlobalTheory.FlatLine.FlatExistsAt Y.U (xiR D) c₁ → |c₁| ≤ 9 * D.R.r * Lb → 4 ≤ e → (∀ k, D.R.r + 1 < D.host.g k) → 8 ≤ D.R.f → 100 ≤ D.R.r → ∀ (fr : TypeFrame (T.Q.Dw j) Y.d.l₂), ∃ u : Y.V (wtOf (T.Q.Dw j) (cZero D j • hodgeWt (T.Q.Dw j)) 0), u ∈ AllWt.latW Y.U _ ∧ (∀ f ∈ secRing Y.d.Xo₂ Y.d.c₂, levDet Y.d.Xo₂ Y.d.c₂ (grpHR fr) u * f = 0 → f = 0) ∧ ∀ (γ : (LevelAut (T.Q.Dw j) Y.d.l₂)) (G : WTZ D.host.E) (f : Y.V G) (g : Y.V (G + (wtOf (T.Q.Dw j) (cZero D j • hodgeWt (T.Q.Dw j)) 0))), Even G.2 → (g : Rul Y.d.Xo₂ Y.d.c₂) = f * pull Y.d.Xo₂ Y.d.c₂ γ u → ∀ σ, Y.nrm _ σ g ≤ Real.exp (C * ((D.R.f : ℝ) * D.R.r * Lb) ^ 9) * Y.nrm G σ f := by
  intro hP hGr hQ hS hK hN
  obtain ⟨C₁, hC₁, hb⟩ := GlobalTheory.T.antitone_weight_log_bound hP
  obtain ⟨C₃, hC₃, h3⟩ := GlobalTheory.T.flat_constant_abs_le_nine_explicit hP
  refine ⟨C₃ + 240 + C₁ + 2 * C₃, by positivity, ?_⟩
  intro D T hT j hp hq hE hj Y e o hG Lb hL hM hF hfr ho c₁ hc hc' he hg hf hr fr
  obtain ⟨-, -, -, -, -, hdeg, hJ⟩ := GlobalTheory.PinNum.numerics_of_pins D T.Q hT.pins
  obtain ⟨hpq, -, -⟩ := hJ j hj
  obtain ⟨hp', hq', -⟩ := hT.pins.2.2.2 j hj
  obtain ⟨-, h0, hcz⟩ := cZero_spec D j
  have hgap : ((8 * D.R.f * D.R.r + 10 : ℕ) : ℤ) ≤ cZero D j := by
    have h1 := (cZeroN_isLeast D j).1.2.1
    have h2 := le_choose hf hr hp hq hpq
    rw [hp', hq'] at h2
    exact Int.ofNat_le.2 (by omega)
  have hanti := antitone_smul_hodgeWt (T.Q.Dw j) h0
  have hgp := gap_smul_hodgeWt (T.Q.Dw j) hp hq (cZero D j)
  have hsz := size_smul_hodgeWt (T.Q.Dw j) h0
  have hcard := card_levelAut_le (T.Q.Dw j) Y.d.l₂
  rw [hdeg, congrArg (Nat.cast : ℕ → ℝ) hpq] at hsz
  rw [hdeg, hpq, Nat.mul_div_cancel_left _ two_pos] at hcard
  have hf' : (8 : ℝ) ≤ D.R.f := by exact_mod_cast hf
  have hr' : (100 : ℝ) ≤ D.R.r := by exact_mod_cast hr
  have hcz' : (cZero D j : ℝ) ≤ 22 * (D.R.f : ℝ) ^ 2 * (D.R.r : ℝ) ^ 4 := by exact_mod_cast hcz
  have hs0 : 0 ≤ ∑ τ, ∑ k, |((cZero D j • hodgeWt (T.Q.Dw j)) τ k : ℝ)| := by positivity
  have hb' := hb D T hT j hp hq hE hj Y e o hG Lb hL hM hF hfr ho _ hanti
  have h3' := h3 D T hT j hp hq hE hj Y e o hG Lb hL hM hF hfr ho c₁ hc hc' _ hanti fun τ => (hgp τ).symm ▸ hgap
  generalize ∑ τ, ∑ k, |((cZero D j • hodgeWt (T.Q.Dw j)) τ k : ℝ)| = s at hs0 hsz hb' h3'
  have ha : (1 : ℝ) ≤ D.R.f * D.R.r := by nlinarith
  have hs : s ≤ ((D.R.f : ℝ) * D.R.r) ^ 5 := by
    refine hsz.trans ?_
    push_cast
    calc _ ≤ 2 * (D.R.f : ℝ) * (D.R.r * (22 * (D.R.f : ℝ) ^ 2 * (D.R.r : ℝ) ^ 4)) := by gcongr
      _ = 44 * ((D.R.f : ℝ) ^ 3 * (D.R.r : ℝ) ^ 5) := by ring
      _ ≤ (D.R.f : ℝ) ^ 2 * ((D.R.f : ℝ) ^ 3 * (D.R.r : ℝ) ^ 5) := by gcongr; nlinarith
      _ = _ := by ring
  have hls : Real.log s ≤ 5 * Lb := by
    rcases hs0.eq_or_lt with rfl | h
    · rw [Real.log_zero]; linarith
    · refine (Real.log_le_log h hs).trans ?_
      rw [Real.log_pow]; push_cast; linarith
  have hcard' : (Nat.card (grpHR fr) : ℝ) ≤ Real.exp (120 * ((D.R.f : ℝ) * D.R.r) ^ 2 * Lb) := by
    have h1 : (Nat.card (grpHR fr) : ℝ) ≤ (Y.d.l₂.M : ℝ) ^ (2 * (D.R.f * D.R.r)) ^ 2 := by
      exact_mod_cast (Subgroup.card_le_card_group _).trans hcard
    refine h1.trans ((pow_le_pow_left₀ (by positivity) ((Real.le_exp_log _).trans (Real.exp_le_exp.2 hM)) _).trans ?_)
    rw [← Real.exp_nat_mul]
    push_cast
    exact le_of_eq (by congr 1; ring)
  have haZ : (D.R.f : ℝ) * D.R.r ≤ D.R.f * D.R.r * Lb := le_mul_of_one_le_right (by positivity) hL
  have hZ2 : ((D.R.f : ℝ) * D.R.r) ^ 2 * Lb ≤ (D.R.f * D.R.r * Lb) ^ 2 := by
    rw [mul_pow _ Lb]; gcongr; nlinarith
  replace hs := hs.trans (pow_le_pow_left₀ (by positivity) haZ 5)
  have hZ := ha.trans haZ
  rw [mul_assoc] at hcard'
  generalize (D.R.f : ℝ) * D.R.r * Lb = Z at hb' h3' hs hZ hZ2 ⊢
  have hw : ∀ k, k ≤ 9 → Z ^ k ≤ Z ^ 9 := fun k hk => pow_le_pow_right₀ hZ hk
  have hA : Y.d.l₂.A.Coprime Y.d.l₂.M := by rw [hG.lev.2]; exact Nat.coprime_one_left _
  have hpos : 1 ≤ (T.Q.Dw j).p + (T.Q.Dw j).q := by omega
  obtain ⟨u₀, h₀, hd₀⟩ := GlobalTheory.T.type_frame_large_genus_bound hP hGr hQ hS hK hN D T hT j hp hq hE hj Y e o hG he hg fr _ (Or.inl rfl)
  obtain ⟨u, hu, hd, hsup⟩ := exists_short (β := Real.exp (C₁ * Z ^ 3)) (Λ := Real.exp (2 * C₃ * Z ^ 9))
    (N := Real.exp (C₃ * Z ^ 3)) hpos hA hG.unf (grpHR fr) _ (Real.one_le_exp (by positivity)) (Real.exp_pos _).le
    (Real.exp_pos _).le (fun W => (hb' (by linarith) W).2.1)
    (fun W => ((GlobalTheory.T.good_weight_antitone_gap hP D T hT j hp hq hE hj Y e o hG _ hanti fun τ => by rw [hgp]; omega).2 W).2.2)
    (fun W => by
      obtain ⟨n, w, abelian₂, a1, a2, a3⟩ := h3' (by linarith) W
      refine ⟨n, w, abelian₂, a1, (Real.le_exp_log _).trans (Real.exp_le_exp.2 (a2.trans ?_)),
        (Real.le_exp_log _).trans (Real.exp_le_exp.2 a3)⟩
      have h1 : Z ^ 3 * s ≤ Z ^ 8 := (mul_le_mul_of_nonneg_left hs (by positivity)).trans_eq (by ring)
      have h2 := hw 8 (by norm_num)
      have h4 := hw 5 (by norm_num)
      rw [mul_comm 2, mul_assoc]
      exact mul_le_mul_of_nonneg_left (by linarith) hC₃) h₀ hd₀
  refine ⟨u, hu, hd, normW_mul_pull_le hpos hA (fun σ hσ => ?_) (fun G hGe => ?_) (AllWt.even_wtOf _ _) (Real.exp_pos _).le
    fun σ z => (hsup σ z).trans ?_⟩
  · obtain ⟨th, hr, -, h⟩ := hG.dictU σ hσ
    exact h.2.2.2.1
  · obtain ⟨k₁, k₂⟩ := GlobalTheory.LevelIsometry.keeps_cusp_lattice_norm D T hT j hp hq hE hj Y e o hG G hGe
    exact ⟨k₁, fun γ f g h => (k₂ γ f g h).2⟩
  · refine (mul_le_mul_of_nonneg_left (mul_le_mul_of_nonneg_right (pow_le_pow_left₀ (by positivity) hcard' 2)
      (by positivity)) (by positivity)).trans ?_
    rw [← Real.exp_nat_mul, ← Real.exp_add, ← Real.exp_add, ← Real.exp_add, Real.exp_le_exp]
    have h1 := mul_le_mul_of_nonneg_left (hw 3 (by norm_num)) hC₁
    have h2 := mul_le_mul_of_nonneg_left (hw 3 (by norm_num)) hC₃
    have h4 := hw 2 (by norm_num)
    push_cast
    linarith

end GlobalTheory.ShortDet
