import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics
import Erdos1135.ND.Discrepancy.A5ReferenceSection3RealRate
import Erdos1135.Tao.Section3.AmbientGeometricBudget

/-!
# Fixed-exponent A5 Section 3 geometric budget

This leaf absorbs the genuine power escape rate into the symbolic
logarithmic passage rate at one scalar cutoff.  It then sums the already
combined one-step error with coefficient `960084`; the inherited
common-exponent theorem and its factor two are not used.
-/

namespace Erdos1135
namespace ND

open Filter
open scoped Topology BigOperators

noncomputable section

/-- Every fixed logarithmic power eventually dominates the genuine
`x^(-1/32000)` escape rate.  No comparison between `d` and `1/32000` is
required.
-/
theorem eventually_rpow_neg_one_div_32000_le_log_rpow_neg
    (d : Real) :
    ∀ᶠ x : Real in atTop,
      x ^ (-(1 / 32000 : Real)) <= (Real.log x) ^ (-d) := by
  have hdecay :
      Tendsto
        (fun L : Real =>
          Real.rpow L d * Real.exp (-(1 / 32000 : Real) * L))
        atTop (nhds 0) :=
    tendsto_rpow_mul_exp_neg_mul_atTop_nhds_zero
      d (1 / 32000 : Real) (by norm_num)
  have hsmall :
      ∀ᶠ x : Real in atTop,
        Real.rpow (Real.log x) d *
            Real.exp (-(1 / 32000 : Real) * Real.log x) <= 1 :=
    (hdecay.comp Real.tendsto_log_atTop).eventually_le_const zero_lt_one
  filter_upwards
      [Real.tendsto_log_atTop.eventually_ge_atTop (1 : Real),
        hsmall, eventually_ge_atTop (1 : Real)]
      with x hlogOne hsmallX hxOne
  let L : Real := Real.log x
  have hxpos : 0 < x := zero_lt_one.trans_le hxOne
  have hLpos : 0 < L := zero_lt_one.trans_le hlogOne
  have hpowPos : 0 < Real.rpow L d := Real.rpow_pos_of_pos hLpos _
  have hscaled :
      Real.exp (-(1 / 32000 : Real) * L) * Real.rpow L d <= 1 := by
    calc
      Real.exp (-(1 / 32000 : Real) * L) * Real.rpow L d =
          Real.rpow L d * Real.exp (-(1 / 32000 : Real) * L) := by ring
      _ <= 1 := by simpa only [L] using hsmallX
  have hdiv :
      Real.exp (-(1 / 32000 : Real) * L) <= 1 / Real.rpow L d :=
    (le_div_iff₀ hpowPos).2 hscaled
  have hneg : Real.rpow L (-d) = (Real.rpow L d)⁻¹ := by
    simpa only using Real.rpow_neg hLpos.le d
  calc
    x ^ (-(1 / 32000 : Real)) =
        Real.exp (-(1 / 32000 : Real) * L) := by
      rw [Real.rpow_def_of_pos hxpos]
      congr 1
      dsimp only [L]
      ring
    _ <= 1 / Real.rpow L d := hdiv
    _ = Real.rpow L (-d) := by
      rw [hneg]
      simp only [one_div]
    _ = (Real.log x) ^ (-d) := by rfl

/-- The two separately checked facade errors combine to one actual-real
one-step rate.  The coefficient is the literal sum
`768064 + 192020 = 960084`.
-/
theorem eventually_ndA5ReferenceSection3StepError_le_real_log_power
    (B0 : Nat) {d : Real}
    (hd : 0 < d) (hd20 : d < 1 / 20) :
    ∀ᶠ q : Real in atTop,
      Tao.taoSection3AmbientStepError
          (ndA5ReferenceSection3NoHitError B0)
          (ndA5ReferenceSection3PassTVError B0 d) q <=
        960084 * (Real.log q) ^ (-d) := by
  filter_upwards
      [eventually_ndA5ReferenceSection3NoHitError_floor_le_real_power B0,
        eventually_ndA5ReferenceSection3PassTVError_floor_le_real_log_power
          B0 hd hd20,
        eventually_rpow_neg_one_div_32000_le_log_rpow_neg d]
      with q hNoHit hPass hAbsorb
  unfold Tao.taoSection3AmbientStepError
  calc
    ndA5ReferenceSection3PassTVError B0 d (Nat.floor q) +
          ndA5ReferenceSection3NoHitError B0 (Nat.floor q) <=
        768064 * (Real.log q) ^ (-d) +
          192020 * q ^ (-(1 / 32000 : Real)) :=
      add_le_add hPass hNoHit
    _ <= 768064 * (Real.log q) ^ (-d) +
          192020 * (Real.log q) ^ (-d) :=
      add_le_add le_rfl
        (mul_le_mul_of_nonneg_left hAbsorb (by norm_num))
    _ = 960084 * (Real.log q) ^ (-d) := by ring

