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

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

import java.util.List;

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.Assert;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.defaults.function.LookupBookmark;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.DefaultOperators;
import nz.org.riskscape.engine.rl.LanguageFunctions;
import nz.org.riskscape.engine.rl.LogicFunctions;
import nz.org.riskscape.engine.rl.MathsFunctions;
import nz.org.riskscape.engine.rl.RealizableFunction;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;

public class ToContinuousCurveTest extends BaseExpressionRealizerTest {

  Struct applyCurveType;
  RealizedExpression applyCurve;
  Tuple applyCurveInput;
  NonStackableLinearContinuousFunctionType curveType;
  Object curveFunction;
  Tuple scope = Tuple.EMPTY_TUPLE;

  public ToContinuousCurveTest() {
    project.getFunctionSet().insertFirst(DefaultOperators.INSTANCE);
    project.getFunctionSet().addAll(LanguageFunctions.FUNCTIONS);
    project.getFunctionSet().addAll(LogicFunctions.LOGIC_FUNCTIONS);
    project.getFunctionSet().addAll(MathsFunctions.FUNCTIONS);
    project.getFunctionSet().add(new ToContinuousCurve().identified("to_continuous_curve"));

    LookupBookmark lookupBookmark = new LookupBookmark();
    project.getFunctionSet().add(RealizableFunction.asFunction(lookupBookmark, lookupBookmark.getArguments(),
        Types.ANYTHING).identified("bookmark"));

    project.getFunctionSet().add(new ApplyContinuousFunction().asFunction().identified("apply_continuous"));
  }

  List<Tuple> tuples = tuples("[{x:0, y:0},{x:100, y:100}]");
  ListRelation relation = new ListRelation(tuples);

  @Before
  public void setup() {
    // allow it to be called twice
    project.getBookmarks().remove("relation");

    relation = new ListRelation(tuples);
    addPickledData("relation", relation);
  }

  @Test
  public void canInterpolateBetweenTwoValuesFromASimpleListOfNumbers() {
    buildCurve("to_continuous_curve([0, 1, 2, 3, 4], x -> x, x -> x * 2 + 1)");

    assertThat(applyCurve(0), is(1D));
  }

  @Test
  public void returnsLowerOrUpperBoundIfOutsideOfXRange() throws Exception {
    buildCurve("to_continuous_curve([2, 4], x -> x, x -> x)");

    assertThat(applyCurve(0), is(2D));
    assertThat(applyCurve(1.9D), is(2D));
    assertThat(applyCurve(2), is(2D));
    assertThat(applyCurve(3.9D), is(3.9D));
    assertThat(applyCurve(4), is(4D));
    assertThat(applyCurve(4.1), is(4D));
  }

  @Test
  public void returnsASinglePointForASingleValue() throws Exception {
    buildCurve("to_continuous_curve([3], x -> x, x -> x)");

    assertThat(applyCurve(0), is(3D));
    assertThat(applyCurve(1.9D), is(3D));
    assertThat(applyCurve(2), is(3D));
    assertThat(applyCurve(3.9D), is(3D));
    assertThat(applyCurve(4), is(3D));
    assertThat(applyCurve(4.1), is(3D));
  }

  @Test
  public void returnsASinglePointForASingleStructValue() throws Exception {
    buildCurve("to_continuous_curve([3], x -> x, x -> {x})");

    // this test is important in that it confirms that the coercion works
    assertThat(applyCurve(0), is(tuple("{x: 3.0}")));
  }

  @Test
  public void canInterpolateBetweenTwoValuesInABookmark() {
    buildCurve("to_continuous_curve(bookmark('relation'), row -> row.x, row -> row.y)");
    assertThat(applyCurve(-10D), is(0D));
    assertThat(applyCurve(0D), is(0D));
    assertThat(applyCurve(50D), is(50D));
    assertThat(applyCurve(100D), is(100D));
    assertThat(applyCurve(10000D), is(100D));
  }

  @Test
  public void canInterpolateBetweenTwoValuesFromList() {
    buildCurve("to_continuous_curve([{x:0, y:0},{x:100, y:100}], row -> row.x, row -> row.y)");
    assertThat(applyCurve(-10D), is(0D));
    assertThat(applyCurve(0D), is(0D));
    assertThat(applyCurve(50D), is(50D));
    assertThat(applyCurve(100D), is(100D));
    assertThat(applyCurve(10000D), is(100D));
  }

  @Test
  public void xValuesDoNotNeedToBePreSorted() {
    buildCurve("to_continuous_curve([{x:0, y:0},{x: 200, y: 400},{x:100, y:200}], row -> row.x, row -> row.y)");
    assertThat(applyCurve(-10D), is(0D));
    assertThat(applyCurve(0D), is(0D));
    assertThat(applyCurve(50D), is(100D));
    assertThat(applyCurve(100D), is(200D));
    assertThat(applyCurve(150D), is(300D));
    assertThat(applyCurve(10000D), is(400D));
  }


  @Test
  public void canInterpolateBetweenTwoValuesFromListWithNullXMembers() {
    buildCurve("to_continuous_curve([{x:0, y:0},{x:null_of('integer'), y:100},{x:100, y:100},"
        + "{x: 200, y: null_of('integer')}], row -> row.x, row -> row.y)");

    // same as before - the nulls are ignored
    assertThat(applyCurve(-10D), is(0D));
    assertThat(applyCurve(0D), is(0D));
    assertThat(applyCurve(50D), is(50D));
    assertThat(applyCurve(100D), is(100D));
    assertThat(applyCurve(10000D), is(100D));
  }

