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

import static nz.org.riskscape.engine.Matchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

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

import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.bind.ParameterSet;
import nz.org.riskscape.engine.function.IdentifiedFunction.Category;
import nz.org.riskscape.engine.function.UntypedFunction;
import nz.org.riskscape.engine.rl.agg.AggregationFunction;
import nz.org.riskscape.engine.rl.agg.BaseAggregationFunctionTest;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.util.SegmentedList;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

@SuppressWarnings("unchecked")
public class FitCurveFunctionTest extends BaseAggregationFunctionTest {

  List<CurveFitter<?>> fitters = new ArrayList<>();
  FitCurveFunction function = new FitCurveFunction(fitters);

  List<Double> xValues = SegmentedList.forClass(Double.class);
  List<Double> yValues = SegmentedList.forClass(Double.class);
  ObservedPoints expectedPoints = new ObservedPoints(xValues, yValues);

  CurveFitter<?> fitterOne;
  CurveFitter<?> fitterTwo;
  CurveFitter<?> fitterThree;

  Struct inputType = Struct.of("x", Types.FLOATING, "y", Types.FLOATING);

  @Before
  public void setup() {
    project.getFunctionSet().add(AggregationFunction.asFunction(function).builtin("fit_curve", Category.MATHS));
    assertSerialAndParallelEqual = false;

    xValues.addAll(Arrays.asList(1D, 3D, 5D));
    yValues.addAll(Arrays.asList(2D, 4D, 6D));

    for (int i = 0; i < 3; i++) {
      CurveFitter<?> fitter = mockFitter();
      fitters.add(fitter);
      when(fitter.getId()).thenReturn("fitter-" + (i + 1)); // make name one based to match field name
    }

    fitterOne = fitters.get(0);
    fitterTwo = fitters.get(1);
    fitterThree = fitters.get(2);
  }

  @Test
  public void returnsBestFitFromAListOfCurves() {
    tuples = Arrays.asList(
      Tuple.ofValues(inputType, 1D, 2D),
      Tuple.ofValues(inputType, 3D, 4D),
      Tuple.ofValues(inputType, 5D, 6D)
    );

    primeCurve(fitterOne, 0.5D);
    primeCurve(fitterTwo, 0.3D);
    primeCurve(fitterThree, 0.7D);

    realizeAggregate(inputType, functionCall("fit_curve(x-value: x, y-value: y)"));

    process();

    UntypedFunction fit = functionFromResult(serialResult);
    assertSame(fit.call(Arrays.asList(0.0D)), fitterThree);
  }

  @Test
  public void returnsBestFitFromAListOfCurvesWithAFitFailure() {
    tuples = Arrays.asList(
      Tuple.ofValues(inputType, 1D, 2D),
      Tuple.ofValues(inputType, 3D, 4D),
      Tuple.ofValues(inputType, 5D, 6D)
    );

    // fitter one needs to fail
    when(fitterOne.fit(any(), any())).thenThrow(new CannotFitCurveException(Problems.foundWith("things")));

    primeCurve(fitterTwo, 0.3D);
    primeCurve(fitterThree, 0.7D);

    realizeAggregate(inputType, functionCall("fit_curve(x-value: x, y-value: y)"));

    process();

    UntypedFunction fit = functionFromResult(serialResult);
    assertSame(fit.call(Arrays.asList(0.0D)), fitterThree);
  }

  @Test
  public void failsIfNoFitFromAll() {
    tuples = Arrays.asList(
      Tuple.ofValues(inputType, 1D, 2D),
      Tuple.ofValues(inputType, 3D, 4D),
      Tuple.ofValues(inputType, 5D, 6D)
    );

    // they all fail
    for (CurveFitter<?> fitter : fitters) {
      // NB the child problems get ignored in this case - maybe one day we could show more info?
      when(fitter.fit(any(), any())).thenThrow(new CannotFitCurveException(Problems.foundWith("things")));
    }

    realizeAggregate(inputType, functionCall("fit_curve(x-value: x, y-value: y)"));

    assertThat(
      Assert.assertThrows(CannotFitCurveException.class, () -> process()).getProblem(),
      equalIgnoringChildren(FitCurveFunction.PROBLEMS.nothingFits())
    );
  }

  @Test
  public void failsIfNoFitFromSpecificFunction() {
    when(fitterOne.fit(any(), any())).thenThrow(new CannotFitCurveException(Problems.foundWith("things")));

    realizeAggregate(inputType, functionCall("fit_curve(x-value: x, y-value: y, fitters: {'fitter-1'})"));

    assertThat(
      Assert.assertThrows(CannotFitCurveException.class, () -> process()).getProblem(),
        hasAncestorProblem(
            is(FitCurveFunction.PROBLEMS.fittingFailed("fitter-1").withChildren(Problems.foundWith("things")))
        ));
  }