/-- A combined logarithmic one-step estimate costs one geometric multiple of
its first term.  Unlike the inherited common-rate theorem, this lemma does
not pay a factor two for bounding the two error components separately.
-/
theorem ndSection3Forward_error_sum_le_stepLogRate
    {errNoHit errTV : Nat -> Real} {C d y : Real}
    (hC : 0 <= C) (hd : 0 < d) (hy : 1 <= y)
    (hq0 : Real.exp 1 < Tao.taoSection3ForwardThreshold y 0)
    (J : Nat)
    (hrate : ∀ m < J,
      Tao.taoSection3ForwardStepError errNoHit errTV y m <=
        C * (Real.log
          (Tao.taoSection3ForwardThreshold y m)) ^ (-d)) :
    (∑ m ∈ Finset.range J,
      Tao.taoSection3ForwardStepError errNoHit errTV y m) <=
      (C * (Real.log
        (Tao.taoSection3ForwardThreshold y 0)) ^ (-d)) /
        (1 - Tao.taoAlpha ^ (-d)) := by
  have hratioNonneg : 0 <= Tao.taoAlpha ^ (-d) :=
    Real.rpow_nonneg Tao.taoAlpha_pos.le _
  have hratioLt : Tao.taoAlpha ^ (-d) < 1 :=
    Real.rpow_lt_one_of_one_lt_of_neg Tao.taoAlpha_one_lt
      (neg_lt_zero.mpr hd)
  have hlog0pos :
      0 < Real.log (Tao.taoSection3ForwardThreshold y 0) := by
    have hq0pos : 0 < Tao.taoSection3ForwardThreshold y 0 :=
      (Real.exp_pos 1).trans hq0
    exact zero_lt_one.trans ((Real.lt_log_iff_exp_lt hq0pos).2 hq0)
  have hcoefficient :
      0 <= C *
        (Real.log (Tao.taoSection3ForwardThreshold y 0)) ^ (-d) := by
    exact mul_nonneg hC (Real.rpow_nonneg hlog0pos.le _)
  calc
    (∑ m ∈ Finset.range J,
        Tao.taoSection3ForwardStepError errNoHit errTV y m) <=
        ∑ m ∈ Finset.range J,
          (C *
            (Real.log (Tao.taoSection3ForwardThreshold y 0)) ^ (-d)) *
              (Tao.taoAlpha ^ (-d)) ^ m := by
      apply Finset.sum_le_sum
      intro m hm
      have hmJ : m < J := Finset.mem_range.mp hm
      calc
        Tao.taoSection3ForwardStepError errNoHit errTV y m <=
            C * (Real.log
              (Tao.taoSection3ForwardThreshold y m)) ^ (-d) :=
          hrate m hmJ
        _ = (C *
              (Real.log
                (Tao.taoSection3ForwardThreshold y 0)) ^ (-d)) *
                (Tao.taoAlpha ^ (-d)) ^ m := by
          rw [Tao.taoSection3Forward_logRate_eq_geometric hy]
          ring
    _ = (C *
          (Real.log (Tao.taoSection3ForwardThreshold y 0)) ^ (-d)) *
          (∑ m ∈ Finset.range J, (Tao.taoAlpha ^ (-d)) ^ m) := by
      rw [Finset.mul_sum]
    _ <= (C *
          (Real.log (Tao.taoSection3ForwardThreshold y 0)) ^ (-d)) *
          (1 / (1 - Tao.taoAlpha ^ (-d))) := by
      apply mul_le_mul_of_nonneg_left _ hcoefficient
      simpa only [Finset.range_eq_Ico, pow_zero, one_div] using
        (geom_sum_Ico_le_of_lt_one (m := 0) (n := J)
          hratioNonneg hratioLt)
    _ = (C *
          (Real.log (Tao.taoSection3ForwardThreshold y 0)) ^ (-d)) /
            (1 - Tao.taoAlpha ^ (-d)) := by
      simp only [one_mul, div_eq_mul_inv]

