///|
/// A checked value-only point retained by an evaluation context.
#derive(Debug)
pub(all) struct EvaluatedPoint {
  x : Array[Double]
  value : Double
}

///|
/// A stopped context rejects further evaluations; a search failure can carry
/// the original error and a best-point checkpoint.
#derive(Debug)
pub(all) suberror EvaluationContextError {
  SearchStopped(SearchTermination)
  SearchFailure(
    source~ : Error,
    last_point~ : EvaluatedPoint,
    evaluations~ : Int32,
    gradient_evaluations~ : Int32,
  )
}

///|
/// Evaluation budget with best-so-far recovery and observation.
pub struct EvaluationContext {
  objective : (ArrayView[Double], Bool) -> (Double, Array[Double]?) raise
  has_gradient : Bool
  dimension : Int32
  max_evaluations : Int32
  target_value : Double?
  observer : ((SearchEvent) -> SearchControl raise)?
  mut evaluations : Int32
  mut gradient_evaluations : Int32
  mut best : EvaluatedPoint?
  mut cancelled : Bool
}

///|
/// Construct a context without evaluating the objective.
///
/// ```mbt check
/// test {
///   let context = @search.EvaluationContext::new(
///     x => x[0] * x[0],
///     1,
///     max_evaluations=2,
///   )
///   assert_eq(context.evaluate([2.0]), 4.0)
///   assert_eq(context.best().unwrap().value, 4.0)
/// }
/// ```
pub fn EvaluationContext::new(
  objective : (ArrayView[Double]) -> Double raise,
  dimension : Int32,
  max_evaluations~ : Int32 = 10000,
  target_value? : Double,
  observer? : (SearchEvent) -> SearchControl raise,
) -> EvaluationContext raise OptimizeError {
  new_evaluation_context(
    (x, _) => (objective(x), None),
    false,
    dimension,
    max_evaluations,
    target_value,
    observer,
  )
}

///|
/// Construct a context whose callback can optionally supply a gradient.
/// The callback's Boolean argument is true when a gradient is requested.
/// In that case it must return `Some` finite vector matching the dimension.
///
/// ```mbt check
/// test {
///   let context = @search.EvaluationContext::new_with_gradient(
///     (x, need_gradient) => {
///       (x[0] * x[0], if need_gradient { Some([2.0 * x[0]]) } else { None })
///     },
///     1,
///   )
///   let (value, gradient) = context.evaluate_with_gradient([2.0])
///   assert_eq(value, 4.0)
///   assert_eq(gradient, [4.0])
/// }
/// ```
pub fn EvaluationContext::new_with_gradient(
  objective : (ArrayView[Double], Bool) -> (Double, Array[Double]?) raise,
  dimension : Int32,
  max_evaluations~ : Int32 = 10000,
  target_value? : Double,
  observer? : (SearchEvent) -> SearchControl raise,
) -> EvaluationContext raise OptimizeError {
  new_evaluation_context(
    objective, true, dimension, max_evaluations, target_value, observer,
  )
}

///|
fn new_evaluation_context(
  objective : (ArrayView[Double], Bool) -> (Double, Array[Double]?) raise,
  has_gradient : Bool,
  dimension : Int32,
  max_evaluations : Int32,
  target_value : Double?,
  observer : ((SearchEvent) -> SearchControl raise)?,
) -> EvaluationContext raise OptimizeError {
  if dimension < 1 || max_evaluations < 1 {
    raise OptimizeError::InvalidInput(
      "invalid evaluation context dimensions or budget",
    )
  }
  if target_value is Some(target) && !target.is_finite() {
    raise OptimizeError::InvalidInput("evaluation target must be finite")
  }
  {
    objective,
    has_gradient,
    dimension,
    max_evaluations,
    target_value,
    observer,
    evaluations: 0,
    gradient_evaluations: 0,
    best: None,
    cancelled: false,
  }
}

///|
/// Number of attempted evaluations requesting a gradient, including failures.
pub fn EvaluationContext::gradient_evaluations(
  self : EvaluationContext,
) -> Int32 {
  self.gradient_evaluations
}

///|
/// Number of attempted objective callbacks, including callbacks that failed.
pub fn EvaluationContext::evaluations(self : EvaluationContext) -> Int32 {
  self.evaluations
}

