/*
 * 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.defaults.function;

import static nz.org.riskscape.engine.Assert.*;
import static nz.org.riskscape.engine.Matchers.*;
import static nz.org.riskscape.engine.problem.ProblemMatchers.isProblem;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import com.google.common.collect.Range;

import nz.org.riskscape.defaults.curves.CannotFitCurveException;
import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.IdentifiedFunction.Category;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.rl.agg.BaseAggregationFunctionTest;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;

public class AALHazardBasedFunctionTest extends BaseAggregationFunctionTest {

  public static final Double[] DEFAULT_PROBABILITIES = new Double[] {0.02, 0.01, 0.002, 0.001, 0.0004};

  AALHazardBasedFunction function = new AALHazardBasedFunction();
  Struct inputType = Struct.of("loss", Types.FLOATING, "probability", Types.FLOATING);

  @Before
  public void setup() {
    project.getFunctionSet().add(function.builtin("aal_trapz", Category.MATHS));
    assertSerialAndParallelEqual = false;
    realizeAggregate(inputType, functionCall("aal_trapz(loss: loss, ep: probability)"));
  }

  @Test
  public void aalMatchesJournalWorkedExample() {
    // this is the worked example (Supplementary Material) from:
    // https://www.frontiersin.org/articles/10.3389/frwa.2022.919726/full
    // note that the article uses 1/RP for the probability
    Double[] probabilites = new Double[] {1 / 10D, 1 / 50D, 1 / 100D, 1 / 500D};

    // note that the journal results are rounded to the nearest dollar amount
    realizeAggregate(inputType, functionCall("round(aal_trapz(loss: loss, ep: probability))"));
    tuples = eventData(probabilites, 14853D, 22625D, 27153D, 34476D);
    assertThat((Long) process(), is(2063L));

    tuples = eventData(probabilites, 6798D, 14853D, 19550D, 27153D);
    assertThat((Long) process(), is(1279L));

    tuples = eventData(probabilites, 0D, 6798D, 11665D, 19550D);
    assertThat((Long) process(), is(528L));

    tuples = eventData(probabilites, 0D, 0D, 3496D, 11665D);
    assertThat((Long) process(), is(101L));

    tuples = eventData(probabilites, 0D, 0D, 0D, 3496D);
    assertThat((Long) process(), is(21L));

    tuples = eventData(probabilites, 0D, 0D, 0D, 0D);
    assertThat((Long) process(), is(0L));
  }

  @Test
  public void orderOfEventsDoesNotAffectAAL() {
    // same data as aalMatchesJournalWorkedExample(), but mix up the event order
    Double[] probabilites = new Double[] {1 / 100D, 1 / 50D, 1 / 500D, 1 / 10D};
    tuples = eventData(probabilites, 27153D, 22625D, 34476D, 14853D);
    // just match against the unrounded values here
    assertThat((Double) process(), closeTo(2063, 0.5));

    // reverse order
    probabilites = new Double[] {1 / 500D, 1 / 100D, 1 / 50D, 1 / 10D};
    tuples = eventData(probabilites, 19550D, 11665D, 6798D, 0D);
    assertThat((Double) process(), closeTo(528, 0.5));
  }

  @Test
  public void nullLossValuesGetTreatedAsZero() {
    // we can't ignore a null loss because it ignores the whole area under the curve between that datapoint
    // and the next one. Because we know it's a loss value, we can infer that null means $0
    Double nothing = null;
    Double[] probabilites = new Double[] {1 / 10D, 1 / 50D, 1 / 100D, 1 / 500D};
    inputType = Struct.of("loss", Nullable.FLOATING, "probability", Types.FLOATING);
    realizeAggregate(inputType, functionCall("aal_trapz(loss: loss, ep: probability)"));
    // same assertion as aalMatchesJournalWorkedExample() except null instead of zero
    tuples = eventData(probabilites, nothing, 6798D, 11665D, 19550D);
    assertThat((Double) process(), closeTo(528, 0.5));
  }

  @Test
  public void failsIfArgumentsAreNotNumeric() throws Exception {
    // loss is no good
    inputType = Struct.of("loss", Types.TEXT, "probability", Types.INTEGER);
    realizeAggregate(inputType, functionCall("aal_trapz(loss: loss, ep: probability)"));
    assertThat(realizationProblems, contains(hasAncestorProblem(
        is(TypeProblems.get().mismatch(function.getArguments().get("loss"),
          Types.FLOATING,
            Types.TEXT))
    )));

    // EP is no good - we don't allow nullable probabilities
    inputType = Struct.of("loss", Nullable.of(Types.DECIMAL), "probability", Nullable.FLOATING);
    realizeAggregate(inputType, functionCall("aal_trapz(loss: loss, ep: probability)"));
    assertThat(realizationProblems, contains(hasAncestorProblem(
        is(TypeProblems.get().mismatch(function.getArguments().get("ep"),
          Types.FLOATING,
          Nullable.FLOATING))
    )));

    // args are required
    inputType = Struct.of("loss", Types.FLOATING);
    realizeAggregate(inputType, functionCall("aal_trapz(loss: loss)"));
    assertThat(realizationProblems, contains(hasAncestorProblem(
        is(ArgsProblems.get().required("ep"))
    )));

    inputType = Struct.of("probability", Types.FLOATING);
    realizeAggregate(inputType, functionCall("aal_trapz(ep: probability)"));
    assertThat(realizationProblems, contains(hasAncestorProblem(
      is(ArgsProblems.get().required("loss"))
    )));
  }

  @Test
  public void probabilityValuesMustBeBetweenZeroAndOne() {
    // sanity-check the probability is 0.0-1.0. Anything else indicates screwy data
    // and will likely lead to a bad AAL result
    Double[] hasNegativeProbability = new Double[] {1 / 10D, 1 / 50D, -1 / 100D, 1 / 500D};
    tuples = eventData(hasNegativeProbability, 0D, 6798D, 11665D, 19550D);
    RiskscapeException ex = assertThrows(CannotFitCurveException.class, () -> process());
    assertThat(ex.getProblem(), hasAncestorProblem(isProblem(GeneralProblems.class,
            (r, gp) -> gp.badValue(r.eq(-1 / 100D), r.any(), r.eq(AALHazardBasedFunction.PROBABILITY_RANGE)))
    ));

    // e.g. if user accidentally switched loss/EP args or uses RP directly instead of EP
    Double[] probabilityTooBig = new Double[] {10D, 50D, -100D, 500D};
    tuples = eventData(probabilityTooBig, 0D, 6798D, 11665D, 19550D);
    ex = assertThrows(CannotFitCurveException.class, () -> process());
    assertThat(ex.getProblem(), hasAncestorProblem(isProblem(GeneralProblems.class,
        (r, gp) -> gp.badValue(r.eq(10D), r.any(), r.eq(AALHazardBasedFunction.PROBABILITY_RANGE)))));
  }

  @Test
  public void lossValuesCannotBeNegative() {
    // mixing negative and positive loss values may screw up the AAL, so assume loss is always >= 0
    tuples = eventData(DEFAULT_PROBABILITIES, -0.5, 0D, 6798D, 11665D, 19550D);
    RiskscapeException ex = assertThrows(CannotFitCurveException.class, () -> process());
    assertThat(ex.getProblem(), hasAncestorProblem(isProblem(GeneralProblems.class,
            (r, gp) -> gp.badValue(r.eq(-0.5), r.any(), r.eq(Range.atLeast(0))))
    ));
  }

  @Test
  public void theSameLossValueCanBeRepeated() {
    // if the same loss value occurs multiple times, we should still get a sane AAL
    // this is a realistic example where the FR for tsunami tops out pretty quickly
    tuples = eventData(DEFAULT_PROBABILITIES, 0.99, 0.99, 0.99, 0.99, 0.99);
    assertThat((Double) process(), closeTo(0.0198, 0.0000001));
  }

  @Test
  public void theSameProbabilityCannotBeRepeated() {
    // we should throw an error if there's multiple different events with the same probability.
    // It will produce an inconsistent/bad AAL and it probably indicates a mistake in the
    // event/input data somewhere, e.g. duplicate buildings for a per-building AAL
    Double[] probabilitiesWithDup = new Double[] {1 / 10D, 1 / 50D, 1 / 100D, 1 / 100D};
    tuples = eventData(probabilitiesWithDup, 10000D, 20000D, 50000D, 100000D);

    RiskscapeException ex = assertThrows(CannotFitCurveException.class, () -> process());
    assertThat(ex.getProblem(), hasAncestorProblem(
        is(AALHazardBasedFunction.PROBLEMS.duplicateProbability(1 / 100D))
    ));
  }

  @Test
  public void getErrorIfTooFewAALDatapoints() {
    // NB: we don't want the pipeline to filter out any zero losses before aal_trapz() gets called,
    // because that removes data-points so there would be less total area under the curve.
    // Throwing an error makes that inadvertent mistake more obvious
    tuples = Collections.emptyList();
    RiskscapeException ex = assertThrows(CannotFitCurveException.class, () -> process());
    assertThat(ex.getProblem(), hasAncestorProblem(
        is(AALHazardBasedFunction.PROBLEMS.tooFewEvents(0, 3))
    ));

    tuples = eventData(new Double[] {1 / 10D, 1 / 50D}, 10000D, 20000D);
    ex = assertThrows(CannotFitCurveException.class, () -> process());
    assertThat(ex.getProblem(), hasAncestorProblem(
        is(AALHazardBasedFunction.PROBLEMS.tooFewEvents(2, 3))
    ));
  }

  @Test
  public void increasingLossesShouldProduceALargerAAL() {
    // as the losses go up, so should the AAL. But this example actually used to
    // produce *smaller* AALs under the old way of doing things
    tuples = eventData(DEFAULT_PROBABILITIES, 100000D, 200000D, 300000D, 400000D, 500000D);
    assertThat((Double) process(), closeTo(4320.0, 0.0001));

    tuples = eventData(DEFAULT_PROBABILITIES, 200000D, 300000D, 400000D, 500000D, 500000D);
    // this should be a bigger AAL than last one
    assertThat((Double) process(), closeTo(6250.0, 0.0001));

    tuples = eventData(DEFAULT_PROBABILITIES, 300000D, 400000D, 500000D, 500000D, 500000D);
    assertThat((Double) process(), closeTo(8100.0, 0.0001));

    tuples = eventData(DEFAULT_PROBABILITIES, 400000D, 500000D, 500000D, 500000D, 500000D);
    assertThat((Double) process(), closeTo(9500.0, 0.0001));
  }

  @Test
  public void aalNotInfluencedBySteepnessOfLossCurve() {
    // another example where the old AAL approach would produce weird results
    // the second event clearly has larger losses, so should have a higher AAL
    // but because the 2nd event had a steeper loss/EP curve at the high probability end,
    // there was less area under the curve so we'd actually get a lower AAL
    Double[] probabilities = new Double[] {0.1813, 0.0952, 0.0392, 0.0198, 0.01, 0.004};
    tuples = eventData(probabilities, 1411D, 1437D, 1597D, 1787D, 1859D, 1866D);
    assertThat((Double) process(), closeTo(276.8876, 0.0001));

    tuples = eventData(probabilities, 1829D, 1855D, 1887D, 1926D, 2099D, 2174D);
    assertThat((Double) process(), closeTo(341.5958, 0.0001));
  }

  private List<Tuple> eventData(Double[] probabilities, Double... losses) {
    List<Tuple> events = new ArrayList<>();
    for (int i = 0; i < probabilities.length; i++) {
      events.add(Tuple.ofValues(inputType, losses[i], probabilities[i]));
    }
    return events;
  }

}
