/-
Copyright (c) 2026 the Nonadditivity project contributors.
All rights reserved. See COPYRIGHT.md for licensing and attribution.
-/

import Mathlib.Analysis.Normed.Module.FiniteDimension
import Mathlib.Data.Real.Sqrt
import Mathlib.MeasureTheory.Measure.Typeclasses.Probability
import Mathlib.Tactic.Abel
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.Ring

/-!
# Finite observable tests and the uniform norm certificate

The traceless Hermitian matrices with Hilbert--Schmidt norm form a real
finite dimensional normed space.  The results below apply to this space
without replacing a linear operator by a table of scalar bounds.

The external Collins--Youn and random-matrix convergence theorems are
represented by explicit bound and convergence hypotheses. They are not
declared as axioms or treated as results proved by this file.
-/

namespace Nonadditivity

open Metric

section FiniteNet

variable {E F : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E]
  [NormedAddCommGroup F] [NormedSpace ℝ F]

/-- A finite set of tests approximating every unit vector. -/
def UnitSphereNet (tests : Finset E) (δ : ℝ) : Prop :=
  ∀ x : E, ‖x‖ = 1 → ∃ y ∈ tests, dist x y ≤ δ

/-- Compactness supplies finite unit-vector tests independently of any map. -/
theorem exists_unitSphereNet [FiniteDimensional ℝ E] {δ : ℝ} (hδ : 0 < δ) :
    ∃ tests : Finset E,
      (∀ y ∈ tests, ‖y‖ = 1) ∧ UnitSphereNet tests δ := by
  classical
  obtain ⟨s, hsphere, hs, hcover⟩ := (isCompact_sphere (0 : E) 1).finite_cover_balls hδ
  refine ⟨hs.toFinset, ?_, ?_⟩
  · intro y hy
    have := hsphere (hs.mem_toFinset.mp hy)
    simpa [Metric.mem_sphere, dist_zero_right] using this
  · intro x hx
    have hxmem : x ∈ sphere (0 : E) 1 := by simpa [Metric.mem_sphere, dist_zero_right]
    obtain ⟨y, hy, hxy⟩ := Set.mem_iUnion₂.mp (hcover hxmem)
    exact ⟨y, hs.mem_toFinset.mpr hy, le_of_lt hxy⟩

/-- The central net argument: finite test bounds control the actual operator norm.
The estimate is valid in arbitrary real normed spaces once a net is given. -/
theorem opNorm_le_of_unitSphereNet (T : E →L[ℝ] F) {tests : Finset E} {δ B : ℝ}
    (hδnonneg : 0 ≤ δ) (hδ : δ < 1) (hB : 0 ≤ B)
    (hnet : UnitSphereNet tests δ) (htests : ∀ y ∈ tests, ‖T y‖ ≤ B) :
    ‖T‖ ≤ B / (1 - δ) := by
  have hunit : ‖T‖ ≤ B + δ * ‖T‖ := by
    apply ContinuousLinearMap.opNorm_le_of_unit_norm
      (add_nonneg hB (mul_nonneg hδnonneg (norm_nonneg T)))
    intro x hx
    obtain ⟨y, hy, hxy⟩ := hnet x hx
    calc
      ‖T x‖ = ‖T y + T (x - y)‖ := by rw [map_sub]; congr 1; abel
      _ ≤ ‖T y‖ + ‖T (x - y)‖ := norm_add_le _ _
      _ ≤ B + ‖T‖ * ‖x - y‖ := add_le_add (htests y hy) (T.le_opNorm _)
      _ ≤ B + ‖T‖ * δ := add_le_add (le_refl B)
        (mul_le_mul_of_nonneg_left (by simpa [dist_eq_norm] using hxy) (norm_nonneg T))
      _ = B + δ * ‖T‖ := by ring
  apply (le_div_iff₀ (by linarith : 0 < 1 - δ)).mpr
  nlinarith

