import Erdos1135.Tao.ColMin
import Erdos1135.Tao.Density.FiniteLogCountAlgebra
import Erdos1135.Tao.Section3.QuantitativeLowerBound
import Erdos1135.Tao.Section3.StandardBadMass
import Erdos1135.Tao.ThresholdAssembly

/-!
# Tao's Almost-Bounded-Orbits Theorem

This final leaf converts the checked all-prefix standard-Collatz bad-mass
bound into a threshold lower bound and then applies the existing statement and
strict `ColMin` adapters.  It makes no natural-density claim.
-/

namespace Erdos1135
namespace Tao

open Filter
open scoped Topology

/-- Harmonic counting ignores zero, so the positive naturals have the full
prefix mass even at the zero endpoint. -/
theorem logCount_positiveNaturals_eq_logMass (X : ℕ) :
    logCount {N : ℕ | 0 < N} X = logMass X := by
  rw [← logCount_univ]
  apply logCount_congr_on_pos
  intro N hN
  simp [hN]

private theorem positiveCollatzBad_eq_diff (B : ℕ) :
    positiveCollatzBad B =
      {N : ℕ | 0 < N} \ collatzThresholdGood B := by
  ext N
  by_cases hN : 0 < N <;>
    simp [positiveCollatzBad, collatzThresholdGood, hN]

/-- The positive standard bad set is the exact harmonic complement of the
positive standard threshold-good set. -/
theorem logCount_positiveCollatzBad_eq_sub (B X : ℕ) :
    logCount (positiveCollatzBad B) X =
      logMass X - logCount (collatzThresholdGood B) X := by
  have hsub : collatzThresholdGood B ⊆ {N : ℕ | 0 < N} := by
    intro N hN
    exact hN.1
  rw [positiveCollatzBad_eq_diff,
    logCount_diff_of_subset hsub,
    logCount_positiveNaturals_eq_logMass]

/-- An all-prefix bad-mass upper bound gives the corresponding normalized
good-mass lower bound.  No sign or upper bound on `delta` is required. -/
theorem logCountingRatio_collatzThresholdGood_ge_one_sub_of_bad_le
    {B X : ℕ} {delta : ℝ} (hX : 0 < X)
    (hbad :
      logCount (positiveCollatzBad B) X ≤ delta * logMass X) :
    1 - delta ≤ logCountingRatio (collatzThresholdGood B) X := by
  rw [logCount_positiveCollatzBad_eq_sub] at hbad
  have hmass :
      logMass X ≤ delta * logMass X +
        logCount (collatzThresholdGood B) X :=
    (sub_le_iff_le_add).mp hbad
  apply logCountingRatio_ge_of_logCount_ge_mul_logMass hX
  calc
    (1 - delta) * logMass X =
        logMass X - delta * logMass X := by ring
    _ ≤ logCount (collatzThresholdGood B) X :=
      (sub_le_iff_le_add).mpr (by simpa [add_comm] using hmass)

/-- Patch a uniform large-threshold all-prefix bad bound across the finitely
many smaller thresholds by assigning them error one. -/
theorem thresholdLowerBoundHypothesis_of_allPrefix_positiveBad
    (eta : ℕ → ℝ) (Bstar : ℕ)
    (heta : Tendsto eta atTop (nhds 0))
    (hbad : ∀ {B : ℕ}, Bstar ≤ B → ∀ X : ℕ,
      logCount (positiveCollatzBad B) X ≤ eta B * logMass X) :
    ThresholdLowerBoundHypothesis
      (fun B : ℕ => if B < Bstar then 1 else eta B) := by
  constructor
  · refine heta.congr' ?_
    filter_upwards [eventually_ge_atTop Bstar] with B hB
    simp [not_lt.mpr hB]
  · intro B _hBtwo
    by_cases hsmall : B < Bstar
    · filter_upwards
        [logCountingRatio_nonneg_eventually (collatzThresholdGood B)] with
        X hnonneg
      simpa [hsmall] using hnonneg
    · have hlarge : Bstar ≤ B := Nat.le_of_not_gt hsmall
      filter_upwards [eventually_ge_atTop (1 : ℕ)] with X hX
      have hXpos : 0 < X := lt_of_lt_of_le zero_lt_one hX
      have hratio :=
        logCountingRatio_collatzThresholdGood_ge_one_sub_of_bad_le
          hXpos (hbad hlarge X)
      simpa [hsmall] using hratio

/-- The checked Section 3 rate supplies a vanishing-error finite-threshold
lower bound for the standard Collatz good sets. -/
theorem exists_taoThresholdLowerBound_checked :
    ∃ eps : ℕ → ℝ, ThresholdLowerBoundHypothesis eps := by
  rcases exists_taoSection3UniformStandardBadMass_checked with
    ⟨D, c, Bstar, _hD, hc, _hBstar, hbad⟩
  let eta : ℕ → ℝ := fun B =>
    D * (Real.log (B : ℝ)) ^ (-c)
  refine ⟨fun B : ℕ => if B < Bstar then 1 else eta B, ?_⟩
  apply thresholdLowerBoundHypothesis_of_allPrefix_positiveBad eta Bstar
  · dsimp only [eta]
    exact section3_log_power_rate_tendsto_zero D c hc
  · intro B hBBstar X
    dsimp only [eta]
    exact hbad hBBstar X

/-- Tao's almost-bounded-orbits theorem in the checked hit-predicate form. -/
theorem taoAlmostBounded_checked :
    TaoAlmostBoundedStatement := by
  rcases exists_taoThresholdLowerBound_checked with ⟨eps, heps⟩
  exact taoAlmostBounded_of_thresholdLowerBound heps

/-- Tao's published strict `ColMin(N) < f(N)` almost-bounded-orbits theorem. -/
theorem taoAlmostBoundedColMin_checked :
    TaoAlmostBoundedColMinStatement :=
  TaoAlmostBoundedStatement_iff_colMin.mp taoAlmostBounded_checked

end Tao
end Erdos1135