///|
/// Return an owned copy of the best valid point, if one has been observed.
pub fn EvaluationContext::best(self : EvaluationContext) -> EvaluatedPoint? {
  self.best.map(point => { x: point.x.copy(), value: point.value, })
}

///|
/// Attach a copy of the best valid point and attempted-work counts to an
/// error. If no valid point has been evaluated, return the original error.
///
/// ```mbt check
/// test {
///   let context = @search.EvaluationContext::new(x => x[0] * x[0], 1)
///   ignore(context.evaluate([2.0]))
///   let failure = context.failure(@nlopt4m.OptimizeError::LineSearchFailed)
///   guard failure
///     is @search.EvaluationContextError::SearchFailure(last_point~, ..) else {
///     fail("expected a checkpoint")
///   }
///   assert_eq(last_point.value, 4.0)
/// }
/// ```
pub fn EvaluationContext::failure(
  self : EvaluationContext,
  source : Error,
) -> Error {
  match self.best() {
    Some(last_point) =>
      EvaluationContextError::SearchFailure(
        source~,
        last_point~,
        evaluations=self.evaluations,
        gradient_evaluations=self.gradient_evaluations,
      )
    None => source
  }
}

///|
/// Cancellation takes precedence over target attainment and budget exhaustion.
pub fn EvaluationContext::stop_reason(
  self : EvaluationContext,
) -> SearchTermination? {
  if self.cancelled {
    Some(Cancelled)
  } else if self.best is Some(point) &&
    self.target_value is Some(target) &&
    point.value <= target {
    Some(TargetReached)
  } else if self.evaluations >= self.max_evaluations {
    Some(MaxEvaluations)
  } else {
    None
  }
}

///|
/// Check the point, charge the attempt, evaluate, then update the checkpoint
/// before invoking the observer. Callback errors propagate and the checkpoint
/// remains available through `best`.
pub fn EvaluationContext::evaluate(
  self : EvaluationContext,
  x : ArrayView[Double],
) -> Double raise {
  self.evaluate_internal(x, false).0
}

///|
/// Evaluate the value and gradient, validating both before updating the
/// checkpoint or notifying the observer. Attempts count as both objective
/// and gradient evaluations.
pub fn EvaluationContext::evaluate_with_gradient(
  self : EvaluationContext,
  x : ArrayView[Double],
) -> (Double, Array[Double]) raise {
  let (value, gradient) = self.evaluate_internal(x, true)
  guard gradient is Some(gradient) else {
    abort("validated gradient is missing")
  }
  (value, gradient)
}

///|
fn EvaluationContext::evaluate_internal(
  self : EvaluationContext,
  x : ArrayView[Double],
  need_gradient : Bool,
) -> (Double, Array[Double]?) raise {
  if x.length() != self.dimension || x.any(value => !value.is_finite()) {
    raise OptimizeError::InvalidInput("invalid evaluation point")
  }
  if need_gradient && !self.has_gradient {
    raise OptimizeError::InvalidInput(
      "evaluation context has no gradient callback",
    )
  }
  if self.stop_reason() is Some(reason) {
    raise EvaluationContextError::SearchStopped(reason)
  }
  self.evaluations += 1
  if need_gradient {
    self.gradient_evaluations += 1
  }
  let (value, gradient) = (self.objective)(x, need_gradient)
  if !value.is_finite() {
    raise OptimizeError::InvalidEvaluation("objective value must be finite")
  }
  if need_gradient {
    match gradient {
      Some(g) if g.length() == self.dimension && g.all(v => v.is_finite()) => ()
      _ =>
        raise OptimizeError::InvalidEvaluation(
          "gradient must be finite and match the evaluation dimension",
        )
    }
  }
  if self.best is None || (self.best is Some(best) && value < best.value) {
    self.best = Some({ x: x.to_owned(), value, })
  }
  if self.observer is Some(observer) {
    let best_value = self.best.unwrap().value
    let control = observer({
      x: x.to_owned(),
      value,
      best_value,
      evaluations: self.evaluations,
    })
    if control is Stop {
      self.cancelled = true
    }
  }
  (value, gradient)
}