import Thesis.PadicBernoulliSums

/-!
# Integral moments for divided Bernoulli numbers

Multiplication by a unit permutes the representatives modulo `q = p^r`.
Taking first differences of powers supplies the factor `n` needed in
`B_n/n`, even when `p ∣ n`.
-/

open Finset Filter
open scoped BigOperators Topology

namespace Thesis.FiniteBernoulli

theorem firstOrderPower (x h : ℤ) (m : ℕ) :
    ∃ e : ℤ, (x + h) ^ (m + 1) =
      x ^ (m + 1) + ((m : ℤ) + 1) * x ^ m * h + h ^ 2 * e := by
  induction m with
  | zero => exact ⟨0, by ring⟩
  | succ m ih =>
    obtain ⟨e, he⟩ := ih
    refine ⟨((m : ℤ) + 1) * x ^ m + (x + h) * e, ?_⟩
    rw [pow_succ (x + h) (m + 1), he]
    push_cast
    simp only [pow_succ]
    ring

/-- The first-order contribution when the scaled representative crosses a
    multiple of the modulus. -/
def carryMoment (c q m : ℕ) : ℤ :=
  ∑ a ∈ range q, ((c * a / q : ℕ) : ℤ) * ((c * a % q : ℕ) : ℤ) ^ m

theorem sum_permute {A : Type*} [AddCommMonoid A] (c q : ℕ) (hq : 0 < q)
    (hc : q.Coprime c) (f : ℕ → A) :
    ∑ a ∈ range q, f (c*a % q) = ∑ a ∈ range q, f a := by
  classical
  have hinj : Set.InjOn (fun a => c*a % q) (↑(range q) : Set ℕ) := by
    intro a ha b hb hab
    have h : c*a ≡ c*b [MOD q] := hab
    exact (Nat.ModEq.cancel_left_of_coprime hc h).eq_of_lt_of_lt
      (mem_range.mp ha) (mem_range.mp hb)
  have him : (range q).image (fun a => c*a % q) = range q :=
    Finset.eq_of_subset_of_card_le
      (by intro x hx; obtain ⟨a, _, rfl⟩ := mem_image.mp hx; exact mem_range.mpr (Nat.mod_lt _ hq))
      (by rw [Finset.card_image_of_injOn hinj])
  calc
    _ = ∑ b ∈ (range q).image (fun a => c*a % q), f b := (Finset.sum_image hinj).symm
    _ = _ := by rw [him]

theorem carry_summand (a c q m : ℕ) : ∃ e : ℤ,
    ((c : ℤ)*a) ^ (m+1) - ((c*a%q : ℕ) : ℤ) ^ (m+1) =
    ((m : ℤ)+1)*q*(((c*a/q : ℕ) : ℤ)*((c*a%q : ℕ) : ℤ)^m) + (q : ℤ)^2 * e := by
  let b : ℤ := (c*a%q : ℕ)
  let d : ℤ := (c*a/q : ℕ)
  have h : b + (q : ℤ)*d = (c : ℤ)*a := by
    dsimp [b, d]
    exact_mod_cast Nat.mod_add_div (c*a) q
  obtain ⟨e, he⟩ := firstOrderPower b ((q : ℤ)*d) m
  refine ⟨d^2*e, ?_⟩
  change ((c : ℤ)*a)^(m+1)-b^(m+1) = ((m : ℤ)+1)*q*(d*b^m) + (q : ℤ)^2*(d^2*e)
  rw [← h, he]
  ring

theorem finite_smoothing (c q m : ℕ) (hq : 0 < q) (hc : q.Coprime c) :
    ∃ e : ℤ, ((c : ℤ) ^ (m+1) - 1) * (∑ a ∈ range q, (a : ℤ) ^ (m+1)) =
      ((m : ℤ) + 1) * q * carryMoment c q m + (q : ℤ)^2 * e := by
  classical
  choose e he using fun a => carry_summand a c q m
  refine ⟨∑ a ∈ range q, e a, ?_⟩
  have hs := Finset.sum_congr (show range q = range q from rfl) (fun a _ => he a)
  rw [sum_sub_distrib, sum_permute c q hq hc (fun x => (x : ℤ)^(m+1)), sum_add_distrib, ← Finset.mul_sum,
    ← Finset.mul_sum] at hs
  simpa only [mul_pow, ← Finset.mul_sum, sub_mul, one_mul, carryMoment] using hs

variable {p : ℕ} [Fact p.Prime]

noncomputable def smoothedValue (c m : ℕ) : ℚ_[p] :=
  ((c : ℚ_[p]) ^ (m+1) - 1) * (bernoulli (m+1) : ℚ_[p]) / ((m : ℚ_[p])+1)

