///|
/// Last completed local iterate retained when a search fails.
#derive(Debug)
pub(all) struct LocalCheckpoint {
  x : Array[Double]
  value : Double
  gradient_norm : Double
  iterations : Int32
}

///|
/// An opt-in local-solver failure with its underlying error and checkpoint.
#derive(Debug)
pub(all) suberror LocalSearchFailure {
  Failed(source~ : Error, checkpoint~ : LocalCheckpoint, evaluations~ : Int32)
}

///|
/// Minimize a differentiable function using the selected local method and
/// Armijo backtracking by default, optionally using strong Wolfe. The default
/// algorithm is steepest descent. The callback returns
/// the value and analytic gradient at `x`.
/// Initial points and callback results must be finite, and the gradient must
/// have the same dimension as `initial`. Callback errors are propagated.
///
/// The returned point is a copy; `initial` is not modified. A budget exit is
/// not convergence. The method is local and does not handle constraints.
/// Optional step and objective tolerances report stagnation, not convergence.
/// With `recover_errors=true`, errors after the first valid evaluation include
/// the last completed iterate and the number of attempted objective evaluations.
///
/// ```mbt check
/// test {
///   let solution = @local.minimize(
///     x => (0.5 * (x[0] - 3.0) * (x[0] - 3.0), [x[0] - 3.0]),
///     [0.0],
///   )
///   assert_true(solution.termination is GradientTolerance)
///   assert_true((solution.x[0] - 3.0).abs() < 1.0e-6)
/// }
/// ```
pub fn minimize(
  objective : (ArrayView[Double]) -> (Double, Array[Double]) raise,
  initial : ArrayView[Double],
  gradient_tolerance~ : Double = 1.0e-6,
  max_iterations~ : Int32 = 5000,
  max_evaluations~ : Int32 = 10000,
  algorithm~ : Algorithm = SteepestDescent,
  line_search~ : LineSearch = Armijo,
  step_tolerance? : Tolerance,
  value_tolerance? : Tolerance,
  recover_errors~ : Bool = false,
) -> Solution raise {
  if initial.is_empty() {
    raise OptimizeError::InvalidInput("initial point must not be empty")
  }
  if !gradient_tolerance.is_finite() || gradient_tolerance <= 0.0 {
    raise OptimizeError::InvalidInput(
      "gradient tolerance must be positive and finite",
    )
  }
  if max_iterations < 0 || max_evaluations < 1 {
    raise OptimizeError::InvalidInput("invalid iteration or evaluation limit")
  }
  validate_tolerance(step_tolerance)
  validate_tolerance(value_tolerance)
  if algorithm is Broyden(phi) {
    if !phi.is_finite() || phi < 0.0 || phi > 1.0 {
      raise OptimizeError::InvalidInput("Broyden weight must be in [0, 1]")
    }
  }
  if algorithm is Lbfgs(memory) && memory <= 0 {
    raise OptimizeError::InvalidInput("L-BFGS memory must be positive")
  }
  for coordinate in initial {
    if !coordinate.is_finite() {
      raise OptimizeError::InvalidInput("initial point must be finite")
    }
  }
  let mut x = initial.to_owned()
  let (initial_value, initial_gradient, initial_norm) = evaluate(
    objective,
    x[:],
  )
  let mut value = initial_value
  let mut gradient = initial_gradient
  let mut norm = initial_norm
  let mut iterations = 0
  let evaluations = Ref(1)
  let mut stagnation : Termination? = None
  let mut inverse : Array[Array[Double]]? = None
  let mut cg_direction : Array[Double]? = None
  let history : Array[LbfgsPair] = []
  try {
    for ;; {
      let termination : Termination? = if norm <= gradient_tolerance {
        Some(GradientTolerance)
      } else if iterations >= max_iterations {
        Some(MaxIterations)
      } else if evaluations.val >= max_evaluations {
        Some(MaxEvaluations)
      } else {
        stagnation
      }
      if termination is Some(termination) {
        return {
          x,
          value,
          gradient_norm: norm,
          iterations,
          evaluations: evaluations.val,
          termination,
        }
      }
      let dense = match algorithm {
        Bfgs | Dfp | Sr1 | Broyden(_) => true
        _ => false
      }
      if dense && inverse is None {
        inverse = Some(identity_matrix(x.length()))
      }
      let mut direction = match algorithm {
        NormalizedGradient => gradient.map(g => -g / norm)
        FletcherReeves =>
          match cg_direction {
            Some(previous) => previous
            None => gradient.map(g => -g)
          }
        Lbfgs(_) => lbfgs_direction(gradient[:], history)
        _ =>
          match inverse {
            None => gradient.map(g => -g)
            Some(matrix) =>
              matrix_vector(matrix, gradient[:]).map(value => -value)
          }
      }
      let mut slope = match algorithm {
        SteepestDescent => norm * norm
        NormalizedGradient => norm
        _ => -dot(gradient[:], direction[:])
      }
      if (dense || algorithm is FletcherReeves || algorithm is Lbfgs(_)) &&
        (!slope.is_finite() || slope <= 0.0) {
        if dense {
          inverse = Some(identity_matrix(x.length()))
        }
        if algorithm is Lbfgs(_) {
          history.clear()
        }
        direction = gradient.map(g => -g)
        slope = norm * norm
      }
      if !slope.is_finite() || slope <= 0.0 {
        raise OptimizeError::NumericalFailure(
          "descent slope is not representable",
        )
      }
      let trial = local_line_search(
        objective,
        x[:],
        value,
        gradient[:],
        direction[:],
        slope,
        line_search,
        evaluations,
        max_evaluations,
      )
      guard trial is Some((candidate, trial_value, trial_gradient, trial_norm)) else {
        return {
          x,
          value,
          gradient_norm: norm,
          iterations,
          evaluations: evaluations.val,
          termination: MaxEvaluations,
        }
      }
      stagnation = if trial_norm <= gradient_tolerance ||
        iterations + 1 >= max_iterations ||
        evaluations.val >= max_evaluations {
        None
      } else {
        stagnation_reason(
          x[:],
          value,
          candidate[:],
          trial_value,
          step_tolerance,
          value_tolerance,
        )
      }
      if algorithm is Lbfgs(memory) {
        lbfgs_remember(
          history,
          memory,
          x[:],
          gradient[:],
          candidate[:],
          trial_gradient[:],
        )
      }
      if inverse is Some(matrix) {
        inverse = Some(
          quasi_newton_update(
            matrix,
            x[:],
            gradient[:],
            candidate[:],
            trial_gradient[:],
            algorithm,
          ),
        )
      }
      if algorithm is FletcherReeves {
        let ratio = trial_norm / norm
        let beta = ratio * ratio
        if (iterations + 1) % x.length() == 0 || !beta.is_finite() {
          cg_direction = None
        } else {
          cg_direction = Some(
            trial_gradient.mapi((i, g) => -g + beta * direction[i]),
          )
        }
      }
      x = candidate
      value = trial_value
      gradient = trial_gradient
      norm = trial_norm
      iterations += 1
    }
  } catch {
    error if recover_errors =>
      raise LocalSearchFailure::Failed(
        source=error,
        checkpoint={ x: x.copy(), value, gradient_norm: norm, iterations, },
        evaluations=evaluations.val,
      )
    error => raise error
  }
}