/-- Homogeneous form of the finite-test certificate. -/
theorem norm_apply_le_of_unitSphereNet (T : E →L[ℝ] F) {tests : Finset E} {δ B : ℝ}
    (hδnonneg : 0 ≤ δ) (hδ : δ < 1) (hB : 0 ≤ B)
    (hnet : UnitSphereNet tests δ) (htests : ∀ y ∈ tests, ‖T y‖ ≤ B) (x : E) :
    ‖T x‖ ≤ (B / (1 - δ)) * ‖x‖ :=
  (T.le_opNorm x).trans (mul_le_mul_of_nonneg_right
    (opNorm_le_of_unitSphereNet T hδnonneg hδ hB hnet htests) (norm_nonneg x))

/-- The paper's choice of net radius gives exactly the prescribed loss κ. -/
theorem kappa_net_certificate (T : E →L[ℝ] F) {tests : Finset E} {κ c : ℝ}
    (hκ : 1 < κ) (hc : 0 ≤ c)
    (hnet : UnitSphereNet tests ((κ - 1) / (κ + 1)))
    (htests : ∀ y ∈ tests, ‖T y‖ ≤ (1 + (κ - 1) / (κ + 1)) * c) (x : E) :
    ‖T x‖ ≤ κ * c * ‖x‖ := by
  have hden : 0 < κ + 1 := by linarith
  have hδ0 : 0 ≤ (κ - 1) / (κ + 1) := div_nonneg (by linarith) (le_of_lt hden)
  have hδ1 : (κ - 1) / (κ + 1) < 1 := by
    apply (div_lt_one hden).mpr
    linarith
  have hidentity :
      ((1 + (κ - 1) / (κ + 1)) * c) / (1 - (κ - 1) / (κ + 1)) = κ * c := by
    field_simp
    ring
  simpa [hidentity] using norm_apply_le_of_unitSphereNet T hδ0 hδ1
    (mul_nonneg (by linarith) hc) hnet htests x

/-- The explicit appendix uses radius `1/n`, giving loss `(n+1)/(n-1)`. -/
theorem inverse_n_net_certificate (T : E →L[ℝ] F) {tests : Finset E} {n c : ℝ}
    (hn : 1 < n) (hc : 0 ≤ c) (hnet : UnitSphereNet tests (1 / n))
    (htests : ∀ y ∈ tests, ‖T y‖ ≤ (1 + 1 / n) * c) (x : E) :
    ‖T x‖ ≤ ((n + 1) / (n - 1)) * c * ‖x‖ := by
  have hn0 : 0 < n := by linarith
  have hδ0 : 0 ≤ 1 / n := by positivity
  have hδ1 : 1 / n < 1 := (div_lt_one hn0).mpr hn
  have hidentity : ((1 + 1 / n) * c) / (1 - 1 / n) = ((n + 1) / (n - 1)) * c := by
    field_simp
  have h := norm_apply_le_of_unitSphereNet T hδ0 hδ1
    (mul_nonneg (by linarith) hc) hnet htests x
  rw [hidentity] at h
  exact h

/-- Prescribed tests can be included before a map or random matrices are chosen. -/
theorem exists_unitSphereNet_containing [FiniteDimensional ℝ E]
    (seeds : Finset E) (hseeds : ∀ y ∈ seeds, ‖y‖ = 1) {δ : ℝ} (hδ : 0 < δ) :
    ∃ tests : Finset E, seeds ⊆ tests ∧
      (∀ y ∈ tests, ‖y‖ = 1) ∧ UnitSphereNet tests δ := by
  classical
  obtain ⟨tests, htests, hnet⟩ := exists_unitSphereNet (E := E) hδ
  refine ⟨seeds ∪ tests, Finset.subset_union_left, ?_, ?_⟩
  · intro y hy
    rcases Finset.mem_union.mp hy with h | h
    · exact hseeds y h
    · exact htests y h
  · intro x hx
    obtain ⟨y, hy, hxy⟩ := hnet x hx
    exact ⟨y, Finset.mem_union_right seeds hy, hxy⟩

