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

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

import java.net.URI;
import java.util.Arrays;
import java.util.List;

import org.junit.Test;
import org.locationtech.jts.geom.Point;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.DummyFunction;
import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.data.InputDataProblems;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.types.WithinRange;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

@SuppressWarnings("unchecked")
public class UserDefinedFunctionTest extends ProjectTest {

  TestFunction testFunction;
  IdentifiedFunction function;
  URI uri = URI.create("foo.py");

  private class TestFunction extends UserDefinedFunction {
    TestFunction(FunctionMetadata details, Resource script) {
      super(details, script);
    }

    @Override
    public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context, FunctionCall functionCall,
        List<Type> argumentTypes) {
      if (areArgumentsCompatible(context, argumentTypes)) {
        return ResultOrProblems.of(new DummyFunction(argumentTypes));
      } else {
        return ResultOrProblems.failed(getArgumentProblems(context, argumentTypes));
      }
    }
  }

  @Test
  public void canCreateFunctionWithExactArgTypes() {
    List<Type> argTypes = Arrays.asList(Types.INTEGER, Nullable.FLOATING);
    FunctionMetadata metadata = new FunctionMetadata("foo", argTypes, Types.TEXT, uri);
    ResultOrProblems<RiskscapeFunction> result = realize(metadata, argTypes);

    assertThat(result, result(DummyFunction.class, instanceOf(DummyFunction.class)));
    assertFalse(result.hasProblems());
    assertThat(function.getId(), is("foo"));
    assertThat(testFunction.getDeclaredArgumentTypes(), is(argTypes));
    assertThat(function.getArgumentTypes(), is(argTypes));
    assertThat(function.getReturnType(), is(Types.TEXT));
    assertThat(function.getRealizable().get(), is(testFunction));

    assertThrows(UnsupportedOperationException.class, () -> function.call(Arrays.asList(1L, 2.0D)));
    assertThat(result.get().call(Arrays.asList(1L, 2.0D)), is("1+2.0"));
  }

  @Test
  public void canCreateFunctionWithAssignableArgTypes() {
    List<Type> expectedArgs = Arrays.asList(Types.GEOMETRY, Types.INTEGER);
    FunctionMetadata metadata = metadata(ArgumentList.anonymous(expectedArgs));
    List<Type> actualArgs = Arrays.asList(Types.POLYGON, new WithinRange(Types.INTEGER, 1, 10));
    ResultOrProblems<RiskscapeFunction> result = realize(metadata, actualArgs);
    assertFalse(result.hasProblems());
    assertThat(testFunction.getDeclaredArgumentTypes(), is(expectedArgs));
    assertThat(function.getArgumentTypes(), is(expectedArgs));
    RiskscapeFunction realized = result.get();
    assertThat(realized.getArgumentTypes(), is(actualArgs));
    GeometryHelper crs84Helper = GeometryHelper.longLat(project.getSridSet());
    Point point = crs84Helper.point(1, 2);
    assertThat(realized.call(Arrays.asList(point, 2L)), is(point.toString() + "+2"));

    // sanity-check we cannot go the other way, from generic to more specific args
    metadata = new FunctionMetadata("foo", actualArgs, Types.TEXT, uri);
    assertThat(realize(metadata, expectedArgs), failedResult(equalIgnoringChildren(
        ArgsProblems.mismatch(metadata.getArguments().get(0), Types.GEOMETRY)
    )));
  }

  @Test
  public void errorTellsUsWhichFunctionArgIsBad() {
    ArgumentList expected = ArgumentList.create("foo", Types.INTEGER, "bar", Types.FLOATING, "baz", Types.GEOMETRY);
    List<Type> actualArgs = Arrays.asList(Types.INTEGER, Types.TEXT, Types.BOOLEAN);
    assertThat(realize(metadata(expected), actualArgs), failedResult(
            is(TypeProblems.get().mismatch(expected.get(1), Types.FLOATING, Types.TEXT)),
            is(TypeProblems.get().mismatch(expected.get(2), Types.GEOMETRY, Types.BOOLEAN))
    ));
  }

  @Test
  public void errorTellsUsWhichStructMemberIsTheWrongType() {
    Struct expected = Struct.of("foo", Types.INTEGER, "bar", Types.FLOATING, "baz", Types.GEOMETRY);
    Struct actual = Struct.of("foo", Types.INTEGER, "bar", Types.INTEGER, "baz", Types.BOOLEAN);
    ArgumentList declaredArgs = ArgumentList.create("qux", expected);

    assertThat(realize(metadata(declaredArgs), Arrays.asList(actual)),
        failedResult(hasAncestorProblem(
            is(TypeProblems.get().mismatch(declaredArgs.get(0), expected, actual).withChildren(
                // note that 'bar' is coercible (Floating => Integer), so not reported here
                TypeProblems.get().mismatch(expected.getEntry("baz"), Types.GEOMETRY, Types.BOOLEAN),
                InputDataProblems.get().doesNotMatchType()
            ))
        ))
    );
  }

  @Test
  public void errorTellsUsWhichStructMembersAreMissing() {
    Struct expected = Struct.of("foo", Types.INTEGER, "bar", Types.FLOATING, "baz", Types.GEOMETRY);
    Struct actual = Struct.of("foo", Types.INTEGER, "bart", Types.INTEGER, "bazza", Types.BOOLEAN);
    ArgumentList declaredArgs = ArgumentList.create("qux", expected);

    assertThat(realize(metadata(declaredArgs), Arrays.asList(actual)),
        failedResult(hasAncestorProblem(
            is(TypeProblems.get().mismatch(declaredArgs.get(0), expected, actual).withChildren(
                GeneralProblems.get().required(expected.getEntry("bar")),
                GeneralProblems.get().required(expected.getEntry("baz")),
                InputDataProblems.get().doesNotMatchType()
            ))
        ))
    );
  }

  @Test
  public void errorTellsUsIfArgumentsAreMissing() {
    ArgumentList expected = ArgumentList.create("foo", Types.INTEGER, "bar", Types.FLOATING);
    List<Type> actualArgs = Arrays.asList(Types.INTEGER);

    assertThat(realize(metadata(expected), actualArgs),
        failedResult(hasAncestorProblem(is(
            ArgsProblems.get().wrongNumber(expected.getArity(), 1)
    ))));
  }

  @Test
  public void errorTellsUsIfTooManyArgumentsAreGiven() {
    ArgumentList expected = ArgumentList.create("foo", Types.INTEGER);
    List<Type> actualArgs = Arrays.asList(Types.INTEGER, Types.FLOATING);

    assertThat(realize(metadata(expected), actualArgs),
        failedResult(hasAncestorProblem(is(ArgsProblems.get().wrongNumber(expected.getArity(), 2)))));
  }

  @Test
  public void canSafelyOmitNullableArguments() {
    List<Type> expectedArgs = Arrays.asList(Types.INTEGER, Nullable.FLOATING);
    FunctionMetadata metadata = metadata(ArgumentList.anonymous(expectedArgs));
    List<Type> actualArgs = Arrays.asList(Types.INTEGER);
    ResultOrProblems<RiskscapeFunction> result = realize(metadata, actualArgs);
    assertFalse(result.hasProblems());
    assertThat(testFunction.getDeclaredArgumentTypes(), is(expectedArgs));
    assertThat(function.getArgumentTypes(), is(expectedArgs));
    RiskscapeFunction realized = result.get();
    assertThat(realized.getArgumentTypes(), is(actualArgs));
    assertThat(realized.call(Arrays.asList(1L)), is("1"));
  }

  @Test
  public void errorDoesNotIncludeCoercibleArguments() {
    // can safely coerce integer to floating
    Struct expected = Struct.of("foo", Types.FLOATING);
    Struct coercible = Struct.of("foo", Types.INTEGER, "bar", Types.INTEGER);
    ArgumentList declaredArgs = ArgumentList.create("baz", expected, "qux", Types.FLOATING);
    List<Type> actualArgs = Arrays.asList(coercible, Types.TEXT);

    // error tells us about the wrong qux args, rather than the coercible struct
    // (this simulates cases where the DefaultFunctionResolver can pass through the
    // original, uncoerced struct to the function)
    assertThat(realize(metadata(declaredArgs), actualArgs),
        failedResult(hasAncestorProblem(
            is(TypeProblems.get().mismatch(declaredArgs.get(1), Types.FLOATING, Types.TEXT))
    )));
  }

  @Test
  public void cannotRealizeUncoercedCoercibleArguments() {
    // can safely coerce integer to floating
    Struct expected = Struct.of("foo", Types.FLOATING);
    Struct coercible = Struct.of("foo", Types.INTEGER, "bar", Types.INTEGER);
    ArgumentList declaredArgs = ArgumentList.create("baz", expected);
    List<Type> actualArgs = Arrays.asList(coercible);

    // make sure we can't realize the function directly with coercible (but uncoerced) args.
    // (shouldn't happen because DefaultFunctionResolver should coerce for us)
    assertThat(realize(metadata(declaredArgs), actualArgs), failedResult(
        is(ArgsProblems.get().realizableDidNotMatch(RiskscapeFunction.class, actualArgs))
    ));
  }

  private FunctionMetadata metadata(ArgumentList args) {
    return new FunctionMetadata("foo", args, Types.TEXT, FunctionMetadata.NO_DESCRIPTION,
        FunctionMetadata.UNCATEGORIZED, uri);
  }

  private ResultOrProblems<RiskscapeFunction> realize(FunctionMetadata metadata, List<Type> givenTypes) {
    testFunction = new TestFunction(metadata, Resource.UNKNOWN);
    function = testFunction.identified();
    return function.getRealizable().get().realize(realizationContext, null, givenTypes);
  }
}
