///|
/// Result of a seeded population search. Generations count fully completed
/// generations; evaluations include initialization and partial generations.
/// Diversity is the maximum normalized coordinate range of evaluated points
/// in the current population.
#derive(Debug)
pub(all) struct GlobalSolution {
  x : Array[Double]
  value : Double
  generations : Int32
  evaluations : Int32
  seed : UInt64
  diversity : Double
  termination : SearchTermination
}

///|
priv enum PopulationRandom {
  Moon(@random.Rand)
  Rust(@rng.RustChaCha8)
}

///|
fn PopulationRandom::double(self : PopulationRandom) -> Double {
  match self {
    Moon(random) => random.double()
    Rust(random) => random.double()
  }
}

///|
fn PopulationRandom::int(self : PopulationRandom, limit~ : Int32) -> Int32 {
  match self {
    Moon(random) => random.int(limit~)
    Rust(random) => random.int(limit~)
  }
}

///|
fn population_diversity(
  population : ArrayView[Array[Double]],
  widths : ArrayView[Double],
) -> Double {
  if population.is_empty() {
    return 0.0
  }
  let mut result = 0.0
  for j in 0.. 0.0 {
      let mut low = population[0][j]
      let mut high = low
      for point in population {
        low = low.min(point[j])
        high = high.max(point[j])
      }
      result = result.max((high - low) / widths[j])
    }
  }
  result
}

///|
fn global_result(
  run : ValueSearch,
  generations : Int32,
  seed : UInt64,
  population : ArrayView[Array[Double]],
  widths : ArrayView[Double],
  termination : SearchTermination,
) -> GlobalSolution {
  {
    x: run.best,
    value: run.best_value,
    generations,
    evaluations: run.evaluations,
    seed,
    diversity: population_diversity(population, widths),
    termination,
  }
}

///|
fn sample_population(
  random : PopulationRandom,
  lower : ArrayView[Double],
  upper : ArrayView[Double],
  widths : ArrayView[Double],
  size : Int32,
  initial : Array[Array[Double]]?,
) -> Array[Array[Double]] raise OptimizeError {
  if size > 2147483647 / widths.length() {
    raise OptimizeError::InvalidInput("population dimensions overflow")
  }
  match initial {
    Some(points) => {
      if points.length() != size {
        raise OptimizeError::InvalidInput(
          "initial population size does not match",
        )
      }
      let result = []
      for point in points {
        let _ = validate_box(point[:], lower, upper)
        result.push(point.copy())
      }
      result
    }
    None =>
      [
        for _ in 0.. {
          lower.mapi((i, low) => {
            (low + random.double() * widths[i]).clamp(min=low, max=upper[i])
          })
        }
      ]
  }
}

///|
fn population_rng(seed : UInt64, rust_compatible : Bool) -> PopulationRandom {
  if rust_compatible {
    Rust(@rng.rust_chacha8(seed))
  } else {
    let bytes = seed.to_le_bytes() + Bytes::make(24, b'\x00')
    Moon(@random.Rand::chacha8(seed=bytes))
  }
}

///|
fn random_donors(
  random : PopulationRandom,
  size : Int32,
  target : Int32,
) -> (Int32, Int32, Int32) {
  let mut a = random.int(limit=size)
  while a == target {
    a = random.int(limit=size)
  }
  let mut b = random.int(limit=size)
  while b == target || b == a {
    b = random.int(limit=size)
  }
  let mut c = random.int(limit=size)
  while c == target || c == a || c == b {
    c = random.int(limit=size)
  }
  (a, b, c)
}

///|
/// Seeded synchronous DE/rand/1/bin on a finite box. The optional initial
/// population must contain exactly `population_size` feasible points.
/// Mutants outside the box are repaired halfway between the violated bound
/// and the target. At least one crossover coordinate is forced.
///
/// The returned best point includes partial initialization and generations;
/// reaching a target does not certify a global optimum. The seed initializes
/// MoonBit's ChaCha8 generator by default. Set `rust_compatible_rng=true` to
/// use the Rust crate's seed expansion and sampling instead.
/// The optional observer can stop after any successful evaluation; cancellation
/// takes precedence over a target or budget reached at the same evaluation.
///
/// ```mbt check
/// test {
///   let result = @search.differential_evolution(
///     x => x[0] * x[0],
///     [-1.0],
///     [1.0],
///     seed=42UL,
///     max_evaluations=1000,
///     target_value=1.0e-6,
///   )
///   assert_true(result.termination is TargetReached)
/// }
/// ```
pub fn differential_evolution(
  objective : (ArrayView[Double]) -> Double raise,
  lower : ArrayView[Double],
  upper : ArrayView[Double],
  seed~ : UInt64 = 0UL,
  population_size~ : Int32 = 40,
  max_generations~ : Int32 = 1000,
  max_evaluations~ : Int32 = 10000,
  weight~ : Double = 0.8,
  crossover~ : Double = 0.9,
  rust_compatible_rng~ : Bool = false,
  initial_population? : Array[Array[Double]],
  target_value? : Double,
  observer? : (SearchEvent) -> SearchControl raise,
) -> GlobalSolution raise {
  validate_search_limits(max_generations, max_evaluations, target_value)
  if population_size < 4 ||
    !weight.is_finite() ||
    weight <= 0.0 ||
    weight > 2.0 ||
    !crossover.is_finite() ||
    crossover < 0.0 ||
    crossover > 1.0 {
    raise OptimizeError::InvalidInput("invalid differential evolution options")
  }
  let (lo, hi, widths) = validate_box(lower, lower, upper)
  let random = population_rng(seed, rust_compatible_rng)
  let mut population = sample_population(
    random,
    lo[:],
    hi[:],
    widths[:],
    population_size,
    initial_population,
  )
  let first = value_only(objective, population[0][:])
  let run : ValueSearch = {
    objective,
    max_evaluations,
    target_value,
    best: population[0].copy(),
    best_value: first,
    evaluations: 1,
    observer,
    cancelled: false,
  }
  run.observe(population[0][:], first)
  let values = [first]
  if run.stop() is Some(reason) {
    return global_result(run, 0, seed, population[:1], widths[:], reason)
  }
  for i in 1.. hi[j] {
            target[j] + 0.5 * (hi[j] - target[j])
          } else {
            mutant
          }
        }
      }
      let value = run.evaluate(trial)
      if value <= values[i] {
        next[i] = trial
        values[i] = value
      }
      if run.stop() is Some(reason) {
        let completed = if i + 1 == population_size {
          generation + 1
        } else {
          generation
        }
        return global_result(run, completed, seed, next[:], widths[:], reason)
      }
    }
    population = next
  }
  global_result(
    run,
    max_generations,
    seed,
    population[:],
    widths[:],
    MaxIterations,
  )
}