import Erdos1135.ND.Discrepancy.A5ReferenceRealLogBlock
import Erdos1135.Tao.Section3.AmbientPartialTrace

/-!
# A5 split-rate Section 3 facade

This leaf exposes the checked real harmonic escape and ordered passage rows
in the exact canonical-window syntax consumed by the Section 3 recurrence.
One cutoff, chosen before every trace parameter, patches the finite prefix by
the universal probability and full-L1 caps `1` and `2`.  The power escape and
logarithmic passage rates remain separate functions.
-/

namespace Erdos1135
namespace ND

open Filter
open scoped BigOperators Topology

noncomputable section

/-- The canonical Tao no-hit wrapper and the ND odd-block no-hit probability
are definitionally the same after exposing the shared endpoints.  The two
positive-mass proofs are identified only by proof irrelevance.
-/
theorem syracuseNoHitRealWindowProb_taoNy_eq_pmfProb_logOddBlockPMF
    (x y : Real)
    (hmassTao : 0 < Tao.logFinsetMass
      (Tao.oddLogWindow (Tao.taoNyLo y)
        (Tao.taoNyHi y Tao.taoAlpha)))
    (hmassND : 0 < Tao.logFinsetMass (oddBlock y)) :
    Tao.syracuseNoHitRealWindowProb x
        (Tao.taoNyLo y) (Tao.taoNyHi y Tao.taoAlpha) hmassTao =
      Tao.pmfProb (logOddBlockPMF y hmassND)
        {N | ¬ Tao.syracuseHitsAtMostReal N.1 x} := by
  unfold Tao.syracuseNoHitRealWindowProb Tao.syracuseNoHitAtMostReal
    Tao.oddLogWindowPMF logOddBlockPMF oddBlock Tao.taoNyOddWindow
  rfl

/-- The canonical Tao real-floor passage distance and the ND logarithmic
passage distance are definitionally the same on shared endpoint windows.
-/
theorem syracusePassRealFloorWindowTV_taoNy_eq_taoTV_logPassLaw
    (x y1 y2 : Real) (hx : 1 <= x)
    (hmassTao1 : 0 < Tao.logFinsetMass
      (Tao.oddLogWindow (Tao.taoNyLo y1)
        (Tao.taoNyHi y1 Tao.taoAlpha)))
    (hmassTao2 : 0 < Tao.logFinsetMass
      (Tao.oddLogWindow (Tao.taoNyLo y2)
        (Tao.taoNyHi y2 Tao.taoAlpha)))
    (hmassND1 : 0 < Tao.logFinsetMass (oddBlock y1))
    (hmassND2 : 0 < Tao.logFinsetMass (oddBlock y2)) :
    Tao.syracusePassRealFloorWindowTV x
        (Tao.taoNyLo y1) (Tao.taoNyHi y1 Tao.taoAlpha)
        (Tao.taoNyLo y2) (Tao.taoNyHi y2 Tao.taoAlpha)
        hx hmassTao1 hmassTao2 =
      Tao.taoTV (logPassLaw x y1 hx hmassND1)
        (logPassLaw x y2 hx hmassND2) := by
  unfold Tao.syracusePassRealFloorWindowTV
    Tao.syracusePassLocationRealFloorLaw
    Tao.syracusePassLocationRealFloorOrOne
    Tao.syracusePassLocationOrOne logPassLaw logOddBlockPMF
    passLocationOrOne oddBlock Tao.taoNyOddWindow Tao.oddLogWindowPMF
  rfl

/-- The uncapped genuine harmonic no-hit error at natural threshold `B`. -/
noncomputable def ndA5ReferenceSection3RawNoHitError (B : Nat) : Real :=
  10 * (B : Real) ^ (-(1 / 32000 : Real)) +
    96000 / ((B : Real) * Real.log (B : Real))

/-- The uncapped ordered harmonic passage error at natural threshold `B`. -/
noncomputable def ndA5ReferenceSection3RawPassTVError
    (d : Real) (B : Nat) : Real :=
  32 * ndA5ReferenceInteriorScalarRate B d +
    4 * (96000 / ((B : Real) * Real.log (B : Real)))

