import Erdos1135.Tao.Section3.AmbientScalePilot

/-!
# Seed-Forward Ambient Section 3 Trace

This leaf reindexes the descending ambient windows forward from the selected
seed.  A bounded telescope requires only the steps in the requested prefix.
A later ambient-cut consumer chooses the prefix ending at
`N_(X^(1 / alpha))`; its proof therefore never inserts the unused next call to
`N_X`.
-/

namespace Erdos1135
namespace Tao

open Filter
open scoped Topology BigOperators

noncomputable section

/-- Scale obtained after `m` forward `alpha`-power steps from seed `y`. -/
def taoSection3ForwardScale (y : ℝ) (m : ℕ) : ℝ :=
  y ^ (taoAlpha ^ m)

/-- Proposition 1.11 threshold for the `m`-th seed-forward step. -/
def taoSection3ForwardThreshold (y : ℝ) (m : ℕ) : ℝ :=
  (taoSection3ForwardScale y m) ^ taoSection3AmbientRatio

/-- Source window at the `m`-th seed-forward scale. -/
def taoSection3ForwardWindow (y : ℝ) (m : ℕ) : Finset ℕ :=
  taoNyOddWindow (taoSection3ForwardScale y m) taoAlpha

/-- Fixed-target good probability in the `m`-th seed-forward window. -/
def taoSection3ForwardGoodProb (B : ℕ) (y : ℝ) (m : ℕ) : ℝ :=
  logFinsetProb (taoSection3ForwardWindow y m) (syracuseThresholdGood B)

/-- Error paid by the `m`-th seed-forward passage step. -/
def taoSection3ForwardStepError
    (errNoHit errTV : ℕ → ℝ) (y : ℝ) (m : ℕ) : ℝ :=
  taoSection3AmbientStepError errNoHit errTV
    (taoSection3ForwardThreshold y m)

theorem taoSection3ForwardScale_succ
    {y : ℝ} (hy : 0 ≤ y) (m : ℕ) :
    taoSection3ForwardScale y (m + 1) =
      (taoSection3ForwardScale y m) ^ taoAlpha := by
  simpa only [taoSection3ForwardScale, pow_succ] using
    Real.rpow_mul hy (taoAlpha ^ m) taoAlpha

theorem taoSection3ForwardThreshold_rpow_alpha
    {y : ℝ} (hy : 0 ≤ y) (m : ℕ) :
    (taoSection3ForwardThreshold y m) ^ taoAlpha =
      taoSection3ForwardScale y m := by
  unfold taoSection3ForwardThreshold
  simpa only [taoSection3AmbientRatio] using
    Real.rpow_inv_rpow
      (Real.rpow_nonneg hy (taoAlpha ^ m)) taoAlpha_pos.ne'

theorem taoSection3ForwardThreshold_rpow_alpha_sq
    {y : ℝ} (hy : 0 ≤ y) (m : ℕ) :
    (taoSection3ForwardThreshold y m) ^ (taoAlpha ^ 2) =
      taoSection3ForwardScale y (m + 1) := by
  calc
    (taoSection3ForwardThreshold y m) ^ (taoAlpha ^ 2) =
        ((taoSection3ForwardThreshold y m) ^ taoAlpha) ^ taoAlpha := by
      simpa only [pow_two] using
        Real.rpow_mul
          (x := taoSection3ForwardThreshold y m)
          (by
            unfold taoSection3ForwardThreshold
            exact Real.rpow_nonneg
              (Real.rpow_nonneg hy (taoAlpha ^ m)) taoSection3AmbientRatio)
          taoAlpha taoAlpha
    _ = (taoSection3ForwardScale y m) ^ taoAlpha := by
      rw [taoSection3ForwardThreshold_rpow_alpha hy]
    _ = taoSection3ForwardScale y (m + 1) := by
      rw [taoSection3ForwardScale_succ hy]

/-- Each seed-forward threshold compares the current window with the literal
next window. -/
theorem taoSection3Forward_prop111_pair
    {y : ℝ} (hy : 0 ≤ y) (m : ℕ) :
    TaoProp111RealWindowPair
      (taoSection3ForwardThreshold y m)
      (taoNyLo (taoSection3ForwardScale y m))
      (taoNyHi (taoSection3ForwardScale y m) taoAlpha)
      (taoNyLo (taoSection3ForwardScale y (m + 1)))
      (taoNyHi (taoSection3ForwardScale y (m + 1)) taoAlpha) := by
  simp [TaoProp111RealWindowPair, taoProp111RealY1, taoProp111RealY2,
    taoSection3ForwardThreshold_rpow_alpha hy,
    taoSection3ForwardThreshold_rpow_alpha_sq hy]

