/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.engine.util;

import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import java.util.Random;

import nz.org.riskscape.engine.RandomSingleton;

/**
 * Helper functions for generating random numbers or sampling from random
 * distributions.
 */
public class RandomUtils {

  /**
   * Randomly selects a value from a normal distribution with the given mean and
   * standard deviation. This means that values closer to the mean have a higher
   * likelihood of being selected.
   */
  public static List<Double> getNormalVariate(double mean, double stddev, Optional<Long> seed, int numSamples) {
    // nextGaussian() samples a standard normal distribution (mean=0, stddev=1).
    // We can convert the standard normal distribution to any normal distribution by
    // multiplying by the stddev and adding the mean. (Note that converting from a normal
    // distribution to the standard normal is something that's done all the time - here
    // we're just going in the opposite direction).
    Random rng = RandomSingleton.get(seed);
    return IntStream.range(0, numSamples)
        .mapToDouble(i -> stddev * rng.nextGaussian() + mean)
        .boxed()
        .toList();
  }

  public static double getNormalVariate(double mean, double stddev) {
    return getNormalVariate(mean, stddev, Optional.empty(), 1).get(0);
  }
  /**
   * Randomly selects a value from the given range. Assumes values are uniformly
   * distributed. The range is from start (inclusive) to stop (exclusive).
   */
  public static List<Double> getFromRange(double start, double stop, Optional<Long> seed, int numSamples) {
    // nextDouble() samples from the range [0, 1.0]. We then scale this
    // out to fit the given range, e.g. 0.5 for range 0-100 results in 50
    Random rng = RandomSingleton.get(seed);
    return IntStream.range(0, numSamples)
        .mapToDouble(i -> start + (stop - start) * rng.nextDouble())
        .boxed()
        .toList();
  }

  public static double getFromRange(double start, double stop) {
    return getFromRange(start, stop, Optional.empty(), 1).get(0);
  }

  /**
   * Picks an item based on a weighted random choice.
   * @param items   the items to choose from
   * @param weights the weighted probabilities
   */
  public static Object pick(List<?> items, List<Double> weights, Optional<Long> seed) {
    if (weights.size() != items.size()) {
      throw new IllegalArgumentException("'items' and 'weights' lists must be the same size");
    }

    // total up the weights, then pick a random number between 0..totalWeight
    double totalWeight = weights.stream().mapToDouble(val -> val).sum();
    double randomWeight = RandomSingleton.get(seed).nextDouble() * totalWeight;

    // now go through the items until we match or exceed the random weighting
    double currentWeight = 0;
    for (int i = 0; i < items.size(); i++) {
      currentWeight += weights.get(i);
      if (currentWeight >= randomWeight) {
        return items.get(i);
      }
    }
    // shouldn't hit this unless list is empty
    return null;
  }

  public static Object pick(List<?> items, List<Double> weights) {
    return pick(items, weights, Optional.empty());
  }

  /**
   * Picks an item randomly from the given list.
   */
  public static Object pick(List<?> items, Optional<Long> seed) {
    if (items.isEmpty()) {
      return null;
    }
    int randomIndex = RandomSingleton.get(seed).nextInt(items.size());
    return items.get(randomIndex);
  }

  public static Object pick(List<?> items) {
    return pick(items, Optional.empty());
  }
}