/-- All-threshold harmonic no-hit error.  Only the finite prefix is replaced
by the universal probability cap `1`.
-/
noncomputable def ndA5ReferenceSection3NoHitError
    (B0 B : Nat) : Real :=
  if B0 <= B then
    ndA5ReferenceSection3RawNoHitError B
  else 1

/-- All-threshold ordered harmonic passage error in project full L1.  Only
the finite prefix is replaced by the universal cap `2`.
-/
noncomputable def ndA5ReferenceSection3PassTVError
    (B0 : Nat) (d : Real) (B : Nat) : Real :=
  if B0 <= B then
    ndA5ReferenceSection3RawPassTVError d B
  else 2

/-- Verbatim all-threshold bounds premise consumed by
`Tao.taoSection3Forward_allPartial_of_realRateBounds`.
-/
def NDA5ReferenceSection3Bounds
    (errNoHit errPassTV : Nat -> Real) : Prop :=
  ∀ x lo1 hi1 lo2 hi2,
    (hx : 1 <= x) ->
      Tao.TaoProp111RealWindowPair x lo1 hi1 lo2 hi2 ->
        ∀ (hmass1 : 0 < Tao.logFinsetMass
            (Tao.oddLogWindow lo1 hi1))
          (hmass2 : 0 < Tao.logFinsetMass
            (Tao.oddLogWindow lo2 hi2)),
          Tao.syracuseNoHitRealWindowProb x lo1 hi1 hmass1 <=
                errNoHit (Nat.floor x) ∧
            Tao.syracuseNoHitRealWindowProb x lo2 hi2 hmass2 <=
                errNoHit (Nat.floor x) ∧
              Tao.syracusePassRealFloorWindowTV
                  x lo1 hi1 lo2 hi2 hx hmass1 hmass2 <=
                errPassTV (Nat.floor x)

/-- Both capped errors are globally nonnegative once their common cutoff is
at least two.
-/
theorem ndA5ReferenceSection3Errors_nonneg
    {B0 : Nat} (hB0 : 2 <= B0) (d : Real) (B : Nat) :
    0 <= ndA5ReferenceSection3NoHitError B0 B ∧
      0 <= ndA5ReferenceSection3PassTVError B0 d B := by
  by_cases hlarge : B0 <= B
  · have hB : 2 <= B := hB0.trans hlarge
    have hBcast : (1 : Real) < (B : Real) := by exact_mod_cast hB
    have hBpos : (0 : Real) < (B : Real) := zero_lt_one.trans hBcast
    have hlog : 0 < Real.log (B : Real) := Real.log_pos hBcast
    have hdelta :
        0 <= 96000 / ((B : Real) * Real.log (B : Real)) :=
      (div_pos (by norm_num) (mul_pos hBpos hlog)).le
    rw [ndA5ReferenceSection3NoHitError, if_pos hlarge,
      ndA5ReferenceSection3PassTVError, if_pos hlarge]
    unfold ndA5ReferenceSection3RawNoHitError
      ndA5ReferenceSection3RawPassTVError
    constructor
    · exact add_nonneg
        (mul_nonneg (by norm_num)
          (Real.rpow_nonneg (Nat.cast_nonneg B) _))
        hdelta
    · exact add_nonneg
        (mul_nonneg (by norm_num) (Real.rpow_nonneg hlog.le _))
        (mul_nonneg (by norm_num) hdelta)
  · simp [ndA5ReferenceSection3NoHitError,
      ndA5ReferenceSection3PassTVError, hlarge]

