///|
/// Termination of a bounded scalar minimization.
#derive(Debug, Eq)
pub(all) enum ScalarTermination {
  IntervalTolerance
  Stagnated
  MaxIterations
  MaxEvaluations
}

///|
/// Scalar interval-search method.
#derive(Debug, Eq)
pub(all) enum ScalarMethod {
  GoldenSection
  Parabolic
}

///|
/// Best evaluated point and remaining interval. When an original endpoint is
/// best, the reported interval is extended to include it.
#derive(Debug)
pub(all) struct ScalarSolution {
  x : Double
  value : Double
  lower : Double
  upper : Double
  iterations : Int32
  evaluations : Int32
  termination : ScalarTermination
}

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

///|
fn scalar_result(
  best_x : Double,
  best_value : Double,
  lower : Double,
  upper : Double,
  iterations : Int32,
  evaluations : Int32,
  termination : ScalarTermination,
) -> ScalarSolution {
  {
    x: best_x,
    value: best_value,
    lower: lower.min(best_x),
    upper: upper.max(best_x),
    iterations,
    evaluations,
    termination,
  }
}

///|
/// Minimize a continuous unimodal scalar function on a closed finite interval
/// by golden-section search or safeguarded parabolic interpolation. Both endpoints are candidates. `IntervalTolerance`
/// describes the reduced interval before any extension to include the best
/// endpoint, not an unconditional global-optimality proof.
/// The interval test uses `absolute_tolerance + relative_tolerance *
/// max(abs(lower), abs(upper))`, with the current reduced endpoints.
/// All objective calls count against the strict evaluation limit.
///
/// ```mbt check
/// test {
///   let result = @scalar.minimize_scalar(x => (x - 0.4) * (x - 0.4), -1.0, 2.0)
///   assert_true(result.termination is IntervalTolerance)
///   assert_true((result.x - 0.4).abs() < 1.0e-6)
/// }
/// ```
pub fn minimize_scalar(
  objective : (Double) -> Double raise,
  lower : Double,
  upper : Double,
  absolute_tolerance~ : Double = 1.0e-8,
  relative_tolerance~ : Double = 1.4901161193847656e-8,
  max_iterations~ : Int32 = 5000,
  max_evaluations~ : Int32 = 10000,
  algorithm~ : ScalarMethod = GoldenSection,
) -> ScalarSolution raise {
  if !lower.is_finite() ||
    !upper.is_finite() ||
    lower >= upper ||
    !(upper - lower).is_finite() {
    raise OptimizeError::InvalidInput(
      "scalar bounds must be finite and increasing",
    )
  }
  if !absolute_tolerance.is_finite() ||
    !relative_tolerance.is_finite() ||
    absolute_tolerance < 0.0 ||
    relative_tolerance < 0.0 ||
    (absolute_tolerance == 0.0 && relative_tolerance == 0.0) {
    raise OptimizeError::InvalidInput(
      "scalar tolerances must be finite, nonnegative, and not both zero",
    )
  }
  if max_iterations < 0 || max_evaluations < 1 {
    raise OptimizeError::InvalidInput("invalid iteration or evaluation limit")
  }
  if algorithm is Parabolic {
    return scalar_parabolic(
      objective, lower, upper, absolute_tolerance, relative_tolerance, max_iterations,
      max_evaluations,
    )
  }
  let mut a = lower
  let mut b = upper
  let mut best_x = lower
  let mut best_value = scalar_value(objective, lower)
  let mut evaluations = 1
  let mut iterations = 0
  if evaluations >= max_evaluations {
    return scalar_result(
      best_x,
      best_value,
      a,
      b,
      iterations,
      evaluations,
      MaxEvaluations,
    )
  }
  let upper_value = scalar_value(objective, upper)
  evaluations += 1
  if upper_value < best_value {
    best_x = upper
    best_value = upper_value
  }
  let tol = absolute_tolerance +
    relative_tolerance * lower.abs().max(upper.abs())
  if !tol.is_finite() {
    raise OptimizeError::NumericalFailure("scalar tolerance overflow")
  }
  if upper - lower <= tol {
    return scalar_result(
      best_x,
      best_value,
      a,
      b,
      iterations,
      evaluations,
      IntervalTolerance,
    )
  }
  if iterations >= max_iterations {
    return scalar_result(
      best_x,
      best_value,
      a,
      b,
      iterations,
      evaluations,
      MaxIterations,
    )
  }
  if evaluations >= max_evaluations {
    return scalar_result(
      best_x,
      best_value,
      a,
      b,
      iterations,
      evaluations,
      MaxEvaluations,
    )
  }
  let fraction = 0.3819660112501051
  let mut left = a + fraction * (b - a)
  let mut right = b - fraction * (b - a)
  if left <= a || right >= b || left >= right {
    return scalar_result(
      best_x,
      best_value,
      a,
      b,
      iterations,
      evaluations,
      Stagnated,
    )
  }
  let mut left_value = scalar_value(objective, left)
  evaluations += 1
  if left_value < best_value {
    best_x = left
    best_value = left_value
  }
  if evaluations >= max_evaluations {
    return scalar_result(
      best_x,
      best_value,
      a,
      b,
      iterations,
      evaluations,
      MaxEvaluations,
    )
  }
  let mut right_value = scalar_value(objective, right)
  evaluations += 1
  if right_value < best_value {
    best_x = right
    best_value = right_value
  }
  for ;; {
    let tolerance = absolute_tolerance +
      relative_tolerance * a.abs().max(b.abs())
    if !tolerance.is_finite() {
      raise OptimizeError::NumericalFailure("scalar tolerance overflow")
    }
    if b - a <= tolerance {
      return scalar_result(
        best_x,
        best_value,
        a,
        b,
        iterations,
        evaluations,
        IntervalTolerance,
      )
    }
    if iterations >= max_iterations {
      return scalar_result(
        best_x,
        best_value,
        a,
        b,
        iterations,
        evaluations,
        MaxIterations,
      )
    }
    if evaluations >= max_evaluations {
      return scalar_result(
        best_x,
        best_value,
        a,
        b,
        iterations,
        evaluations,
        MaxEvaluations,
      )
    }
    if left_value <= right_value {
      b = right
      right = left
      right_value = left_value
      left = a + fraction * (b - a)
      if left <= a || left >= right {
        return scalar_result(
          best_x,
          best_value,
          a,
          b,
          iterations,
          evaluations,
          Stagnated,
        )
      }
      left_value = scalar_value(objective, left)
      evaluations += 1
      if left_value < best_value {
        best_x = left
        best_value = left_value
      }
    } else {
      a = left
      left = right
      left_value = right_value
      right = b - fraction * (b - a)
      if right >= b || right <= left {
        return scalar_result(
          best_x,
          best_value,
          a,
          b,
          iterations,
          evaluations,
          Stagnated,
        )
      }
      right_value = scalar_value(objective, right)
      evaluations += 1
      if right_value < best_value {
        best_x = right
        best_value = right_value
      }
    }
    iterations += 1
  }
}