import Std

/-!
An exact finite-recipe minimum certificate and a fully specified discrete
cluster toy. All clock times, rates, memories, and budget figures in the toy
are chosen constants; this is not a training-time estimate for a real model.
-/
namespace FiniteTrainingOptimum

universe u
variable {Recipe : Type u}

/-- Exact global minimum among only the listed recipes and modeled runs. -/
def ExactMinimum (recipes : List Recipe) (feasible : Recipe → Nat → Prop)
    (best : Nat) : Prop :=
  (∃ r ∈ recipes, feasible r best) ∧
    ∀ t, (∃ r ∈ recipes, feasible r t) → best ≤ t

/-- An individually sound lower certificate and an attaining witness suffice.
The exhaustive assumption is relative to this exact recipe list. -/
theorem minimum_from_bounds_and_witness
    (recipes : List Recipe) (admissible : Recipe → Prop)
    (feasible : Recipe → Nat → Prop) (lower : Recipe → Nat) (best : Nat)
    (feasible_admits : ∀ r ∈ recipes, ∀ t, feasible r t → admissible r)
    (bound_sound : ∀ r ∈ recipes, ∀ t, feasible r t → lower r ≤ t)
    (all_admissible_bounds : ∀ r ∈ recipes, admissible r → best ≤ lower r)
    (attains : ∃ r ∈ recipes, feasible r best) :
    ExactMinimum recipes feasible best := by
  constructor
  · exact attains
  · intro t ht
    obtain ⟨r, member, run⟩ := ht
    exact Nat.le_trans
      (all_admissible_bounds r member (feasible_admits r member t run))
      (bound_sound r member t run)

theorem minimum_unique (recipes : List Recipe) (feasible : Recipe → Nat → Prop)
    (a b : Nat) (ha : ExactMinimum recipes feasible a) (hb : ExactMinimum recipes feasible b) :
    a = b :=
  Nat.le_antisymm (ha.2 b hb.1) (hb.2 a ha.1)

/-- First hit for a single fixed initialization, goal, recipe and execution. -/
def FirstHit (hit : Nat → Prop) (m : Nat) : Prop :=
  hit m ∧ ∀ t, hit t → m ≤ t

/-- Finite prefix search witness; no monotonicity is needed for existence. -/
theorem first_hit_within (hit : Nat → Prop) (cap : Nat) :
    (∃ k, k ≤ cap ∧ hit k) → ∃ m, m ≤ cap ∧ FirstHit hit m := by
  classical
  induction cap with
  | zero =>
    rintro ⟨k, hk, h⟩
    have zero : k = 0 := by omega
    subst k
    exact ⟨0, Nat.le_refl 0, h, fun _ _ => Nat.zero_le _⟩
  | succ n step =>
    intro has
    by_cases before : ∃ k, k ≤ n ∧ hit k
    · obtain ⟨m, hm, first⟩ := step before
      exact ⟨m, by omega, first⟩
    · obtain ⟨k, hk, succeeds⟩ := has
      have notLE : ¬ k ≤ n := fun h => before ⟨k, h, succeeds⟩
      refine ⟨k, hk, succeeds, ?_⟩
      intro t ht
      have notLE' : ¬ t ≤ n := fun h => before ⟨t, h, ht⟩
      omega

/-- A success alone provides an upper bound, not evidence of minimality. -/
theorem observed_success_upper_bound (hit : Nat → Prop) (U : Nat)
    (success : hit U) : ∃ m, m ≤ U ∧ FirstHit hit m :=
  first_hit_within hit U ⟨U, Nat.le_refl U, success⟩

/-- A failure rules out earlier hits only with an independently justified
monotonicity premise, and only for this one recipe/run predicate. -/
theorem monotone_observed_bracket (hit : Nat → Prop) (L U : Nat)
    (mono : ∀ a b, a ≤ b → hit a → hit b)
    (failure : ¬ hit L) (success : hit U) :
    ∃ m, FirstHit hit m ∧ L < m ∧ m ≤ U := by
  obtain ⟨m, hm, first⟩ := observed_success_upper_bound hit U success
  have h : ¬ m ≤ L := fun le => failure (mono m L le first.1)
  exact ⟨m, first, by omega, hm⟩

namespace Toy

structure Plan where
  extraWorkers : Nat
  fast : Bool
  deriving DecidableEq, Repr

def workers (r : Plan) : Nat := r.extraWorkers + 1
def perWorkerRate (r : Plan) : Nat := if r.fast then 8 else 4
def bandwidth (r : Plan) : Nat := workers r * perWorkerRate r
def serial (r : Plan) : Nat := 1 + 2 * r.extraWorkers
def slots (r : Plan) : Nat := if r.fast then 5 else 8
def fixedWork : Nat := 96
def trainingWeightSlots : Nat := 16
def maxWorkerTicks : Nat := 39

def plans : List Plan :=
  [⟨0,false⟩,⟨1,false⟩,⟨2,false⟩,⟨3,false⟩,
   ⟨0,true⟩,⟨1,true⟩,⟨2,true⟩,⟨3,true⟩]

