module

public import SubentropyCertificates.BinaryCrossoverConvex
public import Mathlib.Analysis.Convex.Slope

/-! Existence, uniqueness and sign of the crossing in Appendix F.3. -/
@[expose] public section
noncomputable section
set_option autoImplicit false
set_option backward.isDefEq.respectTransparency false
open Set Filter
open scoped Topology
namespace SubentropyCertificates.BinaryCrossover
open SubentropyCertificates.SmallOverlap
open SubentropyCertificates.ClassicalCurve
open SubentropyCertificates.Discrimination

theorem gap_zero : gap 0 = 0 := by norm_num [gap,conditionalCurve,phi_zero]

theorem gap_one_pos : 0 < gap 1 := by
  have h := phi_strictMono 0
    (show (1/4 : ℝ) ∈ Icc 0 (uniformError 0) by norm_num [uniformError])
    (show (1/2 : ℝ) ∈ Icc 0 (uniformError 0) by norm_num [uniformError]) (by norm_num)
  simpa [gap, conditionalCurve, phi_zero, sub_pos] using h

theorem gap_continuousOn : ContinuousOn gap (Icc (0 : ℝ) 1) := by
  have h1 : ContinuousOn (fun t : ℝ ↦ (1-Real.sqrt t)/2) (Icc 0 1) := by fun_prop
  have h2 : ContinuousOn (fun t : ℝ ↦ t/4) (Icc 0 1) := by fun_prop
  have h1' (t : ℝ) (ht : t ∈ Icc 0 1) : (1-Real.sqrt t)/2 ∈ Icc (0:ℝ) 1 := by
    have hh := Real.sqrt_le_sqrt ht.2
    rw [Real.sqrt_one] at hh
    constructor <;> linarith [Real.sqrt_nonneg t]
  have h2' (t : ℝ) (ht : t ∈ Icc 0 1) : t/4 ∈ Icc (0:ℝ) 1 := by constructor <;> linarith [ht.1,ht.2]
  exact (continuousOn_const.sub ((phi_continuous 0).comp h1 h1')).sub
    ((phi_continuous 0).comp h2 h2')

theorem gap_slope_tendsto : Tendsto (fun t ↦ gap t/t) (𝓝[>] (0:ℝ)) (𝓝 (-1/12)) := by
  have ht : Tendsto (fun x : ℝ ↦ x) (𝓝[>] 0) (𝓝 0) := nhdsWithin_le_nhds
  have htpos : ∀ᶠ t : ℝ in 𝓝[>] 0, 0 < t := self_mem_nhdsWithin
  have hs : Tendsto Real.sqrt (𝓝[>] (0:ℝ)) (𝓝[>] 0) := by
    apply tendsto_nhdsWithin_iff.mpr
    exact ⟨by simpa only [Function.comp_def, Real.sqrt_zero] using Real.continuous_sqrt.continuousAt.tendsto.comp ht,
      htpos.mono (fun t (h : 0 < t) ↦ Real.sqrt_pos.2 h)⟩
  have h4 : Tendsto (fun t : ℝ ↦ t/4) (𝓝[>] 0) (𝓝[>] 0) := by
    apply tendsto_nhdsWithin_iff.mpr
    exact ⟨by simpa using ht.div_const 4,
      htpos.mono (fun t (h : 0 < t) ↦ by change 0 < t/4; positivity)⟩
  have h := (overlap_leading_terms.1.comp hs).sub
    (((phi_div_error_tendsto_one 0).comp h4).div_const 4)
  have hl : (1/6:ℝ)-1/4 = -1/12 := by norm_num
  rw [← hl]
  apply h.congr'
  filter_upwards [self_mem_nhdsWithin] with t (ht : 0<t)
  change conditionalCurve (Real.sqrt t)/(Real.sqrt t)^2 - phi 0 (t/4)/(t/4)/4 = gap t/t
  rw [Real.sq_sqrt ht.le]
  unfold gap
  ring

theorem gap_right_derivative : HasDerivWithinAt gap (-1/12) (Ioi 0) 0 := by
  apply (hasDerivWithinAt_iff_tendsto_slope' (show (0:ℝ) ∉ Ioi 0 from lt_irrefl _)).2
  simpa only [slope_fun_def_field,gap_zero,sub_zero] using gap_slope_tendsto

theorem gap_ratio_strictMono : StrictMonoOn (fun t : ℝ ↦ gap t/t) (Ioc 0 1) := by
  intro x hx y hy hxy
  have h := gap_strictConvex.secant_strict_mono_aux2 (show (0:ℝ) ∈ Icc 0 1 by norm_num)
    ⟨hy.1.le,hy.2⟩ hx.1 hxy
  simpa only [gap_zero,sub_zero] using h

/-- The unique positive crossing in the squared overlap, with ordering on both sides. -/
theorem crossing_exists :
    ∃ u ∈ Ioo (0:ℝ) 1, gap u = 0 ∧
      (∀ t ∈ Ioc (0:ℝ) 1, gap t = 0 ↔ t = u) ∧
      (∀ t ∈ Ioo (0:ℝ) u, gap t < 0) ∧ (∀ t ∈ Ioc u 1, 0 < gap t) := by
  have hneg := gap_slope_tendsto.eventually_lt_const (show (-1/12:ℝ)<0 by norm_num)
  have hsmall : ∀ᶠ t : ℝ in 𝓝[>] 0, t ∈ Ioo 0 1 := Ioo_mem_nhdsGT_of_mem ⟨le_rfl,zero_lt_one⟩
  obtain ⟨w,hw,hw'⟩ := (hsmall.and hneg).exists
  have hwneg : gap w < 0 := by simpa using (div_lt_iff₀ hw.1).mp hw'
  have hsubset : Icc w 1 ⊆ Icc (0:ℝ) 1 := Icc_subset_Icc_left hw.1.le
  obtain ⟨u,hu,hu0⟩ := intermediate_value_Icc hw.2.le (gap_continuousOn.mono hsubset)
    (show (0:ℝ) ∈ Icc (gap w) (gap 1) from ⟨hwneg.le,gap_one_pos.le⟩)
  have hu1 : u < 1 := lt_of_le_of_ne hu.2 (fun he ↦ by rw [he] at hu0; linarith [gap_one_pos])
  have hu' := lt_of_lt_of_le hw.1 hu.1
  have low (t : ℝ) (ht : t ∈ Ioo 0 u) : gap t < 0 := by
    have hh := gap_ratio_strictMono ⟨ht.1,ht.2.le.trans hu.2⟩ ⟨hu',hu.2⟩ ht.2
    change gap t/t < gap u/u at hh
    rw [hu0,zero_div] at hh
    simpa using (div_lt_iff₀ ht.1).mp hh
  have high (t : ℝ) (ht : t ∈ Ioc u 1) : 0 < gap t := by
    have ht0 := hu'.trans ht.1
    have hh := gap_ratio_strictMono ⟨hu',hu.2⟩ ⟨ht0,ht.2⟩ ht.1
    change gap u/u < gap t/t at hh
    rw [hu0,zero_div] at hh
    simpa using (lt_div_iff₀ ht0).1 hh
  refine ⟨u,⟨hu',hu1⟩,hu0,?_,low,high⟩
  intro t ht
  refine ⟨fun h ↦ ?_, fun h ↦ h ▸ hu0⟩
  rcases lt_trichotomy t u with htu|he|hut
  · exact False.elim (ne_of_lt (low t ⟨ht.1,htu⟩) h)
  · exact he
  · exact False.elim (ne_of_gt (high t ⟨hut,ht.2⟩) h)

/-- The sign comparison in the paper is between the original lower bound and s²/4. -/
theorem bound_comparison (s : Icc (0:ℝ) 1) :
    (subentropyBound s < (s:ℝ)^2/4 ↔ gap ((s:ℝ)^2) < 0) ∧
    (subentropyBound s = (s:ℝ)^2/4 ↔ gap ((s:ℝ)^2) = 0) ∧
    ((s:ℝ)^2/4 < subentropyBound s ↔ 0 < gap ((s:ℝ)^2)) := by
  have hq := phiInverse_mem 0 _ (conditionalCurve_mem s)
  have hs : (s:ℝ)^2/4 ∈ Icc 0 (uniformError 0) := by
    have hsq := pow_le_pow_left₀ s.2.1 s.2.2 2
    rw [one_pow] at hsq
    rw [show uniformError 0 = 1/2 by norm_num [uniformError]]
    constructor <;> nlinarith [sq_nonneg (s:ℝ)]
  change subentropyBound s ∈ Icc 0 (uniformError 0) at hq
  have hm := phi_strictMono 0
  unfold gap
  rw [Real.sqrt_sq s.2.1, ← phi_bound s, sub_neg, sub_eq_zero, sub_pos]
  exact ⟨(hm.lt_iff_lt hq hs).symm, (hm.eq_iff_eq hq hs).symm, (hm.lt_iff_lt hs hq).symm⟩


/-- The unique interior threshold in the physical overlap: the subentropy bound is smaller
than the fidelity bound below it and larger above it. Orthogonal signals give equality at zero. -/
theorem overlap_crossing :
    ∃ s₀ ∈ Ioo (0:ℝ) 1, ∀ s : Icc (0:ℝ) 1,
      (subentropyBound s = (s:ℝ)^2/4 ↔ (s:ℝ) = 0 ∨ (s:ℝ) = s₀) ∧
      (0 < (s:ℝ) → (s:ℝ) < s₀ → subentropyBound s < (s:ℝ)^2/4) ∧
      (s₀ < (s:ℝ) → (s:ℝ)^2/4 < subentropyBound s) := by
  obtain ⟨u,hu,hu0,huniq,hlo,hhi⟩ := crossing_exists
  have hr := Real.sq_sqrt hu.1.le
  have hrpos := Real.sqrt_pos.2 hu.1
  refine ⟨Real.sqrt u,⟨hrpos,?_⟩,?_⟩
  · exact (Real.sqrt_lt' zero_lt_one).2 (by simpa only [one_pow] using hu.2)
  intro s
  obtain ⟨hlt,heq,hgt⟩ := bound_comparison s
  have hs1 : (s:ℝ)^2 ≤ 1 := by simpa only [one_pow] using pow_le_pow_left₀ s.2.1 s.2.2 2
  constructor
  · rw [heq]
    by_cases h : (s:ℝ) = 0
    · simp [h, gap_zero]
    have hp := lt_of_le_of_ne s.2.1 (Ne.symm h)
    rw [huniq _ ⟨sq_pos_of_pos hp,hs1⟩, or_iff_right h]
    constructor
    · intro e
      exact (Real.sqrt_sq s.2.1).symm.trans (congrArg Real.sqrt e)
    · rintro e
      rw [e,hr]
  constructor
  · intro hs0 h
    apply hlt.2 (hlo _ ⟨sq_pos_of_pos hs0, ?_⟩)
    nlinarith [mul_pos (sub_pos.mpr h) (add_pos hrpos hs0)]
  · intro h
    apply hgt.2 (hhi _ ⟨?_,hs1⟩)
    nlinarith [mul_pos (sub_pos.mpr h) (add_pos hrpos (hrpos.trans h))]

end SubentropyCertificates.BinaryCrossover
