module

public import SubentropyCertificates.AncillaReplicatedFactor
import Mathlib.Analysis.Calculus.LHopital
import Mathlib.Analysis.Calculus.DSlope

/-! Pointwise large-ancilla expansion of the reciprocal determinant at a fixed spectrum. -/
@[expose] public section
noncomputable section
open Filter Set
open scoped BigOperators Topology

namespace SubentropyCertificates.AncillaLimit

private theorem scaled_log_correction (b : ℝ) (hb : 0 ≤ b) :
    Tendsto (fun x : ℝ ↦ (b*x - Real.log (1+b*x))/x^2) (𝓝[>] 0) (𝓝 (b^2/2)) := by
  have hpos : ∀ᶠ x : ℝ in 𝓝[>] 0, 0 < x := self_mem_nhdsWithin
  apply HasDerivAt.lhopital_zero_nhdsGT (f' := fun x ↦ b - b / (1+b*x))
    (g' := fun x ↦ 2*x)
  · filter_upwards [hpos] with x hx
    have hd : HasDerivAt (fun y : ℝ ↦ b*y) b x := by simpa using (hasDerivAt_id x).const_mul b
    exact hd.sub ((hd.const_add 1).log (by positivity))
  · exact .of_forall fun x ↦ by simpa using hasDerivAt_pow 2 x
  · filter_upwards [hpos] with x hx using ne_of_gt (by positivity)
  · have h : ContinuousAt (fun x : ℝ ↦ b*x - Real.log (1+b*x)) 0 := by fun_prop (disch := norm_num)
    simpa using h.continuousWithinAt (s := Ioi 0) |>.tendsto
  · have h : ContinuousAt (fun x : ℝ ↦ x^2) 0 := by fun_prop
    simpa using (h.continuousWithinAt (s := Ioi 0)).tendsto
  · have h : ContinuousAt (fun x : ℝ ↦ b^2 / (2*(1+b*x))) 0 := by fun_prop (disch := norm_num)
    apply ((show Tendsto (fun x : ℝ ↦ b^2 / (2*(1+b*x))) (𝓝[>] 0) (𝓝 (b^2/2)) by
      simpa using h.continuousWithinAt (s := Ioi 0) |>.tendsto)).congr'
    filter_upwards [hpos] with x hx
    have hden : 0 < 1+b*x := by positivity
    field_simp
    ring

/-- At fixed positive t, the first finite-ancilla correction is half the spectral purity
times the exponential density after division by t squared. -/
theorem replicatedFactor_centered_tendsto {I : Type*} [Fintype I] (w : I → ℝ)
    (hw : ∀ i, 0 ≤ w i) (hs : ∑ i, w i = 1) {t : ℝ} (ht : 0 < t) :
    Tendsto (fun k : ℕ ↦ ((k+1 : ℕ) : ℝ) * (replicatedFactor w k t - Real.exp (-t)) / t^2)
      atTop (𝓝 ((∑ i, w i ^ 2) / 2 * Real.exp (-t))) := by
  let N := fun k : ℕ ↦ ((k+1 : ℕ) : ℝ)
  let a := fun k ↦ 1 / N k
  let b := fun i ↦ t * w i
  let D := fun k ↦ t - N k * ∑ i, Real.log (1 + b i * a k)
  let P := (∑ i, b i ^ 2) / 2
  have hN (k) : 0 < N k := by dsimp [N]; positivity
  have ha : Tendsto a atTop (𝓝 (0 : ℝ)) := by simpa [a,N] using
    (tendsto_one_div_add_atTop_nhds_zero_nat (𝕜 := ℝ))
  have har : Tendsto a atTop (𝓝[>] 0) :=
    tendsto_nhdsWithin_iff.mpr ⟨ha, .of_forall fun k ↦ one_div_pos.mpr (hN k)⟩
  have hb (i) : 0 ≤ b i := mul_nonneg ht.le (hw i)
  have hbs : ∑ i, b i = t := by simp [b, ← Finset.mul_sum, hs]
  have hsum := tendsto_finsetSum Finset.univ (fun i _ ↦ (scaled_log_correction (b i) (hb i)).comp har)
  have hcorr : Tendsto (fun k ↦ N k * D k) atTop (𝓝 P) := by
    rw [← Finset.sum_div] at hsum
    apply hsum.congr'
    apply Eventually.of_forall
    intro k
    simp only [Function.comp_apply, ← Finset.sum_div, Finset.sum_sub_distrib, ← Finset.sum_mul, hbs]
    dsimp only [D,a]
    field_simp [(hN k).ne']
  have hd : Tendsto D atTop (𝓝 0) := by
    have H := hcorr.mul ha
    simp only [mul_zero] at H
    exact H.congr (fun k ↦ by dsimp [a]; field_simp [(hN k).ne'])
  have hsl : Tendsto (fun k ↦ dslope Real.exp 0 (D k)) atTop (𝓝 1) := by
    simpa [Function.comp_def] using ((continuousAt_dslope_same.mpr (Real.hasDerivAt_exp 0).differentiableAt).tendsto.comp hd)
  have hfac (k) : replicatedFactor w k t = Real.exp (-t) * Real.exp (D k) := by
    have H (i) : 0 < 1+b i*a k := by
      have := hb i
      have := one_div_pos.mpr (hN k)
      dsimp [a]; positivity
    rw [← Real.exp_add, show -t + D k = -(N k * ∑ i, Real.log (1+b i*a k)) by dsimp [D]; ring,
      Real.exp_neg, Real.exp_nat_mul, Real.exp_sum]
    have hexp (i) : Real.exp (Real.log (1+b i*a k)) = 1+b i*a k := Real.exp_log (H i)
    simp_rw [hexp]
    simp only [replicatedFactor, inv_pow, b, a, N, mul_one_div]
  have hscaled := ((hcorr.mul hsl).const_mul (Real.exp (-t))).div_const (t^2)
  have htarget : Real.exp (-t) * (P * 1) / t^2 = (∑ i, w i ^ 2)/2 * Real.exp (-t) := by
    simp only [P, b, mul_pow, ← Finset.mul_sum, mul_one]
    field_simp [ht.ne']
  rw [htarget] at hscaled
  apply hscaled.congr
  intro k
  have H := sub_smul_dslope Real.exp 0 (D k)
  simp only [sub_zero, smul_eq_mul, Real.exp_zero] at H
  rw [hfac]
  change Real.exp (-t) * (N k * D k * dslope Real.exp 0 (D k)) / t^2 = _
  rw [mul_assoc (N k), H]
  ring

end SubentropyCertificates.AncillaLimit
