import Erdos1135.ND.Discrepancy.A5ReferenceSection3GeometricBudget

/-!
# Same-witness A5 Section 3 ambient terminal trace

This leaf combines one fixed facade witness, its geometric budget, the
uniform forward-window mass cutoff, and the weak ambient least crossing.  It
exports only the terminal harmonic no-hit estimate consumed by the later
all-source theorem.
-/

namespace Erdos1135
namespace ND

open Filter
open scoped Topology BigOperators

noncomputable section

/-- The explicit fixed-`d` loss from the first active threshold
`q_0 = b_(j+3)` to the fixed target `B`.
-/
noncomputable def ndA5ReferenceSection3AmbientTraceConstant
    (d : Real) : Real :=
  (960084 * (Tao.taoSection3AmbientRatio ^ 3) ^ (-d)) /
    (1 - Tao.taoAlpha ^ (-d))

/-- One sufficiently large natural target controls the complete active
ambient trace uniformly in its top `X`.  The hidden facade cutoff, scalar
step cutoff, mass cutoff, crossing index, and trace length are all selected
before or hidden from the public `B,X` tail.
-/
theorem exists_ndA5ReferenceSection3AmbientTerminal
    {c kappa d : Real} (hPhase : PhaseGap c kappa)
    (hd : 0 < d) (hd20 : d < 1 / 20)
    (hdk : d < 1 / (2 * kappa)) :
    ∃ Bstar : Nat,
      2 <= Bstar ∧
        0 <= ndA5ReferenceSection3AmbientTraceConstant d ∧
        ∀ {B : Nat}, Bstar <= B ->
          ∀ {X : Real}, (B : Real) < X ->
            ∃ hmass :
                0 < Tao.logFinsetMass
                  (Tao.taoSection3AmbientWindow X 1),
              Tao.syracuseNoHitWindowProb B
                  (Tao.taoNyLo
                    (Tao.taoSection3AmbientBoundary X 1))
                  (Tao.taoNyHi
                    (Tao.taoSection3AmbientBoundary X 1)
                    Tao.taoAlpha)
                  hmass <=
                ndA5ReferenceSection3AmbientTraceConstant d *
                  (Real.log (B : Real)) ^ (-d) := by
  rcases exists_ndA5ReferenceSection3ForwardGeometricPacket
      hPhase hd hd20 hdk with
    ⟨B0, Qstep, _hB0, hQstep, _hnonneg, hbounds, hgeom⟩
  rcases Tao.exists_taoSection3ForwardFamilyCutoff with
    ⟨Ymass, hYmass, hfamily⟩
  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 hdenomPos : 0 < 1 - Tao.taoAlpha ^ (-d) :=
    sub_pos.mpr hratioLt
  have hCtrace :
      0 <= ndA5ReferenceSection3AmbientTraceConstant d := by
    unfold ndA5ReferenceSection3AmbientTraceConstant
    exact div_nonneg
      (mul_nonneg (by norm_num)
        (Real.rpow_nonneg
          (pow_nonneg Tao.taoSection3AmbientRatio_pos.le 3) _))
      hdenomPos.le
  have hpow2 :
      Tendsto
        (fun B : Nat =>
          (B : Real) ^ (Tao.taoSection3AmbientRatio ^ 2)) atTop atTop := by
    simpa only [Function.comp_def] using
      (tendsto_rpow_atTop
        (pow_pos Tao.taoSection3AmbientRatio_pos 2)).comp
          tendsto_natCast_atTop_atTop
  have hpow3 :
      Tendsto
        (fun B : Nat =>
          (B : Real) ^ (Tao.taoSection3AmbientRatio ^ 3)) atTop atTop := by
    simpa only [Function.comp_def] using
      (tendsto_rpow_atTop
        (pow_pos Tao.taoSection3AmbientRatio_pos 3)).comp
          tendsto_natCast_atTop_atTop
  have hlarge : ∀ᶠ B : Nat in atTop,
      2 <= B ∧
        Ymass <= (B : Real) ^ (Tao.taoSection3AmbientRatio ^ 2) ∧
          Qstep <= (B : Real) ^ (Tao.taoSection3AmbientRatio ^ 3) := by
    filter_upwards [eventually_ge_atTop (2 : Nat),
      hpow2.eventually_ge_atTop Ymass,
      hpow3.eventually_ge_atTop Qstep]
      with B hB hmass hstep
    exact ⟨hB, hmass, hstep⟩
  rcases eventually_atTop.1 hlarge with ⟨Bstar, hBstar⟩
  refine ⟨Bstar, (hBstar Bstar le_rfl).1, hCtrace, ?_⟩
  intro B hBBstar X hBX
  rcases hBstar B hBBstar with ⟨hB, hmassB, hstepB⟩
  rcases Tao.exists_taoSection3AmbientTraceCut hB hBX with
    ⟨j, _hBj, _hpredLower, hpredUpper, hseedLower, _hseedUpper,
      hthresholdLower, _hthresholdUpper⟩
  have hBnonneg : (0 : Real) <= (B : Real) := Nat.cast_nonneg B
  have hXnonneg : (0 : Real) <= X := hBnonneg.trans hBX.le
  have hident := Tao.taoSection3AmbientForwardTrace_identifications
    hXnonneg j
  have hyMass :
      Ymass <= Tao.taoSection3AmbientBoundary X (j + 2) :=
    hmassB.trans hseedLower.le
  have hyOne :
      1 <= Tao.taoSection3AmbientBoundary X (j + 2) :=
    hYmass.trans hyMass
  have hseed :
      Tao.taoSection3ForwardScale
          (Tao.taoSection3AmbientBoundary X (j + 2)) 1 <=
        (B : Real) := by
    rw [hident.1]
    exact hpredUpper
  have hpartial := Tao.taoSection3Forward_allPartial_of_realRateBounds
    (Jmax := j + 1) hbounds (show 1 <= B by omega) hyOne
    (fun m _hm => (hfamily hyMass m).2) hseed
  let hmassForward :
      0 < Tao.logFinsetMass
        (Tao.taoSection3ForwardWindow
          (Tao.taoSection3AmbientBoundary X (j + 2)) (j + 1)) :=
    (hfamily hyMass (j + 1)).2
  have hpartialTerminal := hpartial (j + 1) le_rfl
  have hnoHitForward :=
    Tao.taoSection3ForwardNoHitProb_le_sum_of_partial
      hmassForward hpartialTerminal
  have hq0Large :
      Qstep < Tao.taoSection3ForwardThreshold
        (Tao.taoSection3AmbientBoundary X (j + 2)) 0 := by
    calc
      Qstep <= (B : Real) ^ (Tao.taoSection3AmbientRatio ^ 3) := hstepB
      _ < Tao.taoSection3AmbientBoundary X (j + 3) := hthresholdLower
      _ = Tao.taoSection3ForwardThreshold
          (Tao.taoSection3AmbientBoundary X (j + 2)) 0 := hident.2.1.symm
  have hsum := hgeom hyOne hq0Large.le (j + 1)
  have hBpos : 0 < (B : Real) := by positivity
  have hBone : (1 : Real) < (B : Real) := by
    exact_mod_cast (show 1 < B by omega)
  have hlogBpos : 0 < Real.log (B : Real) := Real.log_pos hBone
  have hboundaryLogLower :
      Tao.taoSection3AmbientRatio ^ 3 * Real.log (B : Real) <
        Real.log (Tao.taoSection3ForwardThreshold
          (Tao.taoSection3AmbientBoundary X (j + 2)) 0) := by
    calc
      Tao.taoSection3AmbientRatio ^ 3 * Real.log (B : Real) =
          Real.log ((B : Real) ^
            (Tao.taoSection3AmbientRatio ^ 3)) :=
        (Real.log_rpow hBpos
          (Tao.taoSection3AmbientRatio ^ 3)).symm
      _ < Real.log (Tao.taoSection3ForwardThreshold
          (Tao.taoSection3AmbientBoundary X (j + 2)) 0) :=
        Real.log_lt_log
          (Real.rpow_pos_of_pos hBpos
            (Tao.taoSection3AmbientRatio ^ 3))
          (by
            calc
              (B : Real) ^ (Tao.taoSection3AmbientRatio ^ 3) <
                  Tao.taoSection3AmbientBoundary X (j + 3) :=
                hthresholdLower
              _ = Tao.taoSection3ForwardThreshold
                  (Tao.taoSection3AmbientBoundary X (j + 2)) 0 :=
                hident.2.1.symm)
  have hlogRateCompare :
      (Real.log (Tao.taoSection3ForwardThreshold
          (Tao.taoSection3AmbientBoundary X (j + 2)) 0)) ^ (-d) <=
        (Tao.taoSection3AmbientRatio ^ 3) ^ (-d) *
          (Real.log (B : Real)) ^ (-d) := by
    calc
      (Real.log (Tao.taoSection3ForwardThreshold
          (Tao.taoSection3AmbientBoundary X (j + 2)) 0)) ^ (-d) <=
          (Tao.taoSection3AmbientRatio ^ 3 *
            Real.log (B : Real)) ^ (-d) :=
        Real.rpow_le_rpow_of_nonpos
          (mul_pos
            (pow_pos Tao.taoSection3AmbientRatio_pos 3) hlogBpos)
          hboundaryLogLower.le (neg_nonpos.mpr hd.le)
      _ = (Tao.taoSection3AmbientRatio ^ 3) ^ (-d) *
          (Real.log (B : Real)) ^ (-d) :=
        Real.mul_rpow
          (pow_nonneg Tao.taoSection3AmbientRatio_pos.le 3)
          hlogBpos.le
  have hfactorNonneg :
      0 <= (960084 : Real) / (1 - Tao.taoAlpha ^ (-d)) := by
    exact div_nonneg (by norm_num) hdenomPos.le
  have hsumRate :
      (∑ m ∈ Finset.range (j + 1),
          Tao.taoSection3ForwardStepError
            (ndA5ReferenceSection3NoHitError B0)
            (ndA5ReferenceSection3PassTVError B0 d)
            (Tao.taoSection3AmbientBoundary X (j + 2)) m) <=
        ndA5ReferenceSection3AmbientTraceConstant d *
          (Real.log (B : Real)) ^ (-d) := by
    refine hsum.trans ?_
    calc
      (960084 * (Real.log (Tao.taoSection3ForwardThreshold
            (Tao.taoSection3AmbientBoundary X (j + 2)) 0)) ^ (-d)) /
          (1 - Tao.taoAlpha ^ (-d)) =
          ((960084 : Real) / (1 - Tao.taoAlpha ^ (-d))) *
            (Real.log (Tao.taoSection3ForwardThreshold
              (Tao.taoSection3AmbientBoundary X (j + 2)) 0)) ^ (-d) := by
        ring
      _ <= ((960084 : Real) / (1 - Tao.taoAlpha ^ (-d))) *
          ((Tao.taoSection3AmbientRatio ^ 3) ^ (-d) *
            (Real.log (B : Real)) ^ (-d)) :=
        mul_le_mul_of_nonneg_left hlogRateCompare hfactorNonneg
      _ = ndA5ReferenceSection3AmbientTraceConstant d *
          (Real.log (B : Real)) ^ (-d) := by
        unfold ndA5ReferenceSection3AmbientTraceConstant
        ring
  have hmass :
      0 < Tao.logFinsetMass
        (Tao.taoSection3AmbientWindow X 1) := by
    rw [← hident.2.2.2]
    exact hmassForward
  refine ⟨hmass, ?_⟩
  have hnoHitTerminal :
      Tao.syracuseNoHitWindowProb B
          (Tao.taoNyLo (Tao.taoSection3AmbientBoundary X 1))
          (Tao.taoNyHi (Tao.taoSection3AmbientBoundary X 1)
            Tao.taoAlpha)
          hmass <=
        ∑ m ∈ Finset.range (j + 1),
          Tao.taoSection3ForwardStepError
            (ndA5ReferenceSection3NoHitError B0)
            (ndA5ReferenceSection3PassTVError B0 d)
            (Tao.taoSection3AmbientBoundary X (j + 2)) m := by
    simpa only [hident.2.2.1] using hnoHitForward
  exact hnoHitTerminal.trans hsumRate

end
end ND
end Erdos1135
