/*
 * 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 static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.IntStream;

import org.junit.Test;

import com.google.common.collect.Maps;

import nz.org.riskscape.engine.RandomSingleton;

public class RandomUtilsTest {

  /**
   * Helper to build up a frequency hashmap of the results we got
   */
  private void countResult(Object val, Map<Object, Integer> results) {
    Integer count = results.get(val);
    if (count == null) {
      results.put(val, 1);
    } else {
      results.put(val, count + 1);
    }
  }

  @Test
  public void canPickFromList() throws Exception {
    // set the random seed so that outlier results don't cause a flappy test
    RandomSingleton.setSeed(1000);
    Map<Object, Integer> results = Maps.newHashMap();

    // sample 1000 times using pick() from list of 10 items
    String[] items = new String[] {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"};
    for (int i = 0; i < 1000; i++) {
      countResult(RandomUtils.pick(Arrays.asList(items)), results);
    }

    // check that we saw every possible option roughly 100 times (+/- 25)
    for (String val : items) {
      assertThat(results.get(val), allOf(greaterThanOrEqualTo(75), lessThanOrEqualTo(125)));
    }
  }

  @Test
  public void canPickFromListConsistentlyWithGlobalSeed() throws Exception {
    List<String> items = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");

    // set the seed and pick 100 items
    List<Object> picked1 = new ArrayList<>(100);
    RandomSingleton.setSeed(1);
    IntStream.range(0, 100).forEach(x -> picked1.add(RandomUtils.pick(items)));

    // repeat with the same seed and we should get the same items back again
    List<Object> picked2 = new ArrayList<>(100);
    RandomSingleton.setSeed(1);
    IntStream.range(0, 100).forEach(x -> picked2.add(RandomUtils.pick(items)));
    assertEquals(picked1, picked2);

    // set a different seed and we should get different items this time
    List<Object> picked3 = new ArrayList<>(100);
    RandomSingleton.setSeed(2);
    IntStream.range(0, 100).forEach(x -> picked2.add(RandomUtils.pick(items)));
    assertNotEquals(picked1, picked3);
  }

  @Test
  public void canPickFromListConsistentlyWithLocalSeed() throws Exception {
    List<String> items = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");

    // set the global seed and pick 100 items
    List<Object> pickedWithGlobalSeed = new ArrayList<>(100);
    RandomSingleton.setSeed(1000);
    IntStream.range(0, 100).forEach(x -> pickedWithGlobalSeed.add(RandomUtils.pick(items)));

    // even if we use the same global seed, the local seed should trump this and pick different items
    RandomSingleton.setSeed(1000);
    List<Object> pickedWithLocalSeed1 = new ArrayList<>(100);
    IntStream.range(0, 100).forEach(seed ->
      pickedWithLocalSeed1.add(RandomUtils.pick(items, Optional.of((long) seed))));
    assertNotEquals(pickedWithGlobalSeed, pickedWithLocalSeed1);

    // using the same local seeds again should return the same items
    RandomSingleton.setSeed(1000);
    List<Object> pickedWithLocalSeed2 = new ArrayList<>(100);
    IntStream.range(0, 100).forEach(seed ->
      pickedWithLocalSeed2.add(RandomUtils.pick(items, Optional.of((long) seed))));
    assertEquals(pickedWithLocalSeed1, pickedWithLocalSeed2);

    // set a different local seed and we should get different items
    RandomSingleton.setSeed(1000);
    List<Object> pickedWithLocalSeed3 = new ArrayList<>(100);
    IntStream.range(0, 100)
        .forEach(seed -> pickedWithLocalSeed3.add(RandomUtils.pick(items, Optional.of((long) seed + 1000))));
    assertNotEquals(pickedWithLocalSeed3, pickedWithLocalSeed2);
    assertNotEquals(pickedWithLocalSeed3, pickedWithGlobalSeed);
  }

  @Test
  public void canInfluenceLocalSeedWithGlobalSeed() throws Exception {
    List<String> items = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");

    // we still want to be able to 'toggle' the randomness with the global seed
    // (otherwise the model will only ever show us the same randomness result)
    RandomSingleton.setSeed(1000);
    List<Object> pickedWithLocalSeed1 = new ArrayList<>(100);
    IntStream.range(0, 100).forEach(seed ->
      pickedWithLocalSeed1.add(RandomUtils.pick(items, Optional.of((long) seed))));

    // change the global seed, but use the same local seed
    RandomSingleton.setSeed(2000);
    List<Object> pickedWithLocalSeed2 = new ArrayList<>(100);
    IntStream.range(0, 100).forEach(seed ->
      pickedWithLocalSeed2.add(RandomUtils.pick(items, Optional.of((long) seed))));
    // we want a slightly different 'picture' of randomness, so the items should differ
    assertNotEquals(pickedWithLocalSeed1, pickedWithLocalSeed2);

    // but if we use the same global and local seed, we always get the same items
    RandomSingleton.setSeed(2000);
    List<Object> pickedWithLocalSeed3 = new ArrayList<>(100);
    IntStream.range(0, 100)
        .forEach(seed -> pickedWithLocalSeed3.add(RandomUtils.pick(items, Optional.of((long) seed))));
    assertEquals(pickedWithLocalSeed3, pickedWithLocalSeed2);
    assertNotEquals(pickedWithLocalSeed3, pickedWithLocalSeed1);
  }

  @Test
  public void canPickFromWeightedList() throws Exception {
    RandomSingleton.setSeed(5000);
    Map<Object, Integer> results = Maps.newHashMap();

    // sample 1000 times using pick() from list of 10 items
    String[] items = new String[] {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"};
    // note that the weighting can be any number - here we use the approx number
    // of times we expect the item to be selected (out of 1000)
    Double[] weights = new Double[] {200.0, 150.0, 20.0, 100.0, 160.0, 90.0, 40.0, 80.0, 60.0, 100.0};
    for (int i = 0; i < 1000; i++) {
      Object val = RandomUtils.pick(Arrays.asList(items), Arrays.asList(weights));
      countResult(val, results);
    }

    // check that we saw every possible option the expected number of times (+/- 20)
    for (int i = 0; i < items.length; i++) {
      String val = items[i];
      int expected = weights[i].intValue();
      assertThat(results.get(val),
          allOf(greaterThanOrEqualTo(expected - 20), lessThanOrEqualTo(expected + 20)));
    }
  }

  @Test
  public void canPickFromWeightedListConsistentlyWithSeed() throws Exception {
    List<String> items = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");
    List<Double> weights = Arrays.asList(200.0, 150.0, 20.0, 100.0, 160.0, 90.0, 40.0, 80.0, 60.0, 100.0);

    // set the global seed and pick 100 items
    List<Object> pickedWithGlobalSeed = new ArrayList<>(100);
    RandomSingleton.setSeed(1000);
    IntStream.range(0, 100).forEach(x -> pickedWithGlobalSeed.add(RandomUtils.pick(items, weights)));

    // even if we use the same global seed, the local seed should trump this and
    // pick different items
    RandomSingleton.setSeed(1000);
    List<Object> pickedWithLocalSeed1 = new ArrayList<>(100);
    IntStream.range(0, 100).forEach(seed ->
      pickedWithLocalSeed1.add(RandomUtils.pick(items, weights, Optional.of((long) seed))));
    assertNotEquals(pickedWithGlobalSeed, pickedWithLocalSeed1);

    // using the same local seeds again should return the same items
    RandomSingleton.setSeed(1000);
    List<Object> pickedWithLocalSeed2 = new ArrayList<>(100);
    IntStream.range(0, 100).forEach(seed ->
      pickedWithLocalSeed2.add(RandomUtils.pick(items, weights, Optional.of((long) seed))));
    assertEquals(pickedWithLocalSeed1, pickedWithLocalSeed2);
  }

  @Test
  public void canSampleFromRange() throws Exception {
    RandomSingleton.setSeed(200);

    // take 1000 samples between and check they're in the expected range
    double total = 0;
    for (int i = 0; i < 1000; i++) {
      double sample = RandomUtils.getFromRange(100, 1100);
      assertThat(sample, allOf(greaterThanOrEqualTo(100.0), lessThanOrEqualTo(1100.0)));
      total += sample;
    }

    // the overall average for our samples should be approx the mid-point (600) +/25
    assertThat(total / 1000, allOf(greaterThanOrEqualTo(575.0), lessThanOrEqualTo(625.0)));
  }

  @Test
  public void canSampleFromRangeConsistentlyWithSeed() throws Exception {
    // set the global seed and pick 100 items
    List<Double> pickedWithGlobalSeed = new ArrayList<>(100);
    RandomSingleton.setSeed(1000);
    IntStream.range(0, 100).forEach(x -> pickedWithGlobalSeed.add(RandomUtils.getFromRange(0, 1000)));

    // even if we use the same global seed, the local seed should trump this and
    // pick different items
    RandomSingleton.setSeed(1000);
    List<Double> pickedWithLocalSeed1 = RandomUtils.getFromRange(0, 1000, Optional.of(2000L), 100);
    assertNotEquals(pickedWithGlobalSeed, pickedWithLocalSeed1);

    // using the same local seeds again should return the same items
    RandomSingleton.setSeed(1000);
    List<Double> pickedWithLocalSeed2 = RandomUtils.getFromRange(0, 1000, Optional.of(2000L), 100);
    assertEquals(pickedWithLocalSeed1, pickedWithLocalSeed2);

    // but a different local seed will produce different results
    RandomSingleton.setSeed(1000);
    List<Double> pickedWithLocalSeed3 = RandomUtils.getFromRange(0, 1000, Optional.of(3000L), 100);
    assertNotEquals(pickedWithLocalSeed3, pickedWithLocalSeed2);
  }

  @Test
  public void canSampleIntegerFromRange() throws Exception {
    RandomSingleton.setSeed(100);
    Map<Object, Integer> results = Maps.newHashMap();

    // here we use round() to pick an integer from the range 101 to 110.
    // Dealing in integers makes it easier to build up a frequency count.
    // However, because we're rounding from a double, our start/end-points need to
    // be expanded by 0.5, otherwise the end-points only get half as much chance
    // of being selected as the other numbers
    for (int i = 0; i < 1000; i++) {
      double sample = RandomUtils.getFromRange(100.5, 110.49);
      assertThat(sample, allOf(greaterThanOrEqualTo(100.5), lessThanOrEqualTo(110.49)));
      countResult(Math.round(sample), results);
    }

    // check that we saw every possible option roughly 100 times (+/- 20)
    for (long i = 101; i <= 110; i++) {
      assertThat(results.get(i), allOf(greaterThanOrEqualTo(80), lessThanOrEqualTo(120)));
    }
  }

  @Test
  public void canSampleFromNormalDist() throws Exception {
    RandomSingleton.setSeed(200);
    Map<Object, Integer> results = Maps.newHashMap();

    // take 1000 (rounded) samples with mean=10, stddev=1.5
    for (int i = 0; i < 1000; i++) {
      double sample = RandomUtils.getNormalVariate(10, 1.5);
      countResult(Math.round(sample), results);
    }

    // one stddev either side of the mean (i.e. 8.5-11.5 rounded) should account
    // for 68% of the samples (680 +/- 20)
    assertThat(results.get(9L) + results.get(10L) + results.get(11L),
        allOf(greaterThanOrEqualTo(660), lessThanOrEqualTo(700)));

    // the next 2 stddevs in either direction should each account for 16% (160 +/- 20)
    assertThat(results.get(6L) + results.get(7L) + results.get(8L),
        allOf(greaterThanOrEqualTo(140), lessThanOrEqualTo(180)));
    assertThat(results.get(12L) + results.get(13L) + results.get(14L),
        allOf(greaterThanOrEqualTo(140), lessThanOrEqualTo(180)));
  }

  @Test
  public void canSampleFromNormalDistConsistentlyWithSeed() throws Exception {
    // set the global seed and pick 100 items
    List<Double> pickedWithGlobalSeed = new ArrayList<>(100);
    RandomSingleton.setSeed(1000);
    IntStream.range(0, 100).forEach(x -> pickedWithGlobalSeed.add(RandomUtils.getNormalVariate(0, 1)));

    // even if we use the same global seed, the local seed should trump this and
    // pick different items
    RandomSingleton.setSeed(1000);
    List<Double> pickedWithLocalSeed1 = RandomUtils.getNormalVariate(0, 1, Optional.of(2000L), 100);
    assertNotEquals(pickedWithGlobalSeed, pickedWithLocalSeed1);

    // using the same local seeds again should return the same items
    RandomSingleton.setSeed(1000);
    List<Double> pickedWithLocalSeed2 = RandomUtils.getNormalVariate(0, 1, Optional.of(2000L), 100);
    assertEquals(pickedWithLocalSeed1, pickedWithLocalSeed2);
  }

  @Test
  public void consecutiveSeedsStillProducesRandomResults() throws Exception {
    RandomSingleton.setSeed(200);
    Map<Object, Integer> results = Maps.newHashMap();

    // take 1000 (rounded) samples with mean=10, stddev=1.5
    for (long i = 0; i < 1000; i++) {
      double sample = RandomUtils.getNormalVariate(10, 1.5, Optional.of(i), 1).get(0);
      countResult(Math.round(sample), results);
    }

    // one stddev either side of the mean (i.e. 8.5-11.5 rounded) should account
    // for 68% of the samples (680 +/- 20)
    assertThat(results.get(9L) + results.get(10L) + results.get(11L),
        allOf(greaterThanOrEqualTo(660), lessThanOrEqualTo(700)));

    // the next 2 stddevs in either direction should each account for 16% (160 +/- 20)
    assertThat(results.get(6L) + results.get(7L) + results.get(8L),
        allOf(greaterThanOrEqualTo(140), lessThanOrEqualTo(180)));
    assertThat(results.get(12L) + results.get(13L) + results.get(14L),
        allOf(greaterThanOrEqualTo(140), lessThanOrEqualTo(180)));
  }
}