theorem carryMoment_tendsto (c m : ℕ) (hc : p.Coprime c) :
    Tendsto (fun r : ℕ => (carryMoment c (p^r) m : ℚ_[p])) atTop
      (𝓝 (smoothedValue (p := p) c m)) := by
  have hp : p.Prime := Fact.out
  have hp0 := hp.ne_zero
  have hq (r : ℕ) : 0 < p ^ r := pow_pos hp.pos r
  choose e he using fun r => finite_smoothing c (p^r) m (hq r) (hc.pow_left r)
  have hkernel (r : ℕ) :
      (((c : ℚ_[p]) ^ (m+1)-1) * PadicBernoulli.normPowSum (p := p) r (m+1)) /
        ((m : ℚ_[p])+1) - ((p : ℚ_[p]) ^ r * (e r : ℚ_[p])) / ((m : ℚ_[p])+1) =
        (carryMoment c (p^r) m : ℚ_[p]) := by
    have h := congrArg (Int.cast : ℤ → ℚ_[p]) (he r)
    push_cast at h
    have hpn : (p : ℚ_[p]) ^ r ≠ 0 := pow_ne_zero _ (Nat.cast_ne_zero.mpr hp0)
    have hm : (m : ℚ_[p])+1 ≠ 0 := by exact_mod_cast Nat.succ_ne_zero m
    unfold PadicBernoulli.normPowSum PadicBernoulli.powSum
    field_simp [hpn, hm]
    linear_combination h
  have hsmall : Tendsto (fun r : ℕ => (p : ℚ_[p]) ^ r * (e r : ℚ_[p])) atTop (𝓝 0) := by
    apply tendsto_zero_iff_norm_tendsto_zero.mpr
    have ht : Tendsto (fun r : ℕ => ‖(p : ℚ_[p])^r‖) atTop (𝓝 0) :=
      by simpa using (PadicBernoulli.tendsto_p_pow (p := p)).norm
    apply squeeze_zero (fun r => norm_nonneg _) (fun r => ?_) ht
    rw [norm_mul]
    exact mul_le_of_le_one_right (norm_nonneg ((p : ℚ_[p])^r)) (Padic.norm_int_le_one (p := p) (e r))
  have ht := (((tendsto_const_nhds (x := (c : ℚ_[p])^(m+1)-1)).mul
    (PadicBernoulli.tendsto_normPowSum (p := p) (m+1))).div_const ((m : ℚ_[p])+1)).sub
    (hsmall.div_const ((m : ℚ_[p])+1))
  simpa only [hkernel, zero_div, sub_zero, smoothedValue] using ht

theorem smoothedValue_integral (c m : ℕ) (hc : p.Coprime c) :
    ‖smoothedValue (p := p) c m‖ ≤ 1 :=
  le_of_tendsto (carryMoment_tendsto c m hc).norm
    (Eventually.of_forall fun _ => Padic.norm_int_le_one _)

/-- A representative of a generator of the multiplicative residue field makes
    the smoothing factor a unit in every nonzero class modulo p-1. -/