  @Test
  public void skipsAnyNulls() {
    tuples = Arrays.asList(
      Tuple.ofValues(inputType, 1D, 2D),
      Tuple.ofValues(inputType, 2D, null),
      Tuple.ofValues(inputType, 3D, 4D),
      Tuple.ofValues(inputType, null, 4D),
      Tuple.ofValues(inputType, 5D, 6D)
    );

    primeCurve(fitterOne, 0.5D);
    primeCurve(fitterTwo, 0.3D);
    primeCurve(fitterThree, 0.7D);

    realizeAggregate(inputType, functionCall("fit_curve(x-value: x, y-value: y)"));

    process();

    UntypedFunction fit = functionFromResult(serialResult);
    assertSame(fit.call(Arrays.asList(0.0D)), fitterThree);
  }

  @Test
  public void returnsBestFitFromAListOfCurvesUsingIntegers() {
    inputType = Struct.of("x", Types.INTEGER, "y", Types.INTEGER);
    tuples = Arrays.asList(
      Tuple.ofValues(inputType, 1L, 2L),
      Tuple.ofValues(inputType, 3L, 4L),
      Tuple.ofValues(inputType, 5L, 6L)
    );

    primeCurve(fitterOne, 0.5D);
    primeCurve(fitterTwo, 0.3D);
    primeCurve(fitterThree, 0.7D);

    realizeAggregate(inputType, functionCall("fit_curve(x-value: x, y-value: y)"));

    process();

    UntypedFunction fit = functionFromResult(serialResult);
    assertSame(fit.call(Arrays.asList(0.0D)), fitterThree);
  }

  @Test
  public void failsIfXAndValuesAreNotNumeric() throws Exception {
    // x is no good
    inputType = Struct.of("x", Types.TEXT, "y", Types.INTEGER);
    realizeAggregate(inputType, functionCall("fit_curve(x-value: x, y-value: y)"));
    assertThat(realizationProblems, Matchers.contains(nz.org.riskscape.engine.Matchers.hasAncestorProblem(
      Matchers.equalTo(
        TypeProblems.get().mismatch(
          function.getArguments().get("x-value"),
          Types.FLOATING,
          Types.TEXT
        )
      )
    )));

    // y is no good
    inputType = Struct.of("x", Types.DECIMAL, "y", Types.TEXT);
    realizeAggregate(inputType, functionCall("fit_curve(x-value: x, y-value: y)"));
    assertThat(realizationProblems, Matchers.contains(nz.org.riskscape.engine.Matchers.hasAncestorProblem(
      Matchers.equalTo(
        TypeProblems.get().mismatch(
          function.getArguments().get("y-value"),
          Types.FLOATING,
          Types.TEXT
        )
      )
    )));

    // args are required, duh
    inputType = Struct.of("y", Types.FLOATING);
    realizeAggregate(inputType, functionCall("fit_curve(y-value: y)"));
    assertThat(realizationProblems, Matchers.contains(nz.org.riskscape.engine.Matchers.hasAncestorProblem(
      Matchers.equalTo(
        ArgsProblems.get().required("x-value")
      )
    )));
    inputType = Struct.of("y", Types.FLOATING);
    realizeAggregate(inputType, functionCall("fit_curve(x-value: y)"));
    assertThat(realizationProblems, Matchers.contains(nz.org.riskscape.engine.Matchers.hasAncestorProblem(
      Matchers.equalTo(
        ArgsProblems.get().required("y-value")
      )
    )));
  }

  private void primeCurve(CurveFitter<?> fitter, double d) {
    when(fitter.fit(any(), any())).thenAnswer(inv -> {
      ObservedPoints givenPoints = inv.getArgument(1);
      assertThat(givenPoints.asListOfPairs(), Matchers.containsInAnyOrder(expectedPoints.asListOfPairs().toArray()));
      return new DefaultFitCurve<>(fitter, xValue -> fitter, inv.getArgument(0), inv.getArgument(1), x -> d);
    });
  }

  @SuppressWarnings("rawtypes")
  private CurveFitter<?> mockFitter() {
    CurveFitter fitter = mock(CurveFitter.class);
    // use a realistic type to make sure the casting works
    Class doubleClass = double[].class;
    when(fitter.getBindingClass()).thenReturn(doubleClass);
    when(fitter.bind(any(), eq(Collections.emptyMap()))).thenReturn(ResultOrProblems.of(new double[] {}));
    ParameterSet params = new ParameterSet(Collections.emptySet());
    when(fitter.getParameters()).thenReturn(params);
    return fitter;
  }

  /**
   * @return the function from the result object.
   */
  private UntypedFunction functionFromResult(Object result) {
    Tuple tuple = (Tuple)result;
    return (UntypedFunction)tuple.fetch("function");
  }

}