  @Test
  public void canInterpolateAStructOfNumbers() {
    buildCurve("to_continuous_curve([{x:0, a: 0, b: 1000},"
        + "{x:100, a:100, b:0}], row -> row.x, row -> {row.a, row.b})");

    assertThat(applyCurve(-10D), is(tuple("{a: 0.0, b: 1000.0}")));
    assertThat(applyCurve(0D), is(tuple("{a: 0.0, b: 1000.0}")));
    assertThat(applyCurve(50D), is(tuple("{a: 50.0, b: 500.0}")));
    assertThat(applyCurve(100D), is(tuple("{a: 100.0, b: 0.0}")));
    assertThat(applyCurve(10000D), is(tuple("{a: 100.0, b: 0.0}")));
  }

  @Test
  public void canInterpolateStructOfNumbersWithNullables() {
    buildCurve("to_continuous_curve([{x:0, a: 0, b: 1000},"
        + "{x:100, a:100, b:0}, {x:200, a:200, b: null_of('integer')}], row -> row.x, row -> {row.a, row.b})");

    assertThat(applyCurve(-10D), is(tuple("{a: 0.0, b: nullable(1000.0)}")));
    assertThat(applyCurve(0D), is(tuple("{a: 0.0, b: nullable(1000.0)}")));
    assertThat(applyCurve(50D), is(tuple("{a: 50.0, b: nullable(500.0)}")));

    // this is interesting/odd - because only b is missing, we can interpolate a, but not b - the function isn't smart
    // enough to return the boundary case for b (like it would if it were interpolated by itself)
    assertThat(applyCurve(100D), is(tuple("{a: 100.0, b: null_of('floating')}")));
    assertThat(applyCurve(10000D), is(tuple("{a: 200.0, b: null_of('floating')}")));
  }

  @Test
  public void canInterpolateBetweenTwoValuesWithApplyLogToX() {
    buildCurve("to_continuous_curve([{x:1, y:0},{x:100, y:100}], row -> row.x, row -> row.y, "
        + "options: {apply_log_to_x: true})");
    assertThat(applyCurve(-1D), is(0D));
    assertThat(applyCurve(1D), is(0D));
    assertThat((double) applyCurve(50D), closeTo(84.948, 0.001));
    assertThat((double) applyCurve(100D), closeTo(100D, 0.001));
    assertThat((double) applyCurve(10000D), closeTo(100D, 0.001));
  }

  @Test
  public void duplicateXvalueCauseError() {
    assertThat(
        Assert.assertThrows(RiskscapeException.class,
            () -> buildCurve("to_continuous_curve([{x:1, y:0},{x:100, y:100}, {x:1, y:0}], "
                + "row -> row.x, row -> row.y)")
        ).getProblem(),
        hasAncestorProblem(ToContinuousCurve.PROBLEMS.duplicateXValue(1.0D, tuple("{x: 1, y: 0}")))
    );
  }

  @Test
  public void errorIfXNotANumber() {
    assertThat(
        realizeOnly("to_continuous_curve([{x: '1', y: 2}], row -> row.x, row -> row.y)", Struct.EMPTY_STRUCT),
        failedResult(
            hasAncestorProblem(TypeProblems.get().mismatch("x-value", Types.FLOATING, Types.TEXT))
        )
    );
  }

  @Test
  public void errorIfYNotANumber() {
    assertThat(
      realizeOnly("to_continuous_curve([{x: 1, y: '2'}], row -> row.x, row -> row.y)", Struct.EMPTY_STRUCT),
      failedResult(
          hasAncestorProblem(equalIgnoringChildren(ToContinuousCurve.PROBLEMS.badYValue(parser.parse("row.y"))))
      )
    );
  }

  @Test
  public void errorIfYIsAStructWithNonNumbers() {
    assertThat(
      realizeOnly("to_continuous_curve([{x: 1, y: 2}], row -> row.x, row -> { row.y, 'foo' })", Struct.EMPTY_STRUCT),
      failedResult(
          hasAncestorProblem(equalIgnoringChildren(
              ToContinuousCurve.PROBLEMS.badYValue(parser.parse("{row.y, 'foo'}"))))
      )
    );
  }

  @Test
  public void errorWrongNumberOfArgs() {
    // not enough args
    assertThat(
        realizeOnly("to_continuous_curve()", Struct.EMPTY_STRUCT),
        failedResult(
            hasAncestorProblem(ArgsProblems.get().wrongNumber(Range.closed(3, 4), 0))
        )
    );

    // too many args
    assertThat(
        realizeOnly("to_continuous_curve([1], x -> x, y -> y, {},  'foo')",
            Struct.EMPTY_STRUCT),
        failedResult(
            hasAncestorProblem(ArgsProblems.get().wrongNumber(Range.closed(3, 4), 5))
        )
    );
  }

  void buildCurve(String curveExpr) {
    if (relation != null) {
      addPickledData("relation", relation);
    }

    curveFunction = evaluate(curveExpr, scope);
    applyCurveType = Struct.of("curve", realized.getResultType(), "x", Types.FLOATING);
    applyCurveInput = Tuple.ofValues(applyCurveType, curveFunction);

    applyCurve = realizeOnly("apply_continuous(curve, x)", applyCurveType).get();
  }

  Object applyCurve(double x) {
    applyCurveInput.set("x", x);
    return applyCurve.evaluate(applyCurveInput);
  }

}