/-- The two canonical Proposition 1.11 real windows inherit the genuine
harmonic escape row.  This adapter has no `PhaseGap` or discrepancy exponent.
-/
theorem eventually_taoProp111RealWindowPair_harmonicNoHit_le :
    ∀ᶠ x : Real in atTop,
      ∀ lo1 hi1 lo2 hi2 : Nat,
        (hx : 1 <= x) ->
        Tao.TaoProp111RealWindowPair x lo1 hi1 lo2 hi2 ->
          ∀ (hmass1 : 0 < Tao.logFinsetMass
              (Tao.oddLogWindow lo1 hi1))
            (hmass2 : 0 < Tao.logFinsetMass
              (Tao.oddLogWindow lo2 hi2)),
            let B := Nat.floor x
            Tao.syracuseNoHitRealWindowProb x lo1 hi1 hmass1 <=
                ndA5ReferenceSection3RawNoHitError B ∧
              Tao.syracuseNoHitRealWindowProb x lo2 hi2 hmass2 <=
                ndA5ReferenceSection3RawNoHitError B := by
  filter_upwards
      [eventually_pmfProb_logOddBlock_transportSourceY_noHit_le]
      with x hescape
  intro lo1 hi1 lo2 hi2 hx hpair hmass1 hmass2
  rcases hpair with ⟨rfl, rfl, rfl, rfl⟩
  have hAlpha : 0 < Tao.logFinsetMass
      (oddBlock (transportSourceY x .alpha)) := by
    simpa [oddBlock, Tao.taoNyOddWindow, transportSourceY,
      Tao.taoProp111RealY1, alpha] using hmass1
  have hAlphaSq : 0 < Tao.logFinsetMass
      (oddBlock (transportSourceY x .alphaSq)) := by
    simpa [oddBlock, Tao.taoNyOddWindow, transportSourceY,
      Tao.taoProp111RealY2, alpha] using hmass2
  have hno1 := hescape hx .alpha hAlpha
  have hno2 := hescape hx .alphaSq hAlphaSq
  dsimp only
  constructor
  · simpa [ndA5ReferenceSection3RawNoHitError,
      Tao.syracuseNoHitRealWindowProb, Tao.oddLogWindowPMF,
      Tao.syracuseNoHitAtMostReal, logOddBlockPMF, oddBlock,
      Tao.taoNyOddWindow, transportSourceY, Tao.taoProp111RealY1,
      alpha] using hno1
  · simpa [ndA5ReferenceSection3RawNoHitError,
      Tao.syracuseNoHitRealWindowProb, Tao.oddLogWindowPMF,
      Tao.syracuseNoHitAtMostReal, logOddBlockPMF, oddBlock,
      Tao.taoNyOddWindow, transportSourceY, Tao.taoProp111RealY2,
      alpha] using hno2

/-- The canonical Proposition 1.11 real window pair inherits the ordered
harmonic full-L1 row, with no uniform error and no additional Hahn factor.
-/
theorem eventually_taoProp111RealWindowPair_harmonicPassTV_le
    {c kappa d : Real}
    (hPhase : PhaseGap c kappa)
    (hd : 0 < d) (hd20 : d < 1 / 20)
    (hdk : d < 1 / (2 * kappa)) :
    ∀ᶠ x : Real in atTop,
      ∀ lo1 hi1 lo2 hi2 : Nat,
        (hx : 1 <= x) ->
        Tao.TaoProp111RealWindowPair x lo1 hi1 lo2 hi2 ->
          ∀ (hmass1 : 0 < Tao.logFinsetMass
              (Tao.oddLogWindow lo1 hi1))
            (hmass2 : 0 < Tao.logFinsetMass
              (Tao.oddLogWindow lo2 hi2)),
            let B := Nat.floor x
            Tao.syracusePassRealFloorWindowTV
                x lo1 hi1 lo2 hi2 hx hmass1 hmass2 <=
              ndA5ReferenceSection3RawPassTVError d B := by
  filter_upwards
      [eventually_ndA5RealCrossHarmonicPassTV_le hPhase hd hd20 hdk]
      with x hcross
  intro lo1 hi1 lo2 hi2 hx hpair hmass1 hmass2
  rcases hpair with ⟨rfl, rfl, rfl, rfl⟩
  have hAlpha : 0 < Tao.logFinsetMass
      (oddBlock (transportSourceY x .alpha)) := by
    simpa [oddBlock, Tao.taoNyOddWindow, transportSourceY,
      Tao.taoProp111RealY1, alpha] using hmass1
  have hAlphaSq : 0 < Tao.logFinsetMass
      (oddBlock (transportSourceY x .alphaSq)) := by
    simpa [oddBlock, Tao.taoNyOddWindow, transportSourceY,
      Tao.taoProp111RealY2, alpha] using hmass2
  have htv := hcross hx hAlpha hAlphaSq
  dsimp only
  simpa [ndA5ReferenceSection3RawPassTVError,
    Tao.syracusePassRealFloorWindowTV,
    Tao.syracusePassLocationRealFloorLaw,
    Tao.syracusePassLocationRealFloorOrOne,
    Tao.syracusePassLocationOrOne, logPassLaw, logOddBlockPMF,
    passLocationOrOne, oddBlock, Tao.taoNyOddWindow,
    Tao.oddLogWindowPMF, transportSourceY,
    Tao.taoProp111RealY1, Tao.taoProp111RealY2, alpha] using htv