/-- One scalar cutoff, selected before every source seed and trace length,
controls the full forward error sum with the fixed exponent `d`.
-/
theorem exists_ndA5ReferenceSection3ForwardGeometricCutoff
    (B0 : Nat) {d : Real}
    (hd : 0 < d) (hd20 : d < 1 / 20) :
    ∃ Qstep : Real, Real.exp 1 < Qstep ∧
      ∀ {y : Real}, 1 <= y ->
        Qstep <= Tao.taoSection3ForwardThreshold y 0 ->
        ∀ J : Nat,
          (∑ m ∈ Finset.range J,
            Tao.taoSection3ForwardStepError
              (ndA5ReferenceSection3NoHitError B0)
              (ndA5ReferenceSection3PassTVError B0 d) y m) <=
            (960084 * (Real.log
              (Tao.taoSection3ForwardThreshold y 0)) ^ (-d)) /
              (1 - Tao.taoAlpha ^ (-d)) := by
  rcases eventually_atTop.1
      (eventually_ndA5ReferenceSection3StepError_le_real_log_power
        B0 hd hd20) with
    ⟨Qrate, hQrate⟩
  let Qstep : Real := max Qrate (Real.exp 1 + 1)
  have hExp : Real.exp 1 < Qstep := by
    calc
      Real.exp 1 < Real.exp 1 + 1 := lt_add_of_pos_right _ zero_lt_one
      _ <= Qstep := le_max_right _ _
  refine ⟨Qstep, hExp, ?_⟩
  intro y hy hq0 J
  apply ndSection3Forward_error_sum_le_stepLogRate
    (C := 960084) (d := d) (y := y) (by norm_num) hd hy
    (hExp.trans_le hq0) J
  intro m _hm
  unfold Tao.taoSection3ForwardStepError
  apply hQrate
  calc
    Qrate <= Qstep := le_max_left _ _
    _ <= Tao.taoSection3ForwardThreshold y 0 := hq0
    _ <= Tao.taoSection3ForwardThreshold y m :=
      Tao.taoSection3ForwardThreshold_monotone hy (Nat.zero_le m)

/-- The facade recurrence premise and the fixed-`d` geometric cutoff share
one literal `B0`.  Both witnesses are chosen before every seed and trace
parameter.
-/
theorem exists_ndA5ReferenceSection3ForwardGeometricPacket
    {c kappa d : Real} (hPhase : PhaseGap c kappa)
    (hd : 0 < d) (hd20 : d < 1 / 20)
    (hdk : d < 1 / (2 * kappa)) :
    ∃ B0 : Nat, ∃ Qstep : Real,
      2 <= B0 ∧ Real.exp 1 < Qstep ∧
        (∀ B : Nat,
          0 <= ndA5ReferenceSection3NoHitError B0 B ∧
            0 <= ndA5ReferenceSection3PassTVError B0 d B) ∧
        NDA5ReferenceSection3Bounds
          (ndA5ReferenceSection3NoHitError B0)
          (ndA5ReferenceSection3PassTVError B0 d) ∧
        ∀ {y : Real}, 1 <= y ->
          Qstep <= Tao.taoSection3ForwardThreshold y 0 ->
          ∀ J : Nat,
            (∑ m ∈ Finset.range J,
              Tao.taoSection3ForwardStepError
                (ndA5ReferenceSection3NoHitError B0)
                (ndA5ReferenceSection3PassTVError B0 d) y m) <=
              (960084 * (Real.log
                (Tao.taoSection3ForwardThreshold y 0)) ^ (-d)) /
                (1 - Tao.taoAlpha ^ (-d)) := by
  rcases exists_ndA5ReferenceSection3SplitRealRatePacket
      hPhase hd hd20 hdk with
    ⟨B0, hB0, hnonneg, _hNoHitRate, _hPassRate, hbounds⟩
  rcases exists_ndA5ReferenceSection3ForwardGeometricCutoff B0 hd hd20 with
    ⟨Qstep, hQstep, hsum⟩
  exact ⟨B0, Qstep, hB0, hQstep, hnonneg, hbounds, hsum⟩

end
end ND
end Erdos1135