/-- The appendix needs tests closed under negation, including its chosen test.
Symmetrizing a compactness net preserves its radius.  This theorem does not
claim the appendix's sharper volume estimate for a maximal separated net. -/
theorem exists_symmetric_unitSphereNet_containing [FiniteDimensional ℝ E]
    (seeds : Finset E) (hseeds : ∀ y ∈ seeds, ‖y‖ = 1) {δ : ℝ} (hδ : 0 < δ) :
    ∃ tests : Finset E, seeds ⊆ tests ∧
      (∀ y ∈ tests, ‖y‖ = 1) ∧
      (∀ y ∈ tests, -y ∈ tests) ∧ UnitSphereNet tests δ := by
  classical
  obtain ⟨tests, hseedsmem, htests, hnet⟩ :=
    exists_unitSphereNet_containing seeds hseeds hδ
  refine ⟨tests ∪ tests.image (- ·), hseedsmem.trans Finset.subset_union_left, ?_, ?_, ?_⟩
  · intro y hy
    rcases Finset.mem_union.mp hy with hy | hy
    · exact htests y hy
    · obtain ⟨z, hz, rfl⟩ := Finset.mem_image.mp hy
      simpa only [norm_neg] using htests z hz
  · intro y hy
    rcases Finset.mem_union.mp hy with hy | hy
    · exact Finset.mem_union_right _ (Finset.mem_image.mpr ⟨y, hy, rfl⟩)
    · obtain ⟨z, hz, rfl⟩ := Finset.mem_image.mp hy
      simpa only [neg_neg] using Finset.mem_union_left (tests.image (- ·)) hz
  · intro x hx
    obtain ⟨y, hy, hxy⟩ := hnet x hx
    exact ⟨y, Finset.mem_union_left _ hy, hxy⟩

/-- The finite union bound selects an actual sampled map satisfying every
test. Independence is unnecessary for this step. The failure probabilities
are the precise input supplied by convergence in probability. -/
theorem exists_norm_certificate_of_failure_sum_lt_one
    {Ω : Type*} [MeasurableSpace Ω] (μ : MeasureTheory.Measure Ω)
    [MeasureTheory.IsProbabilityMeasure μ] (T : Ω → E →L[ℝ] F)
    {tests : Finset E} {δ B : ℝ}
    (hδnonneg : 0 ≤ δ) (hδ : δ < 1) (hB : 0 ≤ B)
    (hnet : UnitSphereNet tests δ)
    (hfailure : ∑ y ∈ tests, μ {ω | B < ‖T ω y‖} < 1) :
    ∃ ω, ‖T ω‖ ≤ B / (1 - δ) ∧
      ∀ x : E, ‖T ω x‖ ≤ (B / (1 - δ)) * ‖x‖ := by
  classical
  let failures : Set Ω := ⋃ y ∈ tests, {ω | B < ‖T ω y‖}
  have hmeasure : μ failures < 1 :=
    (MeasureTheory.measure_biUnion_finset_le tests (fun y => {ω | B < ‖T ω y‖})).trans_lt hfailure
  have hproper : failures ≠ Set.univ := by
    intro heq
    rw [heq, MeasureTheory.measure_univ] at hmeasure
    exact lt_irrefl _ hmeasure
  obtain ⟨ω, hω⟩ := (Set.ne_univ_iff_exists_notMem failures).mp hproper
  have htests : ∀ y ∈ tests, ‖T ω y‖ ≤ B := by
    intro y hy
    apply le_of_not_gt
    intro hbad
    exact hω (Set.mem_iUnion₂.mpr ⟨y, hy, hbad⟩)
  exact ⟨ω, opNorm_le_of_unitSphereNet (T ω) hδnonneg hδ hB hnet htests,
    norm_apply_le_of_unitSphereNet (T ω) hδnonneg hδ hB hnet htests⟩

