import Erdos1135.Terras.FiniteStoppingTime

/-!
# Logarithmic-time Terras corollary

This module strengthens the density-one finite-stopping-time theorem by imposing any fixed
positive logarithmic budget on the number of accelerated Collatz steps.
-/

namespace Erdos1135
namespace Terras

open Filter
open scoped Topology

/-- Starting values that descend within a real-valued `C * log n` accelerated-step budget. -/
def finiteStoppingTimeLogBudgetSet (C : ℝ) : Set ℕ :=
  {n | ∃ k : ℕ,
    (k : ℝ) ≤ C * Real.log (n : ℝ) ∧ accelerated^[k] n < n}

/-- Every fixed step count eventually fits inside any positive multiple of `log n`. -/
theorem exists_finiteStoppingTimeLogBudget_cutoff
    (C : ℝ) (hC : 0 < C) (k : ℕ) :
    ∃ B : ℕ, ∀ n : ℕ, B ≤ n → (k : ℝ) ≤ C * Real.log (n : ℝ) := by
  have hlog :
      Tendsto (fun n : ℕ => Real.log (n : ℝ)) atTop atTop :=
    Real.tendsto_log_atTop.comp tendsto_natCast_atTop_atTop
  rcases eventually_atTop.1
      (hlog.eventually_ge_atTop ((k : ℝ) / C)) with ⟨B, hB⟩
  refine ⟨B, fun n hn => ?_⟩
  calc
    (k : ℝ) = C * ((k : ℝ) / C) := by field_simp [hC.ne']
    _ ≤ C * Real.log (n : ℝ) :=
      mul_le_mul_of_nonneg_left (hB n hn) hC.le

/-- Terras's density-one stopping theorem remains true with any fixed positive `C * log n`
budget on the number of accelerated steps. -/
theorem finiteStoppingTimeLogBudgetSet_natDensity_one
    (C : ℝ) (hC : 0 < C) :
    HasNatDensity (finiteStoppingTimeLogBudgetSet C) 1 := by
  choose B hB using fun k => exists_finiteStoppingTimeLogBudget_cutoff C hC k
  apply HasNatDensity.of_superset_of_tendsto_one
    (A := fun k =>
      {n : ℕ |
        (branchThresholdMax k ≤ n ∧
          (n : ZMod (2 ^ k)) ∈ contractingResidues k) ∧ B k ≤ n})
    (d := fun k =>
      ((Fintype.card {w : ParityWord k // 3 ^ numOdd w < 2 ^ k}) : ℝ) /
        (2 ^ k : ℝ))
  · intro k n hn
    change ∃ j : ℕ,
      (j : ℝ) ≤ C * Real.log (n : ℝ) ∧ accelerated^[j] n < n
    exact ⟨k, hB k n hn.2,
      descends_of_mem_contractingResidues_ge hn.1.1 hn.1.2⟩
  · intro k
    exact (hasNatDensity_contractingResidues_ge_wordRatio k).inter_Ici (B k)
  · exact card_contracting_words_asymptotic

/-- Literal-set form of the positive-constant logarithmic stopping-time corollary. -/
theorem finiteStoppingTime_logBudget_natDensity_one
    (C : ℝ) (hC : 0 < C) :
    HasNatDensity
      {n : ℕ | ∃ k : ℕ,
        (k : ℝ) ≤ C * Real.log (n : ℝ) ∧ accelerated^[k] n < n}
      1 := by
  exact finiteStoppingTimeLogBudgetSet_natDensity_one C hC

/-- In particular, almost every starting value descends within `log n` accelerated steps. -/
theorem finiteStoppingTime_log_natDensity_one :
    HasNatDensity
      {n : ℕ | ∃ k : ℕ,
        (k : ℝ) ≤ Real.log (n : ℝ) ∧ accelerated^[k] n < n}
      1 := by
  simpa using finiteStoppingTime_logBudget_natDensity_one (1 : ℝ) zero_lt_one

end Terras
end Erdos1135
