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

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

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

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.FunctionMetadata;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.resource.Resource;
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.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

public class FunctionRealizerTest extends BaseExpressionRealizerTest {

  static final ArgumentList ARGUMENTS = ArgumentList.create(
      "foo", Nullable.TEXT,
      "bar", Nullable.INTEGER,
      "baz", Nullable.FLOATING
  );

  /**
   * Realizable function for testing. It will accept any args and when called it just echos them back which
   * is useful for testing the arguments are given in the expected order.
   */
  class FooRealizeable implements RealizableFunction {

    @Override
    public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context, FunctionCall fc,
        List<Type> argumentTypes) {
      FunctionRealizerTest.this.functionCall = fc;
      FunctionRealizerTest.this.givenTypes = argumentTypes;

      return ResultOrProblems.of(
          RiskscapeFunction.create("test", argumentTypes, RSList.LIST_ANYTHING, (args) -> args)
      );
    }
  }

  List<Type> givenTypes;
  FunctionCall functionCall;

  @Before
  public void addFooFunction() {
    project.getFunctionSet().add(RealizableFunction.identified(
        new FooRealizeable(),
        new FunctionMetadata("foo", ARGUMENTS, Types.ANYTHING,
            "foo function", IdentifiedFunction.Category.MATHS, Resource.UNKNOWN_URI)
    ));
  }

  @Test
  public void canEvaluateFunctionWithPositionalArgs() {
    assertThat(evaluate("foo('foo', 11, 22.5)", Tuple.EMPTY_TUPLE), is(Arrays.asList("foo", 11L, 22.5D)));
    assertThat(givenTypes, contains(Types.TEXT, Types.INTEGER, Types.FLOATING));


    assertThat(evaluate("foo('foo', 11)", Tuple.EMPTY_TUPLE), is(Arrays.asList("foo", 11L)));
    assertThat(givenTypes, contains(Types.TEXT, Types.INTEGER));

    assertThat(evaluate("foo('foo')", Tuple.EMPTY_TUPLE), is(Arrays.asList("foo")));
    assertThat(givenTypes, contains(Types.TEXT));

    assertThat(evaluate("foo()", Tuple.EMPTY_TUPLE), is(Arrays.asList()));
    assertThat(givenTypes, hasSize(0));
  }

  @Test
  public void canEvaluateFunctionWithNamedArgsInAnyOrder() {
    assertThat(evaluate("foo(foo: 'foo', bar: 11, baz: 22.5)", Tuple.EMPTY_TUPLE),
        is(Arrays.asList("foo", 11L, 22.5D)));
    assertThat(givenTypes, contains(Types.TEXT, Types.INTEGER, Types.FLOATING));

    assertThat(evaluate("foo(baz: 22.5, foo: 'foo', bar: 11)", Tuple.EMPTY_TUPLE),
        is(Arrays.asList("foo", 11L, 22.5D)));
    assertThat(givenTypes, contains(Types.TEXT, Types.INTEGER, Types.FLOATING));

    assertThat(evaluate("foo(bar: 11, foo: 'foo', baz: 22.5)", Tuple.EMPTY_TUPLE),
        is(Arrays.asList("foo", 11L, 22.5D)));
    assertThat(givenTypes, contains(Types.TEXT, Types.INTEGER, Types.FLOATING));
  }

  @Test
  public void optionalKeywordArgumentsCanBeOmitted() {
    // missing the args 1 and 3. 3 is removed but 1 has the nothing placeholder.
    assertThat(evaluate("foo(bar: 11)", Tuple.EMPTY_TUPLE),
        is(Arrays.asList(null, 11L)));
    assertThat(givenTypes, contains(Types.NOTHING, Types.INTEGER));

    // only the last argument is specified
    assertThat(evaluate("foo(baz: 22.5)", Tuple.EMPTY_TUPLE),
        is(Arrays.asList(null, null, 22.5D)));
    assertThat(givenTypes, contains(Types.NOTHING, Types.NOTHING, Types.FLOATING));

    // whilst we here we should check what args as accessible via the funtion call.
    assertThat(ARGUMENTS.getArgument(functionCall, "foo").isPresent(), is(false));
    assertThat(ARGUMENTS.getRequiredArgument(functionCall, "foo").hasErrors(), is(true));
    assertThat(ARGUMENTS.getArgument(functionCall, "bar").isPresent(), is(false));
    assertThat(ARGUMENTS.getRequiredArgument(functionCall, "bar").hasErrors(), is(true));
    assertThat(ARGUMENTS.getArgument(functionCall, "baz").get().getExpression(), is(parse("22.5")));
    assertThat(ARGUMENTS.getRequiredArgument(functionCall, "baz").get().getExpression(), is(parse("22.5")));

    assertThat(functionCall.indexOfArgNamed("foo"), is(-1));
    assertThat(functionCall.indexOfArgNamed("bar"), is(-1));
    assertThat(functionCall.indexOfArgNamed("baz"), is(0));
    assertThat(functionCall.getArguments().get(0).getExpression(), is(parse("22.5")));
  }

  @Test
  public void realizerDoesNotMessWithInputTypesWhenTypeAdaptationIsOff() throws Exception {
    AtomicBoolean onOff = new AtomicBoolean(false);
    RealizableFunction rf = new RealizableFunction() {

      @Override
      public boolean isDoTypeAdaptation() {
        return onOff.get();
      }

      @Override
      public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context, FunctionCall fc,
          List<Type> argumentTypes) {

        // we'll check to see what we were given after realizing
        FunctionRealizerTest.this.givenTypes = argumentTypes;

        return ResultOrProblems.of(RiskscapeFunction.create(this, givenTypes, Types.TEXT, args -> "foo"));
      }
    };

    Struct genericStruct = Struct.of("foo", Types.ANYTHING);
    Struct expectedStruct = Struct.of("foo", Types.TEXT, "bar", Types.TEXT);

    project.getFunctionSet().add(RealizableFunction.identified(
        rf,
        new FunctionMetadata("subject", List.of(genericStruct), Types.TEXT, Resource.UNKNOWN_URI))
    );

    evaluate("subject({foo: 'text', bar: 'surplus'})", Tuple.EMPTY_TUPLE);
    assertThat(realizationProblems, empty());

    // confirm we were given the struct without any coercion (which would have removed the surplus member, and down-cast
    // the foo member)
    assertThat(givenTypes, equalTo(List.of(expectedStruct)));

    // try again with type adaptation on and see the effect (we test this implicitly elsewhere, but good to have an
    // explicit test)
    onOff.set(true);

    evaluate("subject({foo: 'text', bar: 'surplus'})", Tuple.EMPTY_TUPLE);
    assertThat(realizationProblems, empty());

    // here we confirm the sad consequnces of type adaptation
    assertThat(givenTypes, equalTo(List.of(genericStruct)));
  }
}