/-- One cutoff selected before every real threshold supplies the exact
all-threshold packet consumed by the checked Section 3 recurrence.
-/
theorem exists_ndA5ReferenceSection3AllThresholdBounds
    {c kappa d : Real}
    (hPhase : PhaseGap c kappa)
    (hd : 0 < d) (hd20 : d < 1 / 20)
    (hdk : d < 1 / (2 * kappa)) :
    ∃ B0 : Nat, 2 <= B0 ∧
      (∀ B : Nat,
        0 <= ndA5ReferenceSection3NoHitError B0 B ∧
          0 <= ndA5ReferenceSection3PassTVError B0 d B) ∧
      (∀ᶠ B : Nat in atTop,
        ndA5ReferenceSection3NoHitError B0 B =
              ndA5ReferenceSection3RawNoHitError B ∧
          ndA5ReferenceSection3PassTVError B0 d B =
            ndA5ReferenceSection3RawPassTVError d B) ∧
      NDA5ReferenceSection3Bounds
        (ndA5ReferenceSection3NoHitError B0)
        (ndA5ReferenceSection3PassTVError B0 d) := by
  have hraw :
      ∀ᶠ x : Real in atTop,
        (∀ lo1 hi1 lo2 hi2 : Nat,
          (hx : 1 <= x) ->
          Tao.TaoProp111RealWindowPair x lo1 hi1 lo2 hi2 ->
            ∀ (hmass1 : 0 < Tao.logFinsetMass
                (Tao.oddLogWindow lo1 hi1))
              (hmass2 : 0 < Tao.logFinsetMass
                (Tao.oddLogWindow lo2 hi2)),
              let B := Nat.floor x
              Tao.syracuseNoHitRealWindowProb x lo1 hi1 hmass1 <=
                  ndA5ReferenceSection3RawNoHitError B ∧
                Tao.syracuseNoHitRealWindowProb x lo2 hi2 hmass2 <=
                  ndA5ReferenceSection3RawNoHitError B) ∧
        (∀ lo1 hi1 lo2 hi2 : Nat,
          (hx : 1 <= x) ->
          Tao.TaoProp111RealWindowPair x lo1 hi1 lo2 hi2 ->
            ∀ (hmass1 : 0 < Tao.logFinsetMass
                (Tao.oddLogWindow lo1 hi1))
              (hmass2 : 0 < Tao.logFinsetMass
                (Tao.oddLogWindow lo2 hi2)),
              let B := Nat.floor x
              Tao.syracusePassRealFloorWindowTV
                  x lo1 hi1 lo2 hi2 hx hmass1 hmass2 <=
                ndA5ReferenceSection3RawPassTVError d B) :=
    eventually_taoProp111RealWindowPair_harmonicNoHit_le.and
      (eventually_taoProp111RealWindowPair_harmonicPassTV_le
        hPhase hd hd20 hdk)
  rcases (eventually_atTop.1 hraw) with ⟨x0, hx0⟩
  let B0 : Nat := max 2 (Nat.ceil x0)
  have hB0 : 2 <= B0 := le_max_left 2 (Nat.ceil x0)
  refine ⟨B0, hB0,
    (fun B => ndA5ReferenceSection3Errors_nonneg hB0 d B), ?_, ?_⟩
  · filter_upwards [eventually_ge_atTop B0] with B hlarge
    simp [ndA5ReferenceSection3NoHitError,
      ndA5ReferenceSection3PassTVError, hlarge]
  · intro x lo1 hi1 lo2 hi2 hx hpair hmass1 hmass2
    by_cases hlarge : B0 <= Nat.floor x
    · have hx0x : x0 <= x := by
        calc
          x0 <= ((Nat.ceil x0 : Nat) : Real) := Nat.le_ceil x0
          _ <= (B0 : Real) := by
            exact_mod_cast (le_max_right 2 (Nat.ceil x0))
          _ <= ((Nat.floor x : Nat) : Real) := by exact_mod_cast hlarge
          _ <= x := Nat.floor_le (zero_le_one.trans hx)
      have hpacket := hx0 x hx0x
      have hno := hpacket.1 lo1 hi1 lo2 hi2 hx hpair hmass1 hmass2
      have htv := hpacket.2 lo1 hi1 lo2 hi2 hx hpair hmass1 hmass2
      simpa [ndA5ReferenceSection3NoHitError,
        ndA5ReferenceSection3PassTVError, hlarge] using
        (show
          Tao.syracuseNoHitRealWindowProb x lo1 hi1 hmass1 <=
                ndA5ReferenceSection3RawNoHitError (Nat.floor x) ∧
            Tao.syracuseNoHitRealWindowProb x lo2 hi2 hmass2 <=
                ndA5ReferenceSection3RawNoHitError (Nat.floor x) ∧
            Tao.syracusePassRealFloorWindowTV
                x lo1 hi1 lo2 hi2 hx hmass1 hmass2 <=
              ndA5ReferenceSection3RawPassTVError d (Nat.floor x) from
          ⟨hno.1, hno.2, htv⟩)
    · rw [show ndA5ReferenceSection3NoHitError B0 (Nat.floor x) = 1 by
          simp [ndA5ReferenceSection3NoHitError, hlarge],
        show ndA5ReferenceSection3PassTVError B0 d (Nat.floor x) = 2 by
          simp [ndA5ReferenceSection3PassTVError, hlarge]]
      have hx0nonneg : 0 <= x := zero_le_one.trans hx
      constructor
      · rw [Tao.syracuseNoHitRealWindowProb_eq_floor hx0nonneg]
        exact Tao.syracuseNoHitWindowProb_le_one _ _ _ hmass1
      constructor
      · rw [Tao.syracuseNoHitRealWindowProb_eq_floor hx0nonneg]
        exact Tao.syracuseNoHitWindowProb_le_one _ _ _ hmass2
      · unfold Tao.syracusePassRealFloorWindowTV
        exact Tao.taoTV_le_two _ _

