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

import static nz.org.riskscape.engine.Matchers.*;

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

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

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

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.config.ConfigProblems;
import nz.org.riskscape.engine.Project;
import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.BoundParameters;
import nz.org.riskscape.engine.bind.JavaParameterSet;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.FunctionFramework;
import nz.org.riskscape.engine.function.FunctionMetadata;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.function.MetadataBasedFunction;
import nz.org.riskscape.engine.function.MetadataParams;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.ExpressionProblems;

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

  // basic function framework for testing that just builds what we tell it
  @RequiredArgsConstructor
  public class TestFunctionFramework implements FunctionFramework {

    @Getter
    private final String id;

    @Getter
    private final int priority;

    @Getter
    private final JavaParameterSet<MetadataParams> parameterSet =
        JavaParameterSet.fromBindingClass(MetadataParams.class);

    @Override
    public boolean canBuild(Project project, Map<String, List<?>> unbound) {
      return MetadataParams.locationEndsWith(unbound, ".test");
    }

    @Override
    public ResultOrProblems<IdentifiedFunction> build(String functionName, Project project, BoundParameters bound) {
      MetadataParams params = parameterSet.bindToObject(bound).getBoundToObject();
      FunctionMetadata metadata = new FunctionMetadata(
          functionName,
          params.argumentTypes,
          params.returnType,
          // append the id to the description so we can tell which one built it (for priority test)
          params.description.orElse("N/A") + " from " + id,
          params.category.orElse(FunctionMetadata.UNCATEGORIZED),
          params.location.orElse(null));

      return ResultOrProblems.of(
          new MetadataBasedFunction(metadata) {
            @Override
            public synchronized Object call(List<Object> args) {
              // just return an empty struct of the corresponding type
              return Tuple.ofValues(getReturnType().asStruct());
            }
      });
    }
  }

  BindingContext modelContext = bindingContext;

  @Before
  public void setup() {
    engine.getFunctionFrameworks().add(new TestFunctionFramework("test", FunctionFramework.DEFAULT_PRIORITY));
  }

  @Test
  public void canBuildASimpleFunction() throws Exception {
    populate(
        "[function foo]",
        "location = dummy.test",
        "return-type = text",
        "argument-types = [integer]");

    IdentifiedFunction built = build("foo").get();
    assertThat(built.getReturnType(), equalTo(Types.TEXT));
  }

  @Test
  public void cannotBuildUnknownFileExtension() throws Exception {
    populate(
        "[function foo]",
        "location = dummy.unknown",
        "return-type = text",
        "argument-types = [integer]");

    assertThat(build("foo"), failedResult(hasAncestorProblem(
        equalTo(GeneralProblems.required("framework", Parameter.class))
    )));
  }

  @Test
  public void canBuildUnknownFileExtensionWithExplicitFramework() throws Exception {
    populate(
        "[function foo]",
        "location = dummy.unknown",
        "return-type = text",
        "argument-types = [integer]",
        "framework = test");

    IdentifiedFunction built = build("foo").get();
    assertThat(built.getReturnType(), equalTo(Types.TEXT));
  }

  @Test
  public void canBuildKeywordArgumentTypes() throws Exception {
    populate(
        "[function foo]",
        "location = dummy.test",
        "return-type = text",
        "argument-types = [bar: integer, baz: floating]");

    ArgumentList expectedArgs = ArgumentList.fromArray(
        new FunctionArgument("bar", Types.INTEGER),
        new FunctionArgument("baz", Types.FLOATING)
    );

    IdentifiedFunction built = build("foo").get();
    assertThat(built.getArguments(), is(expectedArgs));
  }

  @Test
  public void cannotBuildBadFrameworkId() throws Exception {
    populate(
        "[function foo]",
        "location = dummy.unknown",
        "return-type = text",
        "argument-types = [integer]",
        "framework = bad");

    assertThat(build("foo"), failedResult(hasAncestorProblem(
        equalTo(GeneralProblems.get().noSuchObjectExists("bad", FunctionFramework.class))
    )));
  }

  @Test
  public void spuriousKeysGetFlaggedAsWarnings() throws Exception {
    populate(
        "[function foo]",
        "location = dummy.test",
        "return-type = text",
        "argument-types = [integer]",
        "framewrok = typo");

    Problem expectedWarning = ConfigProblems.get().spuriousKeys(config.getSection("function foo").get(),
        new HashSet<String>(Arrays.asList("framewrok")));

    ResultOrProblems<IdentifiedFunction> result = build("foo");
    assertTrue(result.hasProblems());
    assertThat(result.getProblems(), contains(hasAncestorProblem(
        equalTo(expectedWarning)
    )));
  }

  @Test
  public void badTypeDefinitionsIsProblem() throws Exception {
    populate(
        "[function foo]",
        "location = dummy.test",
        "return-type = text",
        // list shouldn't have quotes around the list type
        "argument-types = [list('integer')]",
        "framework = test");

    assertThat(build("foo"), failedResult(hasAncestorProblem(
        equalIgnoringChildren(ExpressionProblems.get().notAValid(Type.class, "list('integer')"))
    )));
  }

  @Test
  public void badReturnTypeDefinitionIsProblem() throws Exception {
    populate(
        "[function foo]",
        "location = dummy.test",
        // list shouldn't have quotes around the list type
        "return-type = list('text')",
        "argument-types = [list(integer)]",
        "framework = test");

    assertThat(build("foo"), failedResult(hasAncestorProblem(
        equalIgnoringChildren(ExpressionProblems.get().notAValid(Type.class, "list('text')"))
    )));
  }

  @Test
  public void favoursHigherPriorityFrameworkWhenNoFrameworkSpecified() throws Exception {

    populate(
        "[function foo]",
        "location = dummy.test",
        "return-type = text",
        "argument-types = [integer]");

    assertThat(build("foo").get().getDescription(), equalTo("N/A from test"));

    // pop in a higher priority framework, check that wins
    engine.getFunctionFrameworks().add(new TestFunctionFramework("usurper", 10));

    populate(
        "[function foo]",
        "location = dummy.test",
        "return-type = text",
        "argument-types = [integer]");

    assertThat(build("foo").get().getDescription(), equalTo("N/A from usurper"));
    // this one is lower, it shouldn't win over the usurper
    engine.getFunctionFrameworks().add(new TestFunctionFramework("loser", -10));

    populate(
        "[function foo]",
        "location = dummy.test",
        "return-type = text",
        "argument-types = [integer]");
    assertThat(build("foo").get().getDescription(), equalTo("N/A from usurper"));
  }

  private ResultOrProblems<IdentifiedFunction> build(String name) {
    return project.getFunctionSet().getOr(name);
  }
}
