import Mathlib
import Development.AbelianVarietyTheory.Definitions.Divisors.EqZeroOfForallPowDvd
import Development.AbelianVarietyTheory.Proofs.DivisorProofs.InvDer
import Development.AbelianVarietyTheory.Proofs.DivisorProofs.DividedInOfQuasiLogarithm
open MvPowerSeries GlobalTheory GlobalTheory.Katz GlobalTheory.QLog GlobalTheory.PDivGroup GlobalTheory.Sandwich GlobalTheory.IndefiniteRowSideFullHecke.EpsilonPairingZeta GlobalTheory.PDivLat GlobalTheory.LawDer

set_option autoImplicit false

namespace GlobalTheory.QLogInt

theorem coeff_integral_of_QL : ∀ (p : ℕ) [Fact p.Prime] (B O Q : Type) [CommRing B] [CommRing Q] [CommRing O] [Algebra B Q] (θ : B →+* O), IsFrame p Q θ → ∀ (d : ℕ) (μ : Fin d → MvPowerSeries (Fin d ⊕ Fin d) B), IsLift θ μ → ∀ l : MvPowerSeries (Fin d) Q, QL μ ⊤ l → ∀ α : Fin d →₀ ℕ, α.degree ≤ p → (∀ i, α ≠ Finsupp.single i p) → ∃ b : B, coeff α l = algebraMap B Q b := by
  intro p hpf B O Q _ _ _ _ θ hF d μ hμ l hl α hdeg hne
  have hp : p.Prime := hpf.out
  classical
  by_cases h0 : α = 0
  · refine ⟨0, ?_⟩
    rw [h0, coeff_zero_eq_constantCoeff_apply, hl.1, map_zero]
  obtain ⟨k, hk⟩ : ∃ k, α k ≠ 0 := by
    by_contra h
    push_neg at h
    exact h0 (Finsupp.ext h)
  have hkle : α k ≤ p := (Finsupp.le_degree k α).trans hdeg
  have hklt : α k < p := by
    refine lt_of_le_of_ne hkle fun hkp => hne k ?_
    have hs : Finsupp.single k p ≤ α := by
      rw [Finsupp.single_le_iff]; omega
    have hsplit : α = Finsupp.single k p + (α - Finsupp.single k p) := (add_tsub_cancel_of_le hs).symm
    have hd : (α - Finsupp.single k p).degree = 0 := by
      have h2 := congrArg Finsupp.degree hsplit
      rw [map_add, Finsupp.degree_single] at h2
      omega
    rw [(Finsupp.degree_eq_zero_iff _).1 hd, add_zero] at hsplit
    exact hsplit
  have hcop : Nat.Coprime (α k) p :=
    (Nat.Coprime.symm ((Nat.Prime.coprime_iff_not_dvd hp).2 (Nat.not_dvd_of_pos_of_lt (Nat.pos_of_ne_zero hk) hklt)))
  obtain ⟨u, hu⟩ := hF.unit_coprime (α k) hcop
  obtain ⟨b', -, hb'⟩ := GlobalTheory.QLogDiff.dIn_of_QL p B O Q θ hF d μ hμ ⊤ l hl α k
  refine ⟨(↑u⁻¹ : B) * b', ?_⟩
  have h1 : algebraMap B Q (↑u⁻¹ : B) * (α k : Q) = 1 := by
    rw [← map_natCast (algebraMap B Q) (α k), ← hu, ← map_mul, Units.inv_mul, map_one]
  rw [map_mul, ← hb']
  linear_combination (-(coeff α l)) * h1

end GlobalTheory.QLogInt
