///|
/// A value-only search stops on a target, a limit, or mesh stagnation.
/// Stagnation does not certify an optimum.
#derive(Debug, Eq)
pub(all) enum SearchTermination {
  TargetReached
  Stagnated
  MaxIterations
  MaxEvaluations
  Cancelled
}

///|
/// An observer's instruction after a successful objective evaluation.
#derive(Debug, Eq)
pub(all) enum SearchControl {
  Continue
  Stop
}

///|
/// A checked value-only evaluation, after updating the best-so-far value.
#derive(Debug)
pub(all) struct SearchEvent {
  x : Array[Double]
  value : Double
  best_value : Double
  evaluations : Int32
}

///|
/// Best point evaluated by a value-only search. Iterations count completed
/// polls or simplex iterations; evaluations include all attempted trials.
#derive(Debug)
pub(all) struct SearchSolution {
  x : Array[Double]
  value : Double
  iterations : Int32
  evaluations : Int32
  termination : SearchTermination
}

///|
fn value_only(
  objective : (ArrayView[Double]) -> Double raise,
  x : ArrayView[Double],
) -> Double raise {
  let value = objective(x)
  if !value.is_finite() {
    raise OptimizeError::InvalidEvaluation("objective value must be finite")
  }
  value
}

///|
fn validate_search_options(
  initial_step : Double,
  step_tolerance : Double,
  max_iterations : Int32,
  max_evaluations : Int32,
  target_value : Double?,
) -> Unit raise OptimizeError {
  if !initial_step.is_finite() ||
    initial_step <= 0.0 ||
    initial_step > 1.0 ||
    !step_tolerance.is_finite() ||
    step_tolerance <= 0.0 {
    raise OptimizeError::InvalidInput("invalid normalized step or tolerance")
  }
  validate_search_limits(max_iterations, max_evaluations, target_value)
}

///|
fn validate_search_limits(
  max_iterations : Int32,
  max_evaluations : Int32,
  target_value : Double?,
) -> Unit raise OptimizeError {
  if max_iterations < 0 || max_evaluations < 1 {
    raise OptimizeError::InvalidInput("invalid iteration or evaluation limit")
  }
  if target_value is Some(target) {
    if !target.is_finite() {
      raise OptimizeError::InvalidInput("target value must be finite")
    }
  }
}

///|
/// Minimize a value-only objective over a finite box by coordinate polling.
/// `initial_step` and `step_tolerance` are fractions of each box width.
/// Fixed coordinates are allowed. The inputs are copied and never modified.
///
/// The returned best point may be from an unfinished poll. A target value is
/// not a global-optimality certificate, and a small mesh is not convergence.
/// Callback errors propagate and non-finite objective values raise an error.
///
/// ```mbt check
/// test {
///   let result = @search.pattern_search(
///     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)
///   assert_true(result.value <= 1.0e-8)
/// }
/// ```
pub fn pattern_search(
  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 {
  let n = initial.length()
  validate_search_options(
    initial_step, step_tolerance, max_iterations, max_evaluations, target_value,
  )
  let (lo, hi, widths) = validate_box(initial, lower, upper)
  let mut best = initial.to_owned()
  let mut best_value = value_only(objective, best[:])
  let mut evaluations = 1
  let mut iterations = 0
  let mut step = initial_step
  for ;; {
    let reason = if target_value is Some(target) && best_value <= target {
      Some(TargetReached)
    } else if evaluations >= max_evaluations {
      Some(MaxEvaluations)
    } else if step <= step_tolerance || widths.all(width => width == 0.0) {
      Some(Stagnated)
    } else if iterations >= max_iterations {
      Some(MaxIterations)
    } else {
      None
    }
    if reason is Some(termination) {
      return {
        x: best,
        value: best_value,
        iterations,
        evaluations,
        termination,
      }
    }
    let center = best.copy()
    let previous_value = best_value
    let mut any_trial = false
    for i in 0..= center[i] - lo[i] {
            lo[i]
          } else {
            center[i] - distance
          }
        } else if distance >= hi[i] - center[i] {
          hi[i]
        } else {
          center[i] + distance
        }
        if next == center[i] {
          continue
        }
        any_trial = true
        let trial = center.copy()
        trial[i] = next
        let trial_value = value_only(objective, trial[:])
        evaluations += 1
        if trial_value < best_value {
          best = trial
          best_value = trial_value
        }
        if target_value is Some(target) && best_value <= target {
          return {
            x: best,
            value: best_value,
            iterations,
            evaluations,
            termination: TargetReached,
          }
        }
        if evaluations >= max_evaluations {
          return {
            x: best,
            value: best_value,
            iterations,
            evaluations,
            termination: MaxEvaluations,
          }
        }
      }
    }
    if !any_trial {
      return {
        x: best,
        value: best_value,
        iterations,
        evaluations,
        termination: Stagnated,
      }
    }
    iterations += 1
    if best_value >= previous_value {
      step *= 0.5
    }
  }
}