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

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

import com.google.common.collect.Range;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.IdentifiedFunction.Category;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.EvalException;
import nz.org.riskscape.engine.rl.LanguageFunctions;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;

/**
 * NB: most of these tests are the same assertions as {@link AALHazardBasedFunctionTest}
 * but are testing the scalar version of the function rather than the aggregate one.
 * I've duplicated them because it's pretty important that the AAL is calculated correctly,
 * and things like errors end up getting handled slightly different in the tests.
 */
public class AALHazardBasedFunctionScalarTest extends BaseExpressionRealizerTest {

  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("losses", RSList.create(Types.FLOATING), "probs", RSList.create(Types.FLOATING));

  @Before
  public void setup() {
    project.getFunctionSet().add(function.builtin("aal_trapz", Category.MATHS));
    project.getFunctionSet().add(LanguageFunctions.NULL_OF);
  }

  @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
    assertThat(Math.round(evaluateAAL(probabilites, 14853D, 22625D, 27153D, 34476D)), is(2063L));

    assertThat(Math.round(evaluateAAL(probabilites, 6798D, 14853D, 19550D, 27153D)), is(1279L));

    assertThat(Math.round(evaluateAAL(probabilites, 0D, 6798D, 11665D, 19550D)), is(528L));

    assertThat(Math.round(evaluateAAL(probabilites, 0D, 0D, 3496D, 11665D)), is(101L));

    assertThat(Math.round(evaluateAAL(probabilites, 0D, 0D, 0D, 3496D)), is(21L));

    assertThat(Math.round(evaluateAAL(probabilites, 0D, 0D, 0D, 0D)), 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};

    // just match against the unrounded values here
    assertThat(evaluateAAL(probabilites, 27153D, 22625D, 34476D, 14853D), closeTo(2063, 0.5));

    // reverse order
    probabilites = new Double[] {1 / 500D, 1 / 100D, 1 / 50D, 1 / 10D};
    assertThat(evaluateAAL(probabilites, 19550D, 11665D, 6798D, 0D), 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};

    // same assertion as aalMatchesJournalWorkedExample() except null instead of zero
    assertThat(evaluateAAL(probabilites, nothing, 6798D, 11665D, 19550D), closeTo(528, 0.5));
  }

  @Test
  public void nullInIsNullOut() {
    assertThat(evaluateConstant("aal_trapz(null_of('list(floating)'), [1.0, 2.0])"), nullValue());
    assertThat(realized.getResultType(), is(Nullable.FLOATING));
    assertThat(evaluateConstant("aal_trapz([1.0, 2.0], null_of('list(floating)'))"), nullValue());
    assertThat(realized.getResultType(), is(Nullable.FLOATING));
    assertThat(evaluateConstant("aal_trapz(null_of('list(floating)'), null_of('list(floating)'))"), nullValue());
    assertThat(realized.getResultType(), is(Nullable.FLOATING));
  }

  @Test
  public void failsIfArgumentsAreNotNumeric() throws Exception {
    // loss is no good
    evaluate("aal_trapz('foo', [0.1, 0.2, 0.3])", Tuple.EMPTY_TUPLE);
    assertThat(realizationProblems, contains(hasAncestorProblem(
        is(TypeProblems.get().mismatch(scalarArg("loss"),
          RSList.create(Types.FLOATING),
          Types.TEXT))
    )));

    // EP is no good - we don't allow nullable probabilities
    evaluate("aal_trapz([1,2,3], [0.1, null, 0.3])", Tuple.EMPTY_TUPLE);
    assertThat(realizationProblems, contains(hasAncestorProblem(
        is(TypeProblems.get().mismatch(scalarArg("ep"),
          RSList.create(Types.FLOATING),
          RSList.create(Nullable.FLOATING)))
    )));

    // args are required
    evaluate("aal_trapz([100, 200, 300])", Tuple.EMPTY_TUPLE);
    assertThat(realizationProblems, contains(hasAncestorProblem(
        is(ArgsProblems.get().wrongNumber(2, 1))
    )));
  }

  @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};
    // note that CannotFitCurveException gets wrapped in an EvalException by the ExpressionRealizer
    RiskscapeException ex = assertThrows(EvalException.class,
        () -> evaluateAAL(hasNegativeProbability, 0D, 6798D, 11665D, 19550D));
    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};
    ex = assertThrows(EvalException.class, () -> evaluateAAL(probabilityTooBig, 0D, 6798D, 11665D, 19550D));
    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
    RiskscapeException ex = assertThrows(EvalException.class,
        () -> evaluateAAL(DEFAULT_PROBABILITIES, -0.5, 0D, 6798D, 11665D, 19550D));
    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
    assertThat(evaluateAAL(DEFAULT_PROBABILITIES, 0.99, 0.99, 0.99, 0.99, 0.99), 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};

    RiskscapeException ex = assertThrows(EvalException.class,
        () -> evaluateAAL(probabilitiesWithDup, 10000D, 20000D, 50000D, 100000D));
    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
    RiskscapeException ex = assertThrows(EvalException.class,
        () -> evaluate("aal_trapz([100], [0.1])", Tuple.EMPTY_TUPLE));
    assertThat(ex.getProblem(), hasAncestorProblem(
        is(AALHazardBasedFunction.PROBLEMS.tooFewEvents(1, 3))
    ));

    ex = assertThrows(EvalException.class,
        () -> evaluate("aal_trapz([100, 200], [0.1, 0.2])", Tuple.EMPTY_TUPLE));
    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
    assertThat(evaluateAAL(DEFAULT_PROBABILITIES, 100000D, 200000D, 300000D, 400000D, 500000D),
        closeTo(4320.0, 0.0001));

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

    assertThat(evaluateAAL(DEFAULT_PROBABILITIES, 300000D, 400000D, 500000D, 500000D, 500000D),
        closeTo(8100.0, 0.0001));

    assertThat(evaluateAAL(DEFAULT_PROBABILITIES, 400000D, 500000D, 500000D, 500000D, 500000D),
        closeTo(9500.0, 0.0001));
  }

  // this one is scalar-specific:
  @Test
  public void failsIfListsAreDifferentSizes() throws Exception {
    RiskscapeException ex = assertThrows(EvalException.class,
        () -> evaluate("aal_trapz([100, 200, 300, 400], [0.1, 0.2, 0.3])", Tuple.EMPTY_TUPLE));
    assertThat(ex.getProblem(), hasAncestorProblem(
        is(GeneralProblems.get().differentListLengths(scalarArg("loss"), 4, scalarArg("ep"), 3))
    ));
    ex = assertThrows(EvalException.class,
        () -> evaluate("aal_trapz([100, 200, 300], [0.1, 0.2, 0.3, 0.4])", Tuple.EMPTY_TUPLE));
    assertThat(ex.getProblem(), hasAncestorProblem(
        is(GeneralProblems.get().differentListLengths(scalarArg("loss"), 3, scalarArg("ep"), 4))
    ));
  }

  private FunctionArgument scalarArg(String name) {
    return AALHazardBasedFunction.SCALAR_ARGUMENTS.get(name);
  }

  private double evaluateAAL(Double[] probabilities, Double... losses) {
    Tuple input = Tuple.ofValues(inputType, Arrays.asList(losses), Arrays.asList(probabilities));
    return (double) evaluate("aal_trapz(losses, probs)", input);
  }
}
