///|
/// A strong-Wolfe trial, including its already evaluated gradient.
#derive(Debug)
pub(all) struct WolfeStep {
  alpha : Double
  value : Double
  gradient : Array[Double]
  evaluations : Int32
}

///|
/// Find a positive step satisfying sufficient decrease and strong curvature.
/// The callback receives the step length and returns the value and gradient
/// at that trial. Its evaluations are counted separately from the supplied
/// origin. Callback errors and exhausted or unrepresentable brackets are
/// reported; an unchecked trial is never returned.
///
/// ```mbt check
/// test {
///   let step = @line_search.strong_wolfe(4.0, [-4.0], [1.0], a => {
///     ((a - 2.0) * (a - 2.0), [2.0 * (a - 2.0)])
///   })
///   assert_true(step.value < 4.0)
/// }
/// ```
pub fn strong_wolfe(
  value : Double,
  gradient : ArrayView[Double],
  direction : ArrayView[Double],
  objective : (Double) -> (Double, Array[Double]) raise,
  sufficient_decrease~ : Double = 1.0e-4,
  curvature~ : Double = 0.9,
  initial_step~ : Double = 1.0,
  maximum_step~ : Double = 1.0e20,
  max_evaluations~ : Int32 = 80,
) -> WolfeStep raise {
  if !value.is_finite() ||
    gradient.is_empty() ||
    gradient.length() != direction.length() ||
    gradient.any(v => !v.is_finite()) ||
    direction.any(v => !v.is_finite()) ||
    !sufficient_decrease.is_finite() ||
    !curvature.is_finite() ||
    sufficient_decrease <= 0.0 ||
    sufficient_decrease >= curvature ||
    curvature >= 1.0 ||
    !initial_step.is_finite() ||
    initial_step <= 0.0 ||
    !maximum_step.is_finite() ||
    maximum_step < initial_step ||
    max_evaluations < 1 {
    raise OptimizeError::InvalidInput("invalid strong-Wolfe arguments")
  }
  let slope = dot(gradient, direction)
  if !slope.is_finite() || slope >= 0.0 {
    raise OptimizeError::InvalidInput(
      "strong-Wolfe direction must be finite and descending",
    )
  }
  let mut previous_alpha = 0.0
  let mut previous_value = value
  let mut alpha = initial_step
  let mut bracket : (Double, Double, Double)? = None
  for evaluations in 1..<=max_evaluations {
    if bracket is Some((lo, hi, _)) {
      alpha = lo + 0.5 * (hi - lo)
      if alpha == lo || alpha == hi || alpha <= 0.0 || !alpha.is_finite() {
        raise OptimizeError::LineSearchFailed
      }
    }
    let (trial_value, trial_gradient) = objective(alpha)
    if !trial_value.is_finite() ||
      trial_gradient.length() != gradient.length() ||
      trial_gradient.any(v => !v.is_finite()) {
      raise OptimizeError::InvalidEvaluation("invalid strong-Wolfe trial")
    }
    let derivative = dot(trial_gradient[:], direction)
    let armijo_bound = value + sufficient_decrease * alpha * slope
    if !derivative.is_finite() || !armijo_bound.is_finite() {
      raise OptimizeError::NumericalFailure(
        "strong-Wolfe derivative or bound overflow",
      )
    }
    let armijo = trial_value <= armijo_bound
    if bracket is Some((lo, hi, flo)) {
      if !armijo || trial_value >= flo {
        bracket = Some((lo, alpha, flo))
      } else {
        if derivative.abs() <= -curvature * slope {
          return {
            alpha,
            value: trial_value,
            gradient: trial_gradient.copy(),
            evaluations,
          }
        }
        let next_hi = if (derivative >= 0.0 && hi >= lo) ||
          (derivative <= 0.0 && hi <= lo) {
          lo
        } else {
          hi
        }
        bracket = Some((alpha, next_hi, trial_value))
      }
    } else if !armijo || (evaluations > 1 && trial_value >= previous_value) {
      bracket = Some((previous_alpha, alpha, previous_value))
    } else {
      if derivative.abs() <= -curvature * slope {
        return {
          alpha,
          value: trial_value,
          gradient: trial_gradient.copy(),
          evaluations,
        }
      }
      if derivative >= 0.0 {
        bracket = Some((alpha, previous_alpha, trial_value))
      } else {
        previous_alpha = alpha
        previous_value = trial_value
        let next = (2.0 * alpha).min(maximum_step)
        if !next.is_finite() || next <= alpha {
          raise OptimizeError::LineSearchFailed
        }
        alpha = next
      }
    }
  }
  raise OptimizeError::LineSearchFailed
}