// APPROXIMATE layer (design D3): unconstrained BFGS minimization, ported from
// verb/core/Minimizer.hx (MIT, 164 lines) — the zero-dependency replacement for
// curvo's argmin crate. Backtracking Armijo line search + inverse-Hessian BFGS
// update. Callers supply an analytic gradient where available (closest-point
// projection does); a numerical central-difference gradient is provided as a
// fallback. Internal to the package.

///|
fn vec_dot(a : FixedArray[Double], b : FixedArray[Double]) -> Double {
  let mut s = 0.0
  for i = 0; i < a.length(); i = i + 1 {
    s = s + a[i] * b[i]
  }
  s
}

///|
fn vec_norm(a : FixedArray[Double]) -> Double {
  vec_dot(a, a).sqrt()
}

///|
/// Row-major n x n matrix-vector product.
fn mat_vec(h : FixedArray[Double], v : FixedArray[Double], n : Int) -> FixedArray[Double] {
  let out : FixedArray[Double] = FixedArray::make(n, 0.0)
  for i = 0; i < n; i = i + 1 {
    let mut s = 0.0
    for j = 0; j < n; j = j + 1 {
      s = s + h[i * n + j] * v[j]
    }
    out[i] = s
  }
  out
}

///|
/// Outer product a (x) b as a row-major n x n matrix.
fn tensor(a : FixedArray[Double], b : FixedArray[Double], n : Int) -> FixedArray[Double] {
  let out : FixedArray[Double] = FixedArray::make(n * n, 0.0)
  for i = 0; i < n; i = i + 1 {
    for j = 0; j < n; j = j + 1 {
      out[i * n + j] = a[i] * b[j]
    }
  }
  out
}

///|
/// Numerical central-difference gradient with adaptive step (verb fallback).
fn numerical_gradient(
  f : (FixedArray[Double]) -> Double,
  x : FixedArray[Double],
) -> FixedArray[Double] {
  let n = x.length()
  let grad : FixedArray[Double] = FixedArray::make(n, 0.0)
  let xp : FixedArray[Double] = FixedArray::make(n, 0.0)
  for i = 0; i < n; i = i + 1 {
    for k = 0; k < n; k = k + 1 {
      xp[k] = x[k]
    }
    let mut h = 1.0e-6 * (1.0 + x[i].abs())
    let mut iter = 0
    while iter < 20 {
      xp[i] = x[i] + h
      let f1 = f(xp)
      xp[i] = x[i] - h
      let f2 = f(xp)
      xp[i] = x[i]
      if !f1.is_nan() && !f2.is_nan() {
        grad[i] = (f1 - f2) / (2.0 * h)
        break
      }
      h = h / 16.0
      iter = iter + 1
    }
  }
  grad
}

///|
/// BFGS minimization of `f` from `x0` with gradient `grad` (verb uncmin).
/// Returns the approximate minimizer, or None if the initial value is NaN.
fn bfgs(
  f : (FixedArray[Double]) -> Double,
  grad : (FixedArray[Double]) -> FixedArray[Double],
  x0 : FixedArray[Double],
  tol? : Double = 1.0e-10,
  maxit? : Int = 200,
) -> FixedArray[Double]? {
  let n = x0.length()
  let xcur : FixedArray[Double] = FixedArray::make(n, 0.0)
  for i = 0; i < n; i = i + 1 {
    xcur[i] = x0[i]
  }
  let mut f0 = f(xcur)
  if f0.is_nan() {
    return None
  }
  let tol = if tol > 1.0e-15 { tol } else { 1.0e-15 }
  let h1 : FixedArray[Double] = FixedArray::make(n * n, 0.0)
  for i = 0; i < n; i = i + 1 {
    h1[i * n + i] = 1.0
  }
  let mut g0 = grad(xcur)
  let mut it = 0
  while it < maxit {
    let hy0 = mat_vec(h1, g0, n)
    let step : FixedArray[Double] = FixedArray::make(n, 0.0)
    for i = 0; i < n; i = i + 1 {
      step[i] = -hy0[i]
    }
    let nstep = vec_norm(step)
    if nstep < tol {
      break
    }
    let mut t = 1.0
    let df0 = vec_dot(g0, step)
    let x1 : FixedArray[Double] = FixedArray::make(n, 0.0)
    let mut f1 = f0
    // Backtracking Armijo line search.
    while it < maxit {
      if t * nstep < tol {
        break
      }
      for i = 0; i < n; i = i + 1 {
        x1[i] = xcur[i] + t * step[i]
      }
      f1 = f(x1)
      if f1 - f0 >= 0.1 * t * df0 || f1.is_nan() {
        t = t * 0.5
        it = it + 1
        continue
      }
      break
    }
    if t * nstep < tol || it >= maxit {
      break
    }
    let g1 = grad(x1)
    let s : FixedArray[Double] = FixedArray::make(n, 0.0)
    let y : FixedArray[Double] = FixedArray::make(n, 0.0)
    for i = 0; i < n; i = i + 1 {
      s[i] = t * step[i]
      y[i] = g1[i] - g0[i]
    }
    let ys = vec_dot(y, s)
    if ys.abs() < 1.0e-20 {
      break
    }
    let hy = mat_vec(h1, y, n)
    let yhy = vec_dot(y, hy)
    let coeff = (ys + yhy) / (ys * ys)
    let ss = tensor(s, s, n)
    let hy_s = tensor(hy, s, n)
    let s_hy = tensor(s, hy, n)
    for i = 0; i < n * n; i = i + 1 {
      h1[i] = h1[i] + coeff * ss[i] - (hy_s[i] + s_hy[i]) / ys
    }
    for i = 0; i < n; i = i + 1 {
      xcur[i] = x1[i]
    }
    f0 = f1
    g0 = g1
    it = it + 1
  }
  Some(xcur)
}