import Mathlib
import Development.AbelianVarietyTheory.Definitions.Divisors.HermSysHypOneLeLambdaZero
import Development.AbelianVarietyTheory.Definitions.Divisors.AevalEqZeroOfMemConeIdeal
import ReciprocityTheory.SemistableReduction.TorusL2CauchyInequality
import Development.AbelianVarietyTheory.Proofs.DivisorProofs.LeOfRingKrullDimConeIdeal
import Development.AbelianVarietyTheory.Proofs.DivisorProofs.ExistsHomogeneousFormsQuotientBirationalSystemStatement
open NumberField MvPolynomial ReciprocityTheory.MultiplicativeHeights CategoryTheory AlgebraicGeometry
open ReciprocityTheory.ChartRestriction.G ReciprocityTheory.ChartRestriction.G.Semi ReciprocityTheory.ChartRestriction.G.Geo.Tor
open ReciprocityTheory.ChartRestriction.G.Out (nonzeroLocus)
open GlobalTheory GlobalTheory.ChowHt GlobalTheory.Adelic GlobalTheory.HSCore GlobalTheory.HSChoice GlobalTheory.HSShort

set_option autoImplicit false
noncomputable section
namespace GlobalTheory.BirFiniteFibre

open GlobalTheory.Points

theorem aeval_smul_of_isHomogeneous {F K σ : Type} [CommRing F] [CommRing K] [Algebra F K] {d : ℕ}
    {p : MvPolynomial σ F} (hp : p.IsHomogeneous d) (c : K) (y : σ → K) :
    aeval (c • y) p = c ^ d * aeval y p := by
  rw [aeval_def, aeval_def, eval₂_eq, eval₂_eq, Finset.mul_sum]
  refine Finset.sum_congr rfl fun a ha => ?_
  have : a.degree = d := by rw [Finsupp.degree_eq_weight_one]; exact hp (mem_support_iff.1 ha)
  simp only [Pi.smul_apply, smul_eq_mul, mul_pow, Finset.prod_mul_distrib, Finset.prod_pow_eq_pow_sum]
  rw [← this, Finsupp.degree_apply, mul_left_comm]

theorem compactSpace_Y {F : Type} [Field F] (S : LinSys F) (h : S.IsVariety) : CompactSpace S.Y := by
  obtain ⟨n, i, hi, e⟩ := h.proj
  have := isProper_str F n
  have : IsProper S.str := e ▸ inferInstance
  exact ⟨by simpa using QuasiCompact.isCompact_preimage (f := S.str) Set.univ isOpen_univ isCompact_univ⟩

