///|
priv struct SimplexVertex {
  x : Array[Double]
  value : Double
}

///|
priv struct ValueSearch {
  objective : (ArrayView[Double]) -> Double raise
  max_evaluations : Int32
  target_value : Double?
  mut best : Array[Double]
  mut best_value : Double
  mut evaluations : Int32
  observer : ((SearchEvent) -> SearchControl raise)?
  mut cancelled : Bool
}

///|
fn ValueSearch::observe(
  self : ValueSearch,
  x : ArrayView[Double],
  value : Double,
) -> Unit raise {
  if self.observer is Some(observer) {
    let control = observer({
      x: x.to_owned(),
      value,
      best_value: self.best_value,
      evaluations: self.evaluations,
    })
    if control is Stop {
      self.cancelled = true
    }
  }
}

///|
fn ValueSearch::evaluate(self : ValueSearch, x : Array[Double]) -> Double raise {
  let value = value_only(self.objective, x[:])
  self.evaluations += 1
  if value < self.best_value {
    self.best = x.copy()
    self.best_value = value
  }
  self.observe(x[:], value)
  value
}

///|
fn ValueSearch::stop(self : ValueSearch) -> SearchTermination? {
  if self.cancelled {
    Some(Cancelled)
  } else if self.target_value is Some(target) && self.best_value <= target {
    Some(TargetReached)
  } else if self.evaluations >= self.max_evaluations {
    Some(MaxEvaluations)
  } else {
    None
  }
}

///|
fn ValueSearch::result(
  self : ValueSearch,
  iterations : Int32,
  termination : SearchTermination,
) -> SearchSolution {
  {
    x: self.best,
    value: self.best_value,
    iterations,
    evaluations: self.evaluations,
    termination,
  }
}

///|
fn simplex_trial(
  origin : ArrayView[Double],
  other : ArrayView[Double],
  factor : Double,
  lo : ArrayView[Double],
  hi : ArrayView[Double],
) -> Array[Double] {
  origin.mapi((i, value) => {
    (value + factor * (other[i] - value)).clamp(min=lo[i], max=hi[i])
  })
}

///|
/// Minimize a value-only objective over a finite box using a projected
/// Nelder-Mead simplex. Each free coordinate contributes one simplex vertex;
/// fixed coordinates are allowed. The inputs are copied and never modified.
///
/// The returned best point includes trials evaluated during an incomplete
/// simplex initialization or iteration. Small or collapsed simplices report
/// `Stagnated`, not convergence or global optimality.
///
/// ```mbt check
/// test {
///   let result = @search.nelder_mead(
///     x => (x[0] - 0.25) * (x[0] - 0.25),
///     [0.0],
///     [-1.0],
///     [1.0],
///     target_value=1.0e-8,
///   )
///   assert_true(result.termination is TargetReached)
/// }
/// ```
pub fn nelder_mead(
  objective : (ArrayView[Double]) -> Double raise,
  initial : ArrayView[Double],
  lower : ArrayView[Double],
  upper : ArrayView[Double],
  initial_step~ : Double = 0.1,
  step_tolerance~ : Double = 1.0e-8,
  max_iterations~ : Int32 = 2000,
  max_evaluations~ : Int32 = 10000,
  target_value? : Double,
) -> SearchSolution raise {
  validate_search_options(
    initial_step, step_tolerance, max_iterations, max_evaluations, target_value,
  )
  let (lo, hi, widths) = validate_box(initial, lower, upper)
  let start = initial.to_owned()
  let first = value_only(objective, start[:])
  let run : ValueSearch = {
    objective,
    max_evaluations,
    target_value,
    best: start.copy(),
    best_value: first,
    evaluations: 1,
    observer: None,
    cancelled: false,
  }
  if run.stop() is Some(reason) {
    return run.result(0, reason)
  }
  let free = []
  for i in 0.. 0.0 {
      free.push(i)
    }
  }
  if free.is_empty() {
    return run.result(0, Stagnated)
  }
  if max_iterations == 0 {
    return run.result(0, MaxIterations)
  }
  let simplex : Array[SimplexVertex] = [{ x: start, value: first, }]
  for i in free {
    let distance = initial_step * widths[i]
    let candidate = start.copy()
    candidate[i] = if distance <= hi[i] - start[i] {
      start[i] + distance
    } else {
      start[i] - distance.min(start[i] - lo[i])
    }
    if candidate[i] == start[i] {
      raise OptimizeError::InvalidInput(
        "initial simplex cannot be represented at this scale",
      )
    }
    let value = run.evaluate(candidate)
    if run.stop() is Some(reason) {
      return run.result(0, reason)
    }
    simplex.push({ x: candidate, value, })
  }
  let dimension = free.length()
  let mut iterations = 0
  for ;; {
    simplex.sort_by((a, b) => a.value.compare(b.value))
    let best = simplex[0]
    let mut diameter = 0.0
    for j in 1..<=dimension {
      for i in free {
        diameter = diameter.max((simplex[j].x[i] - best.x[i]).abs() / widths[i])
      }
    }
    if diameter <= step_tolerance {
      return run.result(iterations, Stagnated)
    }
    if iterations >= max_iterations {
      return run.result(iterations, MaxIterations)
    }
    let center = simplex[0].x.copy()
    for j in 1..