/-- Finitely many test failure probabilities tending to zero yield eventual
existence of a uniform certificate. The probability spaces may change with
the index, as the Haar unitary spaces do when their dimension increases. -/
theorem eventually_exists_norm_certificate_of_test_failures
    {ι : Type*} {Ω : ι → Type*} [∀ i, MeasurableSpace (Ω i)]
    {G : ι → Type*} [∀ i, NormedAddCommGroup (G i)] [∀ i, NormedSpace ℝ (G i)]
    (μ : (i : ι) → MeasureTheory.Measure (Ω i))
    [∀ i, MeasureTheory.IsProbabilityMeasure (μ i)]
    (T : (i : ι) → Ω i → E →L[ℝ] G i) (l : Filter ι)
    {tests : Finset E} {δ B : ℝ}
    (hδnonneg : 0 ≤ δ) (hδ : δ < 1) (hB : 0 ≤ B)
    (hnet : UnitSphereNet tests δ)
    (hfailure : ∀ y ∈ tests, Filter.Tendsto
      (fun i => μ i {ω | B < ‖T i ω y‖}) l (nhds 0)) :
    Filter.Eventually (fun i => ∃ ω, ‖T i ω‖ ≤ B / (1 - δ) ∧
      ∀ x : E, ‖T i ω x‖ ≤ (B / (1 - δ)) * ‖x‖) l := by
  have hsum : Filter.Tendsto
      (fun i => ∑ y ∈ tests, μ i {ω | B < ‖T i ω y‖}) l (nhds 0) := by
    simpa only [Finset.sum_const_zero] using
      tendsto_finset_sum tests (fun y hy => hfailure y hy)
  have hsmall := hsum.eventually_lt_const (by simp : (0 : ENNReal) < 1)
  exact hsmall.mono fun i hi =>
    exists_norm_certificate_of_failure_sum_lt_one (μ i) (T i)
      hδnonneg hδ hB hnet hi

/-- Norm convergence in probability on the fixed finite tests gives the
failure-probability premise of the preceding theorem. This is the tail
formulation of convergence in probability, valid for changing sample spaces. -/
theorem eventually_exists_norm_certificate_of_norm_convergence
    {ι : Type*} {Ω : ι → Type*} [∀ i, MeasurableSpace (Ω i)]
    {G : ι → Type*} [∀ i, NormedAddCommGroup (G i)] [∀ i, NormedSpace ℝ (G i)]
    (μ : (i : ι) → MeasureTheory.Measure (Ω i))
    [∀ i, MeasureTheory.IsProbabilityMeasure (μ i)]
    (T : (i : ι) → Ω i → E →L[ℝ] G i) (l : Filter ι)
    (limitNorm : E → ℝ) {tests : Finset E} {δ B c : ℝ}
    (hδnonneg : 0 ≤ δ) (hδ : δ < 1) (hB : 0 ≤ B) (hcB : c < B)
    (hnet : UnitSphereNet tests δ) (hlimit : ∀ y ∈ tests, limitNorm y ≤ c)
    (hconvergence : ∀ y ∈ tests, ∀ ε : ℝ, 0 < ε → Filter.Tendsto
      (fun i => μ i {ω | ε ≤ |‖T i ω y‖ - limitNorm y|}) l (nhds 0)) :
    Filter.Eventually (fun i => ∃ ω, ‖T i ω‖ ≤ B / (1 - δ) ∧
      ∀ x : E, ‖T i ω x‖ ≤ (B / (1 - δ)) * ‖x‖) l := by
  apply eventually_exists_norm_certificate_of_test_failures μ T l hδnonneg hδ hB hnet
  intro y hy
  have htail := hconvergence y hy (B - c) (sub_pos.mpr hcB)
  refine tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds htail
    (fun _ => zero_le _) ?_
  intro i
  apply MeasureTheory.measure_mono
  intro ω hω
  have hnorm : B < ‖T i ω y‖ := hω
  have hlim := hlimit y hy
  have habs := le_abs_self (‖T i ω y‖ - limitNorm y)
  change B - c ≤ |‖T i ω y‖ - limitNorm y|
  linarith