theorem exists_finset_separating {F : Type} [Field F] (S : LinSys F) (h : S.IsVariety) (W : S.Y.Opens)
    (hW : IsAffineOpen W) : ∃ s : Finset Γ(S.Y, W), ∀ (K : Type) [Field K] [Algebra F K] (x x' : S.Pt K),
      ptOf x.1 ∈ W → ptOf x'.1 ∈ W → (∀ a ∈ s, valR x.1 W a = valR x'.1 W a) → x = x' := by
  obtain ⟨n, i, hi, e⟩ := h.proj
  have := isProper_str F n
  have : IsProper S.str := e ▸ inferInstance
  have hle : W ≤ S.str ⁻¹ᵁ ⊤ := le_top
  have hft : (S.str.appLE ⊤ W hle).hom.FiniteType :=
    HasRingHomProperty.appLE (P := @LocallyOfFiniteType) S.str inferInstance ⟨⊤, isAffineOpen_top _⟩ ⟨W, hW⟩ hle
  letI := (S.str.appLE ⊤ W hle).hom.toAlgebra
  obtain ⟨s, hs⟩ : Algebra.FiniteType Γ(Sp F, ⊤) Γ(S.Y, W) := hft
  refine ⟨s, fun K _ _ x x' hx hx' H => Subtype.ext ?_⟩
  have h1 := (le_iff_ptOf_mem _ _).2 hx
  have h2 := (le_iff_ptOf_mem _ _).2 hx'
  refine ext_of_valR hW h1 h2 fun f => ?_
  have hf : f ∈ Algebra.adjoin Γ(Sp F, ⊤) (s : Set Γ(S.Y, W)) := hs ▸ Algebra.mem_top
  induction hf using Algebra.adjoin_induction with
  | mem a ha => exact H a ha
  | algebraMap r =>
    exact (valR_appLE x.1 S.str hle h1 r).trans
      ((congrArg (fun q => valR q ⊤ r) (x.2.trans x'.2.symm)).trans (valR_appLE x'.1 S.str hle h2 r).symm)
  | add a b _ _ ha hb => rw [valR_add _ _ h1, valR_add _ _ h2, ha, hb]
  | mul a b _ _ ha hb => rw [valR_mul _ _ h1, valR_mul _ _ h2, ha, hb]

theorem exists_form_finite_fibres : ∀ (F : Type) [Field F] (S : LinSys F), S.IsVariety → S.BasePointFree → S.Birational → ∃ (d : ℕ) (g : MvPolynomial (Fin S.N) F), g.IsHomogeneous d ∧ g ∉ S.imageIdeal ∧ ∀ (K : Type) [Field K] [Algebra F K] (y : Fin S.N → K), {x : S.Pt K | aeval (S.coords x.1) g ≠ 0 ∧ ∃ c : K, S.coords x.1 = c • y}.Finite := by
  intro F _ S hV hb hB
  classical
  haveI := compactSpace_Y S hV
  haveI := HeightExists.isPrime_imageIdeal hV
  have hcov : ∀ y : S.Y, ∃ W : S.Y.Opens, IsAffineOpen W ∧ y ∈ W := fun y => by
    obtain ⟨W, hW, hy, -⟩ := exists_isAffineOpen_mem_and_subset (U := ⊤) (x := y) trivial
    exact ⟨W, hW, hy⟩
  choose W hW hy using hcov
  obtain ⟨t, ht⟩ := isCompact_univ.elim_finite_subcover (fun y => (W y : Set S.Y)) (fun y => (W y).isOpen)
    (fun y _ => Set.mem_iUnion.2 ⟨y, hy y⟩)
  choose s hs using fun z => exists_finset_separating S hV (W z) (hW z)
  choose d P Q hP hQ hQI _ hval using fun z a => GlobalTheory.T.exists_homogeneous_forms_quotient_birational_system F S hV hb hB (W z) a
  refine ⟨∑ z ∈ t, ∑ a ∈ s z, d z a, ∏ z ∈ t, ∏ a ∈ s z, Q z a, ?_, ?_, fun K _ _ y => ?_⟩
  · exact IsHomogeneous.prod _ _ _ fun z _ => IsHomogeneous.prod _ _ _ fun a _ => hQ z a
  · rw [Ideal.IsPrime.prod_mem_iff]
    rintro ⟨z, -, hz⟩
    rw [Ideal.IsPrime.prod_mem_iff] at hz
    obtain ⟨a, -, ha⟩ := hz
    exact hQI z a ha
  · have key : ∀ z ∈ t, ∀ a ∈ s z, ∀ x : S.Pt K, ptOf x.1 ∈ W z →
        aeval (S.coords x.1) (∏ z ∈ t, ∏ a ∈ s z, Q z a) ≠ 0 → (∃ c : K, S.coords x.1 = c • y) →
        valR x.1 (W z) a = aeval y (P z a) / aeval y (Q z a) := by
      rintro z hz a ha x hx hg ⟨c, hc⟩
      have h1 : aeval (S.coords x.1) (Q z a) ≠ 0 := by
        rw [map_prod, Finset.prod_ne_zero_iff] at hg
        have := hg z hz
        rw [map_prod, Finset.prod_ne_zero_iff] at this
        exact this a ha
      have h2 := hval z a K x hx
      have hc0 : c ≠ 0 := by
        rintro rfl
        exact hb.coords_ne_zero x.1 (hc.trans (zero_smul _ _))
      rw [hc, aeval_smul_of_isHomogeneous (hQ z a)] at h1 h2
      rw [aeval_smul_of_isHomogeneous (hP z a), mul_left_comm] at h2
      rw [eq_div_iff (right_ne_zero_of_mul h1)]
      exact mul_left_cancel₀ (pow_ne_zero _ hc0) h2
    refine (t.finite_toSet.biUnion (t := fun z => {x : S.Pt K | ptOf x.1 ∈ W z ∧
      aeval (S.coords x.1) (∏ z ∈ t, ∏ a ∈ s z, Q z a) ≠ 0 ∧ ∃ c : K, S.coords x.1 = c • y})
      fun z hz => Set.Subsingleton.finite fun x hx x' hx' => ?_).subset fun x hx => ?_
    · exact hs z K x x' hx.1 hx'.1 fun a ha =>
        (key z hz a ha x hx.1 hx.2.1 hx.2.2).trans (key z hz a ha x' hx'.1 hx'.2.1 hx'.2.2).symm
    · obtain ⟨z, hz, hxz⟩ := Set.mem_iUnion₂.1 (ht (Set.mem_univ (ptOf x.1)))
      exact Set.mem_iUnion₂.2 ⟨z, hz, hxz, hx⟩

end GlobalTheory.BirFiniteFibre