theorem exists_smoothing_unit {n : ℕ} (hn : ¬ (p-1) ∣ n) :
    ∃ c : ℕ, p.Coprime c ∧ (c : ZMod p)^n ≠ 1 := by
  obtain ⟨g, hg⟩ :=
    (isCyclic_iff_exists_orderOf_eq_natCard.mp (inferInstance : IsCyclic (ZMod p)ˣ))
  have ho : orderOf g = p-1 := by
    simpa only [Nat.card_eq_fintype_card, ZMod.card_units, Nat.totient_prime (Fact.out : p.Prime)] using hg
  refine ⟨(g : ZMod p).val, ?_, ?_⟩
  · apply (Fact.out : p.Prime).coprime_iff_not_dvd.mpr
    intro hd
    have hz := (ZMod.natCast_eq_zero_iff (g : ZMod p).val p).mpr hd
    rw [ZMod.natCast_zmod_val] at hz
    exact g.ne_zero hz
  · rw [ZMod.natCast_zmod_val]
    intro h
    have h' : g^n = 1 := Units.ext (by simpa using h)
    exact hn (ho ▸ orderOf_dvd_of_pow_eq_one h')

theorem norm_smoothing_factor {c n : ℕ} (hn : (c : ZMod p)^n ≠ 1) :
    ‖(c : ℚ_[p])^n-1‖ = 1 := by
  let z : ℤ := (c : ℤ)^n-1
  have hcast : (z : ℚ_[p]) = (c : ℚ_[p])^n-1 := by simp [z]
  rw [← hcast]
  apply le_antisymm (Padic.norm_int_le_one z)
  apply le_of_not_gt
  intro hlt
  have hd := (Padic.norm_intCast_lt_one_iff.mp hlt)
  have hz := (ZMod.intCast_zmod_eq_zero_iff_dvd z p).mpr hd
  apply hn
  exact sub_eq_zero.mp (by simpa [z] using hz)

theorem divided_bernoulli_integral {n : ℕ} (hn : 0 < n) (hclass : ¬ (p-1) ∣ n) :
    ‖(bernoulli n : ℚ_[p]) / (n : ℚ_[p])‖ ≤ 1 := by
  obtain ⟨m, rfl⟩ := Nat.exists_eq_succ_of_ne_zero hn.ne'
  obtain ⟨c, hc, hu⟩ := exists_smoothing_unit hclass
  have h := smoothedValue_integral (p := p) c m hc
  simpa only [smoothedValue, mul_div_assoc, norm_mul, norm_smoothing_factor hu, one_mul,
    Nat.cast_succ] using h

private theorem residue_pow {m n : ℕ} (x : ZMod p) (hm : m ≠ 0) (hn : n ≠ 0)
    (h : m ≡ n [MOD p-1]) : x^m = x^n := by
  by_cases hx : x = 0
  · simp [hx, hm, hn]
  · exact pow_eq_pow_of_modEq h (ZMod.pow_card_sub_one_eq_one hx)

theorem carryMoment_congruent (c q : ℕ) {m n : ℕ} (hm : m ≠ 0) (hn : n ≠ 0)
    (h : m ≡ n [MOD p-1]) : (p : ℤ) ∣ carryMoment c q m - carryMoment c q n := by
  apply (ZMod.intCast_zmod_eq_zero_iff_dvd _ p).mp
  rw [Int.cast_sub, sub_eq_zero]
  unfold carryMoment
  push_cast
  exact Finset.sum_congr rfl (fun a _ => by rw [residue_pow _ hm hn h])

private theorem norm_int_difference (a b : ℤ) (h : (p : ℤ) ∣ a-b) :
    ‖(a : ℚ_[p])-(b : ℚ_[p])‖ ≤ (p : ℝ)⁻¹ := by
  have hh := (Padic.norm_int_le_pow_iff_dvd (p := p) (a-b) 1).mpr (by simpa using h)
  simpa using hh

theorem smoothedValue_congruent (c : ℕ) (hc : p.Coprime c) {m n : ℕ} (hm : m ≠ 0)
    (hn : n ≠ 0) (h : m ≡ n [MOD p-1]) :
    ‖smoothedValue (p := p) c m - smoothedValue c n‖ ≤ (p : ℝ)⁻¹ := by
  apply le_of_tendsto (((carryMoment_tendsto c m hc).sub (carryMoment_tendsto c n hc)).norm)
  exact Eventually.of_forall (fun r => norm_int_difference _ _ (carryMoment_congruent c (p^r) hm hn h))

/-- The divided Bernoulli congruence, including indices divisible by p. -/
theorem divided_bernoulli_kummer {m n : ℕ} (hm : m ≠ 0) (hn : n ≠ 0)
    (h : m ≡ n [MOD p-1]) (hmclass : ¬ (p-1) ∣ m+1) :
    ‖(bernoulli (m+1) : ℚ_[p]) / (↑(m+1 : ℕ) : ℚ_[p]) -
      (bernoulli (n+1) : ℚ_[p]) / (↑(n+1 : ℕ) : ℚ_[p])‖ ≤ (p : ℝ)⁻¹ := by
  obtain ⟨c, hc, hu⟩ := exists_smoothing_unit hmclass
  have h' : m+1 ≡ n+1 [MOD p-1] := h.add_right 1
  have hpow := residue_pow (c : ZMod p) (Nat.succ_ne_zero m) (Nat.succ_ne_zero n) h'
  have hnclass : ¬ (p-1) ∣ n+1 := by
    intro hd
    apply hmclass
    exact Nat.dvd_of_mod_eq_zero ((show (m+1) % (p-1) = (n+1) % (p-1) from h').trans
      (Nat.mod_eq_zero_of_dvd hd))
  set A : ℚ_[p] := (bernoulli (m+1) : ℚ_[p]) / (↑(m+1 : ℕ) : ℚ_[p])
  set B : ℚ_[p] := (bernoulli (n+1) : ℚ_[p]) / (↑(n+1 : ℕ) : ℚ_[p])
  set U : ℚ_[p] := (c : ℚ_[p])^(m+1)-1
  set V : ℚ_[p] := (c : ℚ_[p])^(n+1)-1
  have huNorm : ‖U‖ = 1 := norm_smoothing_factor hu
  have hb : ‖B‖ ≤ 1 := divided_bernoulli_integral (Nat.succ_pos n) hnclass
  have huv : ‖V-U‖ ≤ (p : ℝ)⁻¹ := by
    have hdiv : (p : ℤ) ∣ (c:ℤ)^(n+1)-(c:ℤ)^(m+1) := by
      apply (ZMod.intCast_zmod_eq_zero_iff_dvd _ p).mp
      simpa using (sub_eq_zero.mpr hpow.symm)
    have hnorm := norm_int_difference (p := p) ((c:ℤ)^(n+1)) ((c:ℤ)^(m+1)) hdiv
    simpa [V, U] using hnorm
  have hAB : ‖U*A - V*B‖ ≤ (p:ℝ)⁻¹ := by
    simpa [A, B, U, V, smoothedValue, mul_div_assoc] using (smoothedValue_congruent c hc hm hn h)
  calc
    ‖A-B‖ = ‖U*(A-B)‖ := by rw [norm_mul, huNorm, one_mul]
    _ = ‖(U*A-V*B)+(V-U)*B‖ := by congr 1; ring
    _ ≤ _ := (IsUltrametricDist.norm_add_le_max _ _).trans (max_le hAB (by
      rw [norm_mul]
      exact (mul_le_of_le_one_right (norm_nonneg _) hb).trans huv))

/-- Transfer of the divided value to the completed algebraic closure. -/
theorem complex_divided_integral {n : ℕ} (hn : 0 < n) (hclass : ¬ (p-1) ∣ n) :
    ‖-(bernoulli n : ℂ_[p]) / (n : ℂ_[p])‖ ≤ 1 := by
  let φ : ℚ_[p] →+* ℂ_[p] := algebraMap _ _
  have hnorm (x : ℚ_[p]) : ‖φ x‖ = ‖x‖ := PadicComplex.norm_extends' p x
  rw [neg_div, norm_neg]
  calc
    _ = ‖φ ((bernoulli n : ℚ_[p]) / (n : ℚ_[p]))‖ := by simp
    _ = _ := hnorm _
    _ ≤ 1 := divided_bernoulli_integral hn hclass

theorem complex_kummer {m n : ℕ} (hm : 0 < m) (hn : 0 < n)
    (hmn : Int.ModEq ((p-1 : ℕ) : ℤ) m n)
    (hmres : ¬Int.ModEq ((p-1 : ℕ) : ℤ) m (-1)) :
    ‖-(bernoulli (m+1) : ℂ_[p]) / ((m : ℂ_[p])+1)‖ ≤ 1 ∧
    ‖-(bernoulli (n+1) : ℂ_[p]) / ((n : ℂ_[p])+1)‖ ≤ 1 ∧
    ‖(-(bernoulli (m+1) : ℂ_[p]) / ((m : ℂ_[p])+1) -
      -(bernoulli (n+1) : ℂ_[p]) / ((n : ℂ_[p])+1)) / (p : ℂ_[p])‖ ≤ 1 := by
  have h : m ≡ n [MOD p-1] := Int.natCast_modEq_iff.mp hmn
  have hclass {t : ℕ} (ht : ¬Int.ModEq ((p-1 : ℕ) : ℤ) t (-1)) : ¬ (p-1) ∣ t+1 := by
    intro hd
    apply ht
    rw [Int.modEq_iff_dvd]
    have hz : ((p-1 : ℕ) : ℤ) ∣ (t : ℤ)+1 := by exact_mod_cast hd
    convert dvd_neg.mpr hz using 1
    ring
  have hmclass := hclass hmres
  have hnclass := hclass (fun hn' => hmres (hmn.trans hn'))
  refine ⟨by simpa using complex_divided_integral (Nat.succ_pos m) hmclass,
    by simpa using complex_divided_integral (Nat.succ_pos n) hnclass, ?_⟩
  let φ : ℚ_[p] →+* ℂ_[p] := algebraMap _ _
  let A : ℚ_[p] := (bernoulli (m+1) : ℚ_[p]) / (↑(m+1 : ℕ) : ℚ_[p])
  let B : ℚ_[p] := (bernoulli (n+1) : ℚ_[p]) / (↑(n+1 : ℕ) : ℚ_[p])
  have hbound : ‖A-B‖ ≤ (p : ℝ)⁻¹ := divided_bernoulli_kummer hm.ne' hn.ne' h hmclass
  have hnorm (x : ℚ_[p]) : ‖φ x‖ = ‖x‖ := PadicComplex.norm_extends' p x
  have hpos : 0 < (p : ℝ)⁻¹ := inv_pos.mpr (by exact_mod_cast (Fact.out : p.Prime).pos)
  calc
    _ = ‖φ ((B-A) / (p : ℚ_[p]))‖ := by simp [A, B]; ring_nf
    _ = _ := hnorm _
    _ ≤ 1 := by rw [norm_div, Padic.norm_p, div_le_one₀ hpos, norm_sub_rev]; exact hbound

end Thesis.FiniteBernoulli

#print axioms Thesis.FiniteBernoulli.divided_bernoulli_integral
#print axioms Thesis.FiniteBernoulli.divided_bernoulli_kummer
#print axioms Thesis.FiniteBernoulli.complex_kummer