/-- The full finite-dimensional net argument in Lemma `cy`, conditional only
on the free unit-sphere bound and the stated strong-convergence input.
All nets, finite probability unions, random realizations, and the uniform
extension are constructed in the proof. -/
theorem eventually_exists_kappa_norm_certificate [FiniteDimensional ℝ E]
    {ι : Type*} {Ω : ι → Type*} [∀ i, MeasurableSpace (Ω i)]
    {G : ι → Type*} [∀ i, NormedAddCommGroup (G i)] [∀ i, NormedSpace ℝ (G i)]
    (μ : (i : ι) → MeasureTheory.Measure (Ω i))
    [∀ i, MeasureTheory.IsProbabilityMeasure (μ i)]
    (T : (i : ι) → Ω i → E →L[ℝ] G i) (l : Filter ι)
    (limitNorm : E → ℝ) {κ c : ℝ} (hκ : 1 < κ) (hc : 0 < c)
    (hlimit : ∀ y, ‖y‖ = 1 → limitNorm y ≤ c)
    (hconvergence : ∀ y, ‖y‖ = 1 → ∀ ε : ℝ, 0 < ε → Filter.Tendsto
      (fun i => μ i {ω | ε ≤ |‖T i ω y‖ - limitNorm y|}) l (nhds 0)) :
    Filter.Eventually (fun i => ∃ ω, ∀ x : E, ‖T i ω x‖ ≤ κ * c * ‖x‖) l := by
  have hden : 0 < κ + 1 := by linarith
  have hξpos : 0 < (κ - 1) / (κ + 1) := div_pos (by linarith) hden
  have hξlt : (κ - 1) / (κ + 1) < 1 := by
    apply (div_lt_one hden).mpr
    linarith
  obtain ⟨tests, hunit, hnet⟩ := exists_unitSphereNet (E := E) hξpos
  have hBpos : 0 < (1 + (κ - 1) / (κ + 1)) * c :=
    mul_pos (by linarith) hc
  have hcB : c < (1 + (κ - 1) / (κ + 1)) * c := by
    have := mul_pos hξpos hc
    nlinarith
  have hcertificate := eventually_exists_norm_certificate_of_norm_convergence μ T l limitNorm
    (le_of_lt hξpos) hξlt (le_of_lt hBpos) hcB hnet
    (fun y hy => hlimit y (hunit y hy))
    (fun y hy => hconvergence y (hunit y hy))
  have hidentity :
      ((1 + (κ - 1) / (κ + 1)) * c) / (1 - (κ - 1) / (κ + 1)) = κ * c := by
    field_simp
    ring
  exact hcertificate.mono fun i ⟨ω, _, hω⟩ => ⟨ω, by simpa only [hidentity] using hω⟩

/-- Division by the output dimension turns the unnormalized free-group bound
into the Hilbert--Schmidt norm certificate in Lemma `cy`. -/
theorem normalized_norm_bound (T : E →L[ℝ] F) {L a : ℝ} (hL : 0 < L) (ha : 0 ≤ a)
    (hT : ∀ x, ‖T x‖ ≤ Real.sqrt (L * a) * ‖x‖) (x : E) :
    ‖(L⁻¹ • T) x‖ ≤ Real.sqrt (a / L) * ‖x‖ := by
  have hnormalize : Real.sqrt (L * a) / L = Real.sqrt (a / L) := by
    calc
      Real.sqrt (L * a) / L = Real.sqrt a * (Real.sqrt L / L) := by
        rw [Real.sqrt_mul (le_of_lt hL)]
        ring
      _ = Real.sqrt a * (Real.sqrt L)⁻¹ := by rw [Real.sqrt_div_self]
      _ = Real.sqrt (a / L) := by rw [Real.sqrt_div ha]; ring
  calc
    ‖(L⁻¹ • T) x‖ = L⁻¹ * ‖T x‖ := by
      simp only [ContinuousLinearMap.smul_apply, norm_smul, Real.norm_eq_abs,
        abs_of_pos (inv_pos.mpr hL)]
    _ ≤ L⁻¹ * (Real.sqrt (L * a) * ‖x‖) :=
      mul_le_mul_of_nonneg_left (hT x) (le_of_lt (inv_pos.mpr hL))
    _ = (Real.sqrt (L * a) / L) * ‖x‖ := by ring
    _ = Real.sqrt (a / L) * ‖x‖ := by rw [hnormalize]

end FiniteNet

