import WeilLogBlock
import Mathlib.Topology.Order.OrderClosed
import Mathlib.Topology.Instances.Real.Lemmas
import Mathlib.Tactic.FieldSimp
set_option autoImplicit false
noncomputable section
namespace AMNAIClosureCycle
open Filter Topology

theorem positive_limit {T : Type*} (Q : ℕ → T → ℝ) (q : T → ℝ)
    (hpos : ∀ n t, 0 ≤ Q n t)
    (hlim : ∀ t, Tendsto (fun n => Q n t) atTop (𝓝 (q t))) :
    ∀ t, 0 ≤ q t := by
  intro t
  exact ge_of_tendsto (hlim t) (Filter.Eventually.of_forall (fun n => hpos n t))

theorem positive_of_vanishing_error {T : Type*}
    (Q : ℕ → T → ℝ) (q : T → ℝ) (err : ℕ → T → ℝ)
    (hpos : ∀ n t, 0 ≤ Q n t)
    (herr : ∀ n t, |q t - Q n t| ≤ err n t)
    (hlim : ∀ t, Tendsto (fun n => err n t) atTop (𝓝 0)) :
    ∀ t, 0 ≤ q t := by
  intro t
  have hbound : ∀ n, -q t ≤ err n t := by
    intro n
    have ha := (abs_le.mp (herr n t)).1
    linarith [hpos n t]
  have hh : -q t ≤ 0 := ge_of_tendsto' (hlim t) hbound
  linarith

theorem arithmetic_positive_of_binding {T S : Type*}
    (Q : ℕ → S → ℝ) (q : S → ℝ) (W : T → ℝ) (encode : T → S)
    (hpos : ∀ n s, 0 ≤ Q n s)
    (hlim : ∀ s, Tendsto (fun n => Q n s) atTop (𝓝 (q s)))
    (binding : ∀ t, W t = q (encode t)) : ∀ t, 0 ≤ W t := by
  intro t
  rw [binding t]
  exact positive_limit Q q hpos hlim (encode t)

theorem positive_margin_transfer {T : Type*}
    (q q0 weight : T → ℝ) (a e : ℝ)
    (h0 : ∀ t, a * weight t ≤ q0 t)
    (herr : ∀ t, |q t - q0 t| ≤ e * weight t)
    (hweight : ∀ t, 0 ≤ weight t) (hmargin : e ≤ a) :
    ∀ t, 0 ≤ q t := by
  intro t
  have hl := WeilLogBlock.lower_bound_transfer q q0 weight a e h0 herr t
  exact le_trans (mul_nonneg (sub_nonneg.mpr hmargin) (hweight t)) hl

theorem reciprocal_center (p : ℝ) (hp : 0 < p) :
    (p - p⁻¹)^2 = 0 ↔ p = 1 := by
  constructor
  · intro h
    have hz : p - p⁻¹ = 0 := (sq_eq_zero_iff).mp h
    have hinv : p = p⁻¹ := sub_eq_zero.mp hz
    have hne : p ≠ 0 := ne_of_gt hp
    have hm : p * p = 1 := by
      calc
        p * p = p * p⁻¹ := congrArg (fun z : ℝ => p * z) hinv
        _ = 1 := mul_inv_cancel₀ hne
    nlinarith
  · rintro rfl
    norm_num

theorem zero_forces_defect_zero {T : Type*}
    (energy defect weight : T → ℝ)
    (hd : ∀ t, 0 ≤ defect t) (hw : ∀ t, 0 < weight t)
    (bound : ∀ t, weight t * defect t ≤ energy t) :
    ∀ t, energy t = 0 → defect t = 0 := by
  intro t hz
  have hh := bound t
  rw [hz] at hh
  nlinarith [hd t, hw t]

theorem finite_prefix_does_not_certify_global (N : ℕ) :
    ∃ q : ℕ → ℝ, (∀ n, n ≤ N → 0 ≤ q n) ∧ q (N + 1) < 0 := by
  refine ⟨fun n => if n ≤ N then 1 else -1, ?_, ?_⟩
  · intro n hn
    simp [hn]
  · simp
end AMNAIClosureCycle