/-- Starting `m` forward steps below ambient index `i` returns exactly the
ambient boundary at `i`. -/
theorem taoSection3ForwardScale_ambient_add
    {X : ℝ} (hX : 0 ≤ X) (i m : ℕ) :
    taoSection3ForwardScale (taoSection3AmbientBoundary X (i + m)) m =
      taoSection3AmbientBoundary X i := by
  have hexponent :
      taoSection3AmbientRatio ^ (i + m) * taoAlpha ^ m =
        taoSection3AmbientRatio ^ i := by
    calc
      taoSection3AmbientRatio ^ (i + m) * taoAlpha ^ m =
          taoSection3AmbientRatio ^ i *
            (taoSection3AmbientRatio ^ m * taoAlpha ^ m) := by
        rw [pow_add]
        ring
      _ = taoSection3AmbientRatio ^ i *
          (taoSection3AmbientRatio * taoAlpha) ^ m := by
        rw [mul_pow]
      _ = taoSection3AmbientRatio ^ i := by
        simp [taoSection3AmbientRatio, taoAlpha_pos.ne']
  unfold taoSection3ForwardScale taoSection3AmbientBoundary
  rw [← Real.rpow_mul hX, hexponent]

/-- The corresponding forward threshold is the next lower ambient boundary. -/
theorem taoSection3ForwardThreshold_ambient_add
    {X : ℝ} (hX : 0 ≤ X) (i m : ℕ) :
    taoSection3ForwardThreshold
        (taoSection3AmbientBoundary X (i + m)) m =
      taoSection3AmbientBoundary X (i + 1) := by
  unfold taoSection3ForwardThreshold
  rw [taoSection3ForwardScale_ambient_add hX]
  symm
  simpa only [taoSection3AmbientRatio] using
    taoSection3AmbientBoundary_succ_eq_rpow_inv hX i

theorem taoSection3ForwardWindow_ambient_add
    {X : ℝ} (hX : 0 ≤ X) (i m : ℕ) :
    taoSection3ForwardWindow
        (taoSection3AmbientBoundary X (i + m)) m =
      taoSection3AmbientWindow X i := by
  unfold taoSection3ForwardWindow taoSection3AmbientWindow
  rw [taoSection3ForwardScale_ambient_add hX]

/-- A bounded seed-forward call has an ambient remainder index, with source,
target, and threshold all identified without natural subtraction. -/
theorem taoSection3ForwardCall_ambient_of_le
    {X : ℝ} (hX : 0 ≤ X) {j m : ℕ} (hm : m ≤ j) :
    ∃ d : ℕ, j = m + d ∧
      taoSection3ForwardThreshold
          (taoSection3AmbientBoundary X (j + 2)) m =
        taoSection3AmbientBoundary X (d + 3) ∧
      taoSection3ForwardWindow
          (taoSection3AmbientBoundary X (j + 2)) m =
        taoSection3AmbientWindow X (d + 2) ∧
      taoSection3ForwardWindow
          (taoSection3AmbientBoundary X (j + 2)) (m + 1) =
        taoSection3AmbientWindow X (d + 1) := by
  obtain ⟨d, rfl⟩ := Nat.exists_eq_add_of_le hm
  refine ⟨d, rfl, ?_, ?_, ?_⟩
  · simpa only [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm,
      Nat.reduceAdd] using
      taoSection3ForwardThreshold_ambient_add hX (d + 2) m
  · simpa only [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using
      taoSection3ForwardWindow_ambient_add hX (d + 2) m
  · simpa only [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm,
      Nat.reduceAdd] using
      taoSection3ForwardWindow_ambient_add hX (d + 1) (m + 1)

/-- Ambient `K=2` is one forward call at `b₃`, from `N_(b₂)` to `N_(b₁)`. -/
theorem taoSection3Forward_ambientK2_identification
    {X : ℝ} (hX : 0 ≤ X) :
    taoSection3ForwardThreshold (taoSection3AmbientBoundary X 2) 0 =
        taoSection3AmbientBoundary X 3 ∧
      taoSection3ForwardWindow (taoSection3AmbientBoundary X 2) 0 =
        taoSection3AmbientWindow X 2 ∧
      taoSection3ForwardWindow (taoSection3AmbientBoundary X 2) 1 =
        taoSection3AmbientWindow X 1 := by
  constructor
  · simpa using taoSection3ForwardThreshold_ambient_add hX 2 0
  constructor
  · simpa using taoSection3ForwardWindow_ambient_add hX 2 0
  · simpa using taoSection3ForwardWindow_ambient_add hX 1 1

/-- Ambient `K=3` has calls at `b₄,b₃` and one literal shared middle
forward window. -/
theorem taoSection3Forward_ambientK3_identification
    {X : ℝ} (hX : 0 ≤ X) :
    taoSection3ForwardThreshold (taoSection3AmbientBoundary X 3) 0 =
        taoSection3AmbientBoundary X 4 ∧
      taoSection3ForwardThreshold (taoSection3AmbientBoundary X 3) 1 =
        taoSection3AmbientBoundary X 3 ∧
      taoSection3ForwardWindow (taoSection3AmbientBoundary X 3) 0 =
        taoSection3AmbientWindow X 3 ∧
      taoSection3ForwardWindow (taoSection3AmbientBoundary X 3) 1 =
        taoSection3AmbientWindow X 2 ∧
      taoSection3ForwardWindow (taoSection3AmbientBoundary X 3) 2 =
        taoSection3AmbientWindow X 1 := by
  constructor
  · simpa using taoSection3ForwardThreshold_ambient_add hX 3 0
  constructor
  · simpa using taoSection3ForwardThreshold_ambient_add hX 2 1
  constructor
  · simpa using taoSection3ForwardWindow_ambient_add hX 3 0
  constructor
  · simpa using taoSection3ForwardWindow_ambient_add hX 2 1
  · simpa using taoSection3ForwardWindow_ambient_add hX 1 2

theorem taoSection3ForwardScale_monotone
    {y : ℝ} (hy : 1 ≤ y) :
    Monotone (taoSection3ForwardScale y) := by
  simpa only [taoSection3ForwardScale, Function.comp_apply] using
    (Real.monotone_rpow_of_base_ge_one hy).comp
      (pow_right_mono₀ taoAlpha_one_lt.le)

theorem taoSection3ForwardScale_seed_le
    {y : ℝ} (hy : 1 ≤ y) (m : ℕ) :
    y ≤ taoSection3ForwardScale y m := by
  have hmono := taoSection3ForwardScale_monotone hy (Nat.zero_le m)
  simpa only [taoSection3ForwardScale, pow_zero, Real.rpow_one] using hmono

theorem taoSection3ForwardThreshold_one_le
    {y : ℝ} (hy : 1 ≤ y) (m : ℕ) :
    1 ≤ taoSection3ForwardThreshold y m := by
  unfold taoSection3ForwardThreshold
  exact Real.one_le_rpow (hy.trans (taoSection3ForwardScale_seed_le hy m))
    taoSection3AmbientRatio_pos.le

/-- One real cutoff supplies every seed-forward threshold and normalizer.
The mass predicate itself is not claimed to be monotone. -/
theorem exists_taoSection3ForwardFamilyCutoff :
    ∃ Ymass : ℝ, 1 ≤ Ymass ∧
      ∀ {y : ℝ}, Ymass ≤ y →
        ∀ m : ℕ,
          1 ≤ taoSection3ForwardThreshold y m ∧
          0 < logFinsetMass (taoSection3ForwardWindow y m) := by
  obtain ⟨Y₀, hY₀⟩ :=
    eventually_taoNyOddWindow_mass_pos.exists_forall_of_atTop
  refine ⟨max 1 Y₀, le_max_left _ _, ?_⟩
  intro y hy m
  have hyOne : 1 ≤ y := (le_max_left 1 Y₀).trans hy
  have hseed := taoSection3ForwardScale_seed_le hyOne m
  refine ⟨taoSection3ForwardThreshold_one_le hyOne m, ?_⟩
  unfold taoSection3ForwardWindow
  exact hY₀ _ ((le_max_right 1 Y₀).trans (hy.trans hseed))

/-- Fixed-target no-hit is the exact complement of forward-window goodness. -/
theorem taoSection3ForwardNoHitProb_eq_one_sub_goodProb
    (B : ℕ) (y : ℝ) (m : ℕ)
    (hmass : 0 < logFinsetMass (taoSection3ForwardWindow y m)) :
    syracuseNoHitWindowProb B
        (taoNyLo (taoSection3ForwardScale y m))
        (taoNyHi (taoSection3ForwardScale y m) taoAlpha) hmass =
      1 - taoSection3ForwardGoodProb B y m := by
  simpa only [taoSection3ForwardGoodProb, taoSection3ForwardWindow,
    taoNyOddWindow] using
    syracuseNoHitWindowProb_eq_one_sub_thresholdGoodProb B
      (taoNyLo (taoSection3ForwardScale y m))
      (taoNyHi (taoSection3ForwardScale y m) taoAlpha) hmass

/-- A partial good-probability lower bound is equivalently a fixed-target
no-hit upper bound on that forward window. -/
theorem taoSection3ForwardNoHitProb_le_sum_of_partial
    {B : ℕ} {y : ℝ} {J : ℕ} {errNoHit errTV : ℕ → ℝ}
    (hmass : 0 < logFinsetMass (taoSection3ForwardWindow y J))
    (hpartial :
      1 - (∑ m ∈ Finset.range J,
          taoSection3ForwardStepError errNoHit errTV y m) ≤
        taoSection3ForwardGoodProb B y J) :
    syracuseNoHitWindowProb B
        (taoNyLo (taoSection3ForwardScale y J))
        (taoNyHi (taoSection3ForwardScale y J) taoAlpha) hmass ≤
      ∑ m ∈ Finset.range J,
        taoSection3ForwardStepError errNoHit errTV y m := by
  rw [taoSection3ForwardNoHitProb_eq_one_sub_goodProb]
  linarith

/-- Bounded all-partial trace consuming one fixed actual-real Proposition 1.11
error packet.  This is the uniform core used after the packet's witnesses have
been chosen outside all trace parameters. -/
theorem taoSection3Forward_allPartial_of_realRateBounds
    {errNoHit errTV : ℕ → ℝ}
    (hbounds : ∀ x lo₁ hi₁ lo₂ hi₂,
      (hx : 1 ≤ x) →
        TaoProp111RealWindowPair x lo₁ hi₁ lo₂ hi₂ →
          ∀ (hmass₁ : 0 < logFinsetMass (oddLogWindow lo₁ hi₁))
            (hmass₂ : 0 < logFinsetMass (oddLogWindow lo₂ hi₂)),
              syracuseNoHitRealWindowProb x lo₁ hi₁ hmass₁ ≤
                    errNoHit (Nat.floor x) ∧
                syracuseNoHitRealWindowProb x lo₂ hi₂ hmass₂ ≤
                    errNoHit (Nat.floor x) ∧
                  syracusePassRealFloorWindowTV x lo₁ hi₁ lo₂ hi₂ hx
                      hmass₁ hmass₂ ≤ errTV (Nat.floor x))
    {B Jmax : ℕ} {y : ℝ} (hB : 1 ≤ B) (hy : 1 ≤ y)
    (hmass : ∀ m : ℕ, m ≤ Jmax →
      0 < logFinsetMass (taoSection3ForwardWindow y m))
    (hseed : taoSection3ForwardScale y 1 ≤ (B : ℝ)) :
    ∀ J : ℕ, J ≤ Jmax →
      1 - (∑ m ∈ Finset.range J,
        taoSection3ForwardStepError errNoHit errTV y m) ≤
          taoSection3ForwardGoodProb B y J := by
  have hy0 : 0 ≤ y := zero_le_one.trans hy
  have hbase : taoSection3ForwardGoodProb B y 0 = 1 := by
    apply taoSection3Ambient_seed_prob_eq_one
      (y := taoSection3ForwardScale y 0)
    · exact Real.rpow_nonneg hy0 _
    · exact hmass 0 (Nat.zero_le Jmax)
    · rw [show
          (taoSection3ForwardScale y 0) ^ taoAlpha =
            taoSection3ForwardScale y 1 by
          symm
          simpa using taoSection3ForwardScale_succ hy0 0]
      exact hseed
  have hstep : ∀ m : ℕ, m < Jmax →
      taoSection3ForwardGoodProb B y m -
          taoSection3ForwardStepError errNoHit errTV y m ≤
        taoSection3ForwardGoodProb B y (m + 1) := by
    intro m hm
    have hmle : m ≤ Jmax := hm.le
    have hmsucc : m + 1 ≤ Jmax := hm
    have hpair := taoSection3Forward_prop111_pair hy0 m
    have hpacket := hbounds
      (taoSection3ForwardThreshold y m)
      (taoNyLo (taoSection3ForwardScale y m))
      (taoNyHi (taoSection3ForwardScale y m) taoAlpha)
      (taoNyLo (taoSection3ForwardScale y (m + 1)))
      (taoNyHi (taoSection3ForwardScale y (m + 1)) taoAlpha)
      (taoSection3ForwardThreshold_one_le hy m) hpair
      (hmass m hmle) (hmass (m + 1) hmsucc)
    have hone := taoSection3_fixedTargetGood_real_oneStep
      (b := B) (x := taoSection3ForwardThreshold y m)
      (lo₁ := taoNyLo (taoSection3ForwardScale y m))
      (hi₁ := taoNyHi (taoSection3ForwardScale y m) taoAlpha)
      (lo₂ := taoNyLo (taoSection3ForwardScale y (m + 1)))
      (hi₂ := taoNyHi (taoSection3ForwardScale y (m + 1)) taoAlpha)
      hB (taoSection3ForwardThreshold_one_le hy m)
      (hmass m hmle) (hmass (m + 1) hmsucc)
    have hone' :
        taoSection3ForwardGoodProb B y m -
            syracusePassRealFloorWindowTV
              (taoSection3ForwardThreshold y m)
              (taoNyLo (taoSection3ForwardScale y m))
              (taoNyHi (taoSection3ForwardScale y m) taoAlpha)
              (taoNyLo (taoSection3ForwardScale y (m + 1)))
              (taoNyHi (taoSection3ForwardScale y (m + 1)) taoAlpha)
              (taoSection3ForwardThreshold_one_le hy m)
              (hmass m hmle) (hmass (m + 1) hmsucc) -
            syracuseNoHitRealWindowProb
              (taoSection3ForwardThreshold y m)
              (taoNyLo (taoSection3ForwardScale y (m + 1)))
              (taoNyHi (taoSection3ForwardScale y (m + 1)) taoAlpha)
              (hmass (m + 1) hmsucc) ≤
          taoSection3ForwardGoodProb B y (m + 1) := by
      simpa only [taoSection3ForwardGoodProb, taoSection3ForwardWindow,
        taoNyOddWindow] using hone
    unfold taoSection3ForwardStepError taoSection3AmbientStepError
    linarith [hone', hpacket.2.2, hpacket.2.1]
  intro J hJ
  have htelescope := finite_telescope_lower_bound_bounded
    (taoSection3ForwardGoodProb B y)
    (taoSection3ForwardStepError errNoHit errTV y) 0 Jmax
    (by simp [hbase]) hstep J hJ
  simpa using htelescope

/-- Local checked bounded trace with rate witnesses selected for this call. -/
theorem taoSection3Forward_allPartial_checked
    {B Jmax : ℕ} {y : ℝ} (hB : 1 ≤ B) (hy : 1 ≤ y)
    (hmass : ∀ m : ℕ, m ≤ Jmax →
      0 < logFinsetMass (taoSection3ForwardWindow y m))
    (hseed : taoSection3ForwardScale y 1 ≤ (B : ℝ)) :
    ∃ errNoHit errTV : ℕ → ℝ, ∃ C c : ℝ,
      0 ≤ C ∧ 0 < c ∧
        (∀ᶠ x : ℝ in atTop,
          0 ≤ errNoHit (Nat.floor x) ∧
            0 ≤ errTV (Nat.floor x) ∧
              errNoHit (Nat.floor x) ≤ C * x ^ (-c) ∧
                errTV (Nat.floor x) ≤ C * (Real.log x) ^ (-c)) ∧
          ∀ J : ℕ, J ≤ Jmax →
            1 - (∑ m ∈ Finset.range J,
              taoSection3ForwardStepError errNoHit errTV y m) ≤
                taoSection3ForwardGoodProb B y J := by
  rcases taoProp111RealFirstPassageStabilizationRate_checked with
    ⟨errNoHit, errTV, C, c, hC, hc, hrate, hbounds⟩
  refine ⟨errNoHit, errTV, C, c, hC, hc, hrate, ?_⟩
  exact taoSection3Forward_allPartial_of_realRateBounds
    hbounds hB hy hmass hseed

end

end Tao
end Erdos1135