section Constants

/-- The Collins--Youn coefficient, with `q = (1+9/K)^n` and `L = K^n`. -/
noncomputable def freeNormConstant (L q : ℝ) : ℝ := Real.sqrt ((q - 1) / L)

theorem freeNormConstant_nonneg (L q : ℝ) : 0 ≤ freeNormConstant L q :=
  Real.sqrt_nonneg _

theorem freeNormConstant_pos {L q : ℝ} (hL : 0 < L) (hq : 1 < q) :
    0 < freeNormConstant L q :=
  Real.sqrt_pos.mpr (div_pos (sub_pos.mpr hq) hL)

theorem freeNormConstant_sq {L q : ℝ} (hL : 0 < L) (hq : 1 ≤ q) :
    freeNormConstant L q ^ 2 = (q - 1) / L := by
  exact Real.sq_sqrt (div_nonneg (sub_nonneg.mpr hq) (le_of_lt hL))

/-- Scalar identity used when substituting the norm certificate into purity. -/
theorem purity_factor_identity {L q κ : ℝ} (hL : 0 < L) (hq : 1 ≤ q) :
    1 + L * (κ * freeNormConstant L q) ^ 2 = κ ^ 2 * q + 1 - κ ^ 2 := by
  rw [mul_pow, freeNormConstant_sq hL hq]
  field_simp
  ring

/-- For `κ ≥ 1` the negative correction may be dropped. -/
theorem purity_factor_le {L q κ : ℝ} (hL : 0 < L) (hq : 1 ≤ q) (hκ : 1 ≤ κ) :
    1 + L * (κ * freeNormConstant L q) ^ 2 ≤ κ ^ 2 * q := by
  rw [purity_factor_identity hL hq]
  nlinarith

/-- The exact constant `c_n` used throughout the manuscript. -/
noncomputable def collinsYounConstant (K n : ℕ) : ℝ :=
  freeNormConstant ((K : ℝ) ^ n) ((1 + 9 / (K : ℝ)) ^ n)

theorem collinsYounConstant_pos {K n : ℕ} (hK : 2 ≤ K) (hn : 1 ≤ n) :
    0 < collinsYounConstant K n := by
  have hKr : (2 : ℝ) ≤ K := by exact_mod_cast hK
  have hKpos : (0 : ℝ) < K := by linarith
  apply freeNormConstant_pos (pow_pos hKpos n)
  apply one_lt_pow₀
  · have := div_pos (by norm_num : (0 : ℝ) < 9) hKpos
    linarith
  · exact Nat.ne_of_gt (Nat.lt_of_lt_of_le Nat.zero_lt_one hn)

theorem collinsYounConstant_sq {K n : ℕ} (hK : 2 ≤ K) :
    collinsYounConstant K n ^ 2 = ((1 + 9 / (K : ℝ)) ^ n - 1) / (K : ℝ) ^ n := by
  have hKr : (2 : ℝ) ≤ K := by exact_mod_cast hK
  have hKpos : (0 : ℝ) < K := by linarith
  apply freeNormConstant_sq (pow_pos hKpos n)
  apply one_le_pow₀
  have := div_nonneg (by norm_num : (0 : ℝ) ≤ 9) (le_of_lt hKpos)
  linarith

/-- Specialized scalar purity estimate for the exact channel-output dimension. -/
theorem collinsYoun_purity_factor_le {K n : ℕ} {κ : ℝ} (hK : 2 ≤ K) (hκ : 1 ≤ κ) :
    1 + (K : ℝ) ^ n * (κ * collinsYounConstant K n) ^ 2 ≤
      κ ^ 2 * (1 + 9 / (K : ℝ)) ^ n := by
  have hKr : (2 : ℝ) ≤ K := by exact_mod_cast hK
  have hKpos : (0 : ℝ) < K := by linarith
  apply purity_factor_le (pow_pos hKpos n) _ hκ
  apply one_le_pow₀
  have := div_nonneg (by norm_num : (0 : ℝ) ≤ 9) (le_of_lt hKpos)
  linarith

end Constants

end Nonadditivity
