module

public import SubentropyCertificates.CurveInverse
public import SubentropyCertificates.IdenticalPureSignals

/-! Pointwise optimality of the curve and its inverse, without regularity
assumptions on competing universal bounds. -/

@[expose] public section
noncomputable section
set_option autoImplicit false
set_option backward.isDefEq.respectTransparency false
open Set
open scoped BigOperators

namespace SubentropyCertificates.Discrimination
open D5.S3.Quantum.Foundation.FiniteStateChannel
open D5.S3.Quantum.Subentropy.ClassicalQuantumGram
open D5.S3.Quantum.Subentropy.GuessingProbability
open SubentropyCertificates.ClassicalCurve

variable {B : Type*} [Fintype B] [DecidableEq B] [Nonempty B]

theorem inverse_attainable_in_dimension (m : ℕ) (q : ℝ) (hq : q ∈ curveRange m) :
    ∃ (p : Option (Fin (m + 1)) → ℝ) (hp : ∀ x, 0 ≤ p x) (hs : ∑ x, p x = 1)
      (ρ : Option (Fin (m + 1)) → DensityState B),
      conditionalSubentropy p hp hs ρ = q ∧ 1 - pGuess p ρ = phiInverse m q hq := by
  obtain ⟨p, hp, hs, ρ, he, hq'⟩ :=
    curve_attainable_in_dimension (B := B) m (phiInverse m q hq) (phiInverse_mem m q hq)
  exact ⟨p, hp, hs, ρ, hq'.trans (phi_phiInverse m q hq), he⟩

theorem universal_upper_bound_ge_curve (m : ℕ) (U : ℝ → ℝ)
    (hU : ∀ (p : Option (Fin (m + 1)) → ℝ) (hp : ∀ x, 0 ≤ p x)
      (hs : ∑ x, p x = 1) (ρ : Option (Fin (m + 1)) → DensityState B),
      conditionalSubentropy p hp hs ρ ≤ U (1 - pGuess p ρ))
    (e : ℝ) (he : e ∈ Icc 0 (uniformError m)) : phi m e ≤ U e := by
  obtain ⟨p, hp, hs, ρ, he', hq'⟩ := curve_attainable_in_dimension (B := B) m e he
  have h := hU p hp hs ρ
  rw [he', hq'] at h
  exact h

theorem universal_lower_bound_le_inverse (m : ℕ) (L : ℝ → ℝ)
    (hL : ∀ (p : Option (Fin (m + 1)) → ℝ) (hp : ∀ x, 0 ≤ p x)
      (hs : ∑ x, p x = 1) (ρ : Option (Fin (m + 1)) → DensityState B),
      L (conditionalSubentropy p hp hs ρ) ≤ 1 - pGuess p ρ)
    (q : ℝ) (hq : q ∈ curveRange m) : L q ≤ phiInverse m q hq := by
  obtain ⟨p, hp, hs, ρ, hq', he'⟩ := inverse_attainable_in_dimension (B := B) m q hq
  have h := hL p hp hs ρ
  rw [hq', he'] at h
  exact h

end SubentropyCertificates.Discrimination