/-- Positive rate is derived from the concrete recipe type. -/
theorem bandwidth_positive (r : Plan) : 0 < bandwidth r := by
  unfold bandwidth workers perWorkerRate
  cases r.fast <;> simp <;> omega

/-- Ideal discrete completion time: communication is a disjoint serial
phase in this model. -/
def lower (r : Plan) : Nat :=
  serial r + (fixedWork + (bandwidth r - 1)) / bandwidth r

/-- Constructive schedule: after setup, perform capacity work per tick
and finish the final partial tick at the target. Workers' allocation
is paid for all ticks, including setup. -/
def progress (r : Plan) (t : Nat) : Nat :=
  min fixedWork ((t - serial r) * bandwidth r)

def memoryFits (r : Plan) : Prop :=
  trainingWeightSlots ≤ workers r * slots r

def feasible (r : Plan) (t : Nat) : Prop :=
  memoryFits r ∧ workers r * t ≤ maxWorkerTicks ∧ progress r t = fixedWork

/-- Purely an accounting model: this schedule starts at zero new work
and does not exceed a single tick's aggregate capacity. -/
theorem initial_zero (r : Plan) : progress r 0 = 0 := by
  simp [progress]

theorem progress_step_capacity (r : Plan) (t : Nat) :
    progress r (t+1) ≤ progress r t + bandwidth r := by
  have subtract : t + 1 - serial r ≤ (t - serial r) + 1 := by omega
  have rate := Nat.mul_le_mul_right (bandwidth r) subtract
  rw [Nat.add_mul, Nat.one_mul] at rate
  unfold progress
  omega

/-- Initialization and goal are distinct: 0 completed units versus 96. -/
theorem zero_is_not_a_training_solution (r : Plan) : ¬ feasible r 0 := by
  intro rhs
  have h := rhs.2.2
  rw [initial_zero] at h
  simp [fixedWork] at h

theorem analytical_floor (r : Plan) (t : Nat) (run : feasible r t) :
    lower r ≤ t := by
  have doneAt := run.2.2
  unfold progress at doneAt
  have cap : fixedWork ≤ (t - serial r) * bandwidth r := by omega
  have hs : serial r ≤ t := by
    by_cases h : serial r ≤ t
    · exact h
    · have h0 : t - serial r = 0 := by omega
      rw [h0, Nat.zero_mul] at cap
      simp [fixedWork] at cap
  have positive := bandwidth_positive r
  have q : (fixedWork + (bandwidth r - 1)) / bandwidth r ≤ t - serial r := by
    apply Nat.le_of_lt_succ
    apply (Nat.div_lt_iff_lt_mul positive).2
    rw [Nat.succ_mul]
    omega
  unfold lower
  omega

/-- Precheck the minimum device-tick charge, even before actual execution. -/
def admitted (r : Plan) : Prop :=
  memoryFits r ∧ workers r * lower r ≤ maxWorkerTicks

theorem any_feasible_is_admitted (r : Plan) (t : Nat) (run : feasible r t) :
    admitted r := by
  exact ⟨run.1, Nat.le_trans (Nat.mul_le_mul_left (workers r) (analytical_floor r t run)) run.2.1⟩

/-- Exhaustive certificate checked by reducing eight concrete recipes.
Not an optimization theorem outside the listed set. -/
theorem every_admitted_plan_has_bound (r : Plan) (row : r ∈ plans) :
    admitted r → 13 ≤ lower r := by
  simp [plans] at row
  rcases row with h | h | h | h | h | h | h | h <;> subst r <;> unfold admitted memoryFits <;> decide

def chosen : Plan := ⟨2,false⟩

theorem chosen_is_listed : chosen ∈ plans := by decide
theorem chosen_attains : feasible chosen 13 := by
  unfold feasible memoryFits
  decide

theorem exact_optimum_is_13 : ExactMinimum plans feasible 13 :=
  minimum_from_bounds_and_witness plans admitted feasible lower 13
    (fun r _ t run => any_feasible_is_admitted r t run)
    (fun r _ t run => analytical_floor r t run)
    every_admitted_plan_has_bound
    ⟨chosen, chosen_is_listed, chosen_attains⟩

/-- Lower time without scratch capacity is not a feasible cheaper recipe. -/
theorem fast_two_is_time_nine_but_not_enough_ram :
    lower ⟨1,true⟩ = 9 ∧ ¬ memoryFits ⟨1,true⟩ := by
  unfold memoryFits
  decide

/-- Faster nominal elapsed time with four workers violates the allocation budget. -/
theorem fast_four_is_time_ten_but_over_budget :
    lower ⟨3,true⟩ = 10 ∧ memoryFits ⟨3,true⟩ ∧
      maxWorkerTicks < workers ⟨3,true⟩ * lower ⟨3,true⟩ := by
  unfold memoryFits
  decide

end Toy

#print axioms minimum_from_bounds_and_witness
#print axioms monotone_observed_bracket
#print axioms Toy.progress_step_capacity
#print axioms Toy.analytical_floor
#print axioms Toy.every_admitted_plan_has_bound
#print axioms Toy.exact_optimum_is_13
#print axioms Toy.zero_is_not_a_training_solution

end FiniteTrainingOptimum