/-- The split all-threshold packet directly feeds every bounded prefix of the
checked seed-forward Section 3 recurrence.  The cutoff is selected before the
fixed target, seed, or trace length.
-/
theorem exists_ndA5ReferenceSection3ForwardAllPartial
    {c kappa d : Real}
    (hPhase : PhaseGap c kappa)
    (hd : 0 < d) (hd20 : d < 1 / 20)
    (hdk : d < 1 / (2 * kappa)) :
    ∃ B0 : Nat, 2 <= B0 ∧
      (∀ B : Nat,
        0 <= ndA5ReferenceSection3NoHitError B0 B ∧
          0 <= ndA5ReferenceSection3PassTVError B0 d B) ∧
      ∀ {N0 Jmax : Nat} {y : Real},
        1 <= N0 -> 1 <= y ->
          (∀ m : Nat, m <= Jmax ->
            0 < Tao.logFinsetMass (Tao.taoSection3ForwardWindow y m)) ->
          Tao.taoSection3ForwardScale y 1 <= (N0 : Real) ->
            ∀ J : Nat, J <= Jmax ->
              1 - (∑ m ∈ Finset.range J,
                Tao.taoSection3ForwardStepError
                  (ndA5ReferenceSection3NoHitError B0)
                  (ndA5ReferenceSection3PassTVError B0 d) y m) <=
                Tao.taoSection3ForwardGoodProb N0 y J := by
  rcases exists_ndA5ReferenceSection3AllThresholdBounds
      hPhase hd hd20 hdk with
    ⟨B0, hB0, hnonneg, _hraw, hbounds⟩
  refine ⟨B0, hB0, hnonneg, ?_⟩
  intro N0 Jmax y hN0 hy hmass hseed J hJ
  exact Tao.taoSection3Forward_allPartial_of_realRateBounds
    hbounds hN0 hy hmass hseed J hJ

end
end ND
end Erdos1135
