///|
/// Equality-constrained exact-Hessian method.
#derive(Debug, Eq)
pub(all) enum EqualityNewtonMethod {
  NewtonLagrange
  LagrangeSqp
}

///|
fn kkt_merit(
  state : ConstrainedEvaluation,
  mu : ArrayView[Double],
) -> Double raise OptimizeError {
  let gradient = lagrangian_gradient(state, mu, [])
  let merit = dot(gradient[:], gradient[:]) +
    dot(state.constraints.equalities[:], state.constraints.equalities[:])
  if !merit.is_finite() {
    raise OptimizeError::NumericalFailure("KKT merit overflow")
  }
  merit
}

///|
/// Solve equality-constrained problems using the exact Lagrangian Hessian.
/// The Hessian callback receives the current point and equality multipliers,
/// using `L = f - mu'h`. `LagrangeSqp` stabilizes the Hessian with `A'A / 3.1`.
/// Inequality constraints are rejected. Objective callbacks, including rejected
/// line-search trials, share the evaluation budget. KKT convergence does not
/// certify that the stationary point is a minimum.
///
/// ```mbt check
/// test {
///   let result = @constrained.equality_newton(
///     x => {
///       value: x[0] * x[0],
///       gradient: [2.0 * x[0]],
///       constraints: {
///         equalities: [x[0] - 1.0],
///         inequalities: [],
///         equality_jacobian: [[1.0]],
///         inequality_jacobian: [],
///       },
///     },
///     (_, _) => [[2.0]],
///     [0.0],
///   )
///   assert_true(result.solution.termination is KktTolerance)
/// }
/// ```
pub fn equality_newton(
  objective : (ArrayView[Double]) -> ConstrainedEvaluation raise,
  lagrangian_hessian : (ArrayView[Double], ArrayView[Double]) -> Array[
    Array[Double],
  ] raise,
  initial : ArrayView[Double],
  algorithm~ : EqualityNewtonMethod = NewtonLagrange,
  gradient_tolerance~ : Double = 1.0e-6,
  feasibility_tolerance~ : Double = 1.0e-6,
  max_iterations~ : Int32 = 100,
  max_evaluations~ : Int32 = 10000,
  step_tolerance? : Tolerance,
  value_tolerance? : Tolerance,
) -> ConstrainedSolution raise {
  if initial.is_empty() ||
    initial.any(value => !value.is_finite()) ||
    !gradient_tolerance.is_finite() ||
    gradient_tolerance <= 0.0 ||
    !feasibility_tolerance.is_finite() ||
    feasibility_tolerance <= 0.0 ||
    max_iterations < 0 ||
    max_evaluations < 1 {
    raise OptimizeError::InvalidInput("invalid equality Newton options")
  }
  validate_tolerance(step_tolerance)
  validate_tolerance(value_tolerance)
  let mut x = initial.to_owned()
  let mut state = constrained_evaluate(objective, x[:], None)
  let count = state.constraints.equalities.length()
  if !state.constraints.inequalities.is_empty() {
    raise OptimizeError::InvalidInput(
      "equality Newton methods do not support inequalities",
    )
  }
  let mut mu = Array::make(count, 0.0)
  let mut evaluations = 1
  let mut previous : (Array[Double], Double)? = None
  let stabilization = match algorithm {
    NewtonLagrange => 0.0
    LagrangeSqp => 1.0 / 3.1
  }
  for iteration in 0..<=max_iterations {
    let report = constrained_report(
      x,
      state,
      mu,
      [],
      iteration,
      evaluations,
      MaxIterations,
    )
    if report.solution.gradient_norm <= gradient_tolerance &&
      report.constraint_violation <= feasibility_tolerance {
      return constrained_report(
        x,
        state,
        mu,
        [],
        iteration,
        evaluations,
        KktTolerance,
      )
    }
    if iteration == max_iterations {
      return report
    }
    if evaluations >= max_evaluations {
      return constrained_report(
        x,
        state,
        mu,
        [],
        iteration,
        evaluations,
        MaxEvaluations,
      )
    }
    if previous is Some((old_x, old_value)) &&
      stagnation_reason(
        old_x[:],
        old_value,
        x[:],
        state.value,
        step_tolerance,
        value_tolerance,
      )
      is Some(reason) {
      return constrained_report(
        x,
        state,
        mu,
        [],
        iteration,
        evaluations,
        reason,
      )
    }
    if step_tolerance is Some(_) || value_tolerance is Some(_) {
      previous = Some((x.copy(), state.value))
    }
    let hessian = lagrangian_hessian(x[:], mu[:])
    let jacobian = state.constraints.equality_jacobian
    if hessian.length() != x.length() ||
      hessian.any(row => {
        row.length() != x.length() || row.any(value => !value.is_finite())
      }) {
      raise OptimizeError::InvalidEvaluation("invalid Lagrangian Hessian")
    }
    let matrix = hessian.map(row => row.copy())
    if stabilization != 0.0 {
      for i in 0.. -value)
    let step = equality_quadratic_inner(
      matrix[:],
      state.gradient[:],
      jacobian[:],
      rhs[:],
      allow_indefinite=true,
    )
    let direction = step.solution.x
    let dmu = step.equality_multipliers.mapi((i, value) => {
      value - mu[i] - stabilization * dot(jacobian[i][:], direction[:])
    })
    if dmu.any(value => !value.is_finite()) {
      raise OptimizeError::NumericalFailure("multiplier step overflow")
    }
    let merit = kkt_merit(state, mu[:])
    let mut alpha = 1.0
    let mut accepted : (Array[Double], Array[Double], ConstrainedEvaluation)? = None
    for _ in 0..<64 {
      if evaluations >= max_evaluations {
        return constrained_report(
          x,
          state,
          mu,
          [],
          iteration,
          evaluations,
          MaxEvaluations,
        )
      }
      let trial_x = x.mapi((i, value) => value + alpha * direction[i])
      let trial_mu = mu.mapi((i, value) => value + alpha * dmu[i])
      if trial_x.any(v => !v.is_finite()) ||
        trial_mu.any(v => !v.is_finite()) ||
        (trial_x == x && trial_mu == mu) {
        raise OptimizeError::NumericalFailure("KKT trial is not representable")
      }
      let trial = constrained_evaluate(objective, trial_x[:], Some((count, 0)))
      evaluations += 1
      if kkt_merit(trial, trial_mu[:]) <= merit * (1.0 - 1.0e-4 * alpha) {
        accepted = Some((trial_x, trial_mu, trial))
        break
      }
      alpha *= 0.5
    }
    guard accepted is Some((next_x, next_mu, next_state)) else {
      raise OptimizeError::LineSearchFailed
    }
    x = next_x
    mu = next_mu
    state = next_state
  }
  abort("unreachable equality Newton iteration")
}