module

public import SubentropyCertificates.EndpointCurvatureMoments
public import SubentropyCertificates.EndpointCurvatureGradient
public import SubentropyCertificates.GaussianGradientDefs
import all SubentropyCertificates.EndpointCurvatureGradient
import all SubentropyCertificates.ExponentialSignMoments
import all SubentropyCertificates.GaussianSpatialSign

/-! The mixed partial derivatives of the Gaussian spectral functional at the uniform state. -/
@[expose] public section
noncomputable section
open MeasureTheory ProbabilityTheory Real Set Filter
open scoped BigOperators Topology
namespace SubentropyCertificates.EndpointCurvature
open SubentropyCertificates.ConditionalContinuity
open SubentropyCertificates.Representations
local instance : IsProbabilityMeasure (expMeasure 1) := isProbabilityMeasure_expMeasure one_pos
variable {D : Type*} [Fintype D] [DecidableEq D]

omit [DecidableEq D] in
/-- On diagonal weights the exponential and circular complex Gaussian expectations agree. -/
theorem spectralGaussianF_eq_circular (w : D → ℝ) :
    spectralGaussianF w = ∫ g, diagonalEnergy w g*log (diagonalEnergy w g) ∂circularGaussian D :=
  (radii_test (fun z ↦ (∑ j, w j*z j)*log (∑ j, w j*z j)) (by fun_prop)).symm

private theorem derivative_slope (i j : D) :
    let w := fun _ : D ↦ 1/(Fintype.card D : ℝ)
    HasDerivAt (fun h ↦ slope (addCoordinate w j h) i)
      ((Fintype.card D : ℝ)*(1+(if i=j then 1 else 0))/(Fintype.card D+1 : ℝ)) 0 := by
  dsimp only
  let c := 1/(Fintype.card D : ℝ)
  have : Nonempty D := ⟨i⟩
  have hc : 0<c := by dsimp [c]; positivity
  let w := fun _ : D ↦ c
  let T := energy w
  let F := fun h (z : D → ℝ) ↦ z i*(log (T z+h*z j)+1)
  let G := fun h (z : D → ℝ) ↦ z i*z j/(T z+h*z j)
  let b := fun z : D → ℝ ↦ z i*(2/c)
  let s := Ioo (-(c/2)) (c/2)
  have hs : s ∈ 𝓝 (0:ℝ) := Ioo_mem_nhds (by linarith) (by positivity)
  have hb : Integrable b (expLaw D) := (unit_coord_integrable i).mul_const _
  have hT (z : D → ℝ) : T z = c * ∑ k, z k := by simp [T,energy,w,Finset.mul_sum]
  have hlow {z : D → ℝ} (hz : ∀ k, 0<z k) {h : ℝ} (hh : h ∈ s) :
      0 < T z+h*z j ∧ c/2*z j ≤ T z+h*z j := by
    have hj : c*z j ≤ T z :=
      Finset.single_le_sum (fun k _ ↦ (mul_pos hc (hz k)).le) (Finset.mem_univ j)
    have hl := mul_lt_mul_of_pos_right hh.1 (hz j)
    constructor <;> nlinarith [mul_pos hc (hz j)]
  have hi : Integrable (F 0) (expLaw D) := by
    simpa [F,T,energy,mul_add,Pi.add_def] using
      ((exponential_log_integrable w (fun _ ↦ hc) i).2.add (unit_coord_integrable i))
  have hi' := hasDerivAt_integral_of_dominated_loc_of_deriv_le (μ:=expLaw D)
    (F:=F) (F':=G) (bound:=b) hs
    (.of_forall fun _ ↦ by apply Measurable.aestronglyMeasurable; dsimp [F,T,energy]; fun_prop) hi
    (by apply Measurable.aestronglyMeasurable; dsimp [G,T,energy]; fun_prop)
    (exp_coord_pos.mono (fun z hz h hh ↦ by
      obtain ⟨hp,hl⟩ := hlow hz hh
      change ‖z i*z j/(T z+h*z j)‖ ≤ z i*(2/c)
      rw [Real.norm_of_nonneg (div_nonneg (mul_pos (hz i) (hz j)).le hp.le),div_le_iff₀ hp]
      have hh' : z j ≤ 2/c*(T z+h*z j) := by
        field_simp
        nlinarith
      nlinarith [mul_le_mul_of_nonneg_left hh' (hz i).le]))
    hb (exp_coord_pos.mono (fun z hz h hh ↦ by
      have hp := (hlow hz hh).1
      have dd : HasDerivAt (fun t : ℝ ↦ T z+t*z j) (z j) h := by
        simpa using ((hasDerivAt_id h).mul_const (z j)).const_add (T z)
      convert ((dd.log hp.ne').add_const 1).const_mul (z i) using 1
      dsimp [F,G]
      ring))
  have hval : (∫ z : D → ℝ, G 0 z ∂expLaw D) =
      (Fintype.card D : ℝ)*(1+(if i=j then 1 else 0))/(Fintype.card D+1 : ℝ) := by
    simpa only [G,zero_mul,mul_zero,add_zero,mul_one,one_mul,hT,c,one_div,div_eq_mul_inv,mul_comm] using
      uniform_exponential_hessian_moment i j
  rw [hval] at hi'
  simpa only [slope,shift_energy,F,T,w,c] using hi'.2

/-- The actual iterated coordinate derivative ∂j∂i F, including the diagonal entries. -/
theorem spectralGaussianF_uniform_hessian (i j : D) :
    let w := fun _ : D ↦ 1/(Fintype.card D : ℝ)
    deriv (fun h ↦ deriv (fun t ↦ spectralGaussianF (addCoordinate (addCoordinate w j h) i t)) 0) 0 =
      (Fintype.card D : ℝ)*(1+(if i=j then 1 else 0))/(Fintype.card D+1 : ℝ) := by
  let w := fun _ : D ↦ 1/(Fintype.card D : ℝ)
  have : Nonempty D := ⟨i⟩
  have hp : ∀ᶠ h : ℝ in 𝓝 0, ∀ k, 0 < addCoordinate w j h k := by
    apply eventually_all.mpr
    intro k
    by_cases hh : k=j
    · have hc : 0 < w k+0 := by dsimp [w]; positivity
      simpa [addCoordinate,hh,w] using (continuous_const.add continuous_id).continuousAt.eventually_const_lt hc
    · exact .of_forall (fun _ ↦ by simp [addCoordinate,hh,w]; positivity)
  apply HasDerivAt.deriv
  apply (derivative_slope i j).congr_of_eventuallyEq
  filter_upwards [hp] with h hh
  exact (gaussian_coordinate_derivative _ hh i).deriv

end SubentropyCertificates.EndpointCurvature
