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

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

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

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

import org.junit.Test;

import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.bind.ParameterBindingException;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.resource.Resource;
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.Types;
import nz.org.riskscape.engine.typeset.CanonicalType;
import nz.org.riskscape.engine.typeset.LinkedType;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.ExpressionProblems;

public class ArgumentListBinderTest extends BaseBinderTest {

  Parameter argsParameter = Parameter.required("argument-types", ArgumentList.class);
  ArgumentListBinder subject = new ArgumentListBinder();

  @Test
  public void canBindToIdentifiedType() {
    CanonicalType fooType = project.getTypeSet().add("foo", Types.ANYTHING);
    ArgumentList bound = bind("[foo]");
    assertThat(bound, equalTo(args(Types.ANYTHING)));
  }

  @Test
  public void canBindToSimpleType() {
    ArgumentList bound = bind("[floating]");
    assertThat(bound, equalTo(args(Types.FLOATING)));
  }

  @Test
  public void canBindToStruct() {
    Struct structType = Struct.of("foo", Types.TEXT);
    ArgumentList bound = bind("[struct(foo: text)]");
    assertThat(bound, equalTo(args(structType)));
  }

  @Test
  public void canBindToMultipleArgs() {
    Type fooType = Types.ANYTHING;
    project.getTypeSet().add("foo", fooType);
    Struct structType = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER);
    ArgumentList bound = bind("[foo, struct(foo: text, bar: integer), floating]");
    assertThat(bound, equalTo(args(fooType, structType, Types.FLOATING)));

    // check spaces don't matter
    bound = bind("[ foo , struct ( foo: text , bar: integer ) , floating ]");
    assertThat(bound, equalTo(args(fooType, structType, Types.FLOATING)));
  }

  @Test
  public void cannotBindIdentifiedTypeInComplexTypeWithoutLookup() {
    project.getTypeSet().add("foo", Types.ANYTHING);
    ParameterBindingException ex = bindThrows("[struct(foo: foo)]");
    assertThat(ex.getProblem(),
        hasAncestorProblem(equalIgnoringChildren(ExpressionProblems.get().notAValid(Type.class, "struct(foo: foo)"))));
  }

  @Test
  public void canBindIdentifiedTypeInComplexTypeWithLookup() {
    project.getTypeSet().add("foo", Types.ANYTHING);
    LinkedType linkedType = new LinkedType(project.getTypeSet(), "foo");
    Struct structType = Struct.of("foo", linkedType);
    ArgumentList bound = bind("[struct(foo: lookup('foo'))]");
    assertThat(bound, equalTo(args(structType)));
  }

  @Test
  public void canBindWithNullable() {
    project.getTypeSet().add("foo", Types.ANYTHING);
    LinkedType linkedType = new LinkedType(project.getTypeSet(), "foo");
    Struct structType = Struct.of("foo", Types.TEXT, "bar", Nullable.INTEGER);
    ArgumentList bound = bind(
        "[nullable(lookup('foo')), struct(foo: text, bar: nullable(integer)), nullable(floating)]");
    assertThat(bound, equalTo(args(Nullable.of(linkedType), structType, Nullable.FLOATING)));
  }

  @Test
  public void canBindKeywordArgsForSimpleTypes() {
    ArgumentList bound = bind("[foo: floating, bar: text]");
    assertThat(bound, equalTo(
        args(new FunctionArgument("foo", Types.FLOATING),
             new FunctionArgument("bar", Types.TEXT))
        ));
  }

  @Test
  public void canBindKeywordArgsForIdentifiedTypes() {
    Type fooType = Types.ANYTHING;
    project.getTypeSet().add("foo", fooType);
    Type barType = Struct.of("baz", Types.TEXT);
    project.getTypeSet().add("bar", barType);
    ArgumentList bound = bind("[foo: bar, bar: foo]");
    assertThat(bound, equalTo(
        args(new FunctionArgument("foo", barType),
             new FunctionArgument("bar", fooType))
        ));
  }

  @Test
  public void canBindKeywordArgsForComplexTypes() {
    Struct structType = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER);
    ArgumentList bound = bind("[foo: struct(foo: text, bar: integer), bar: nullable(text)]");
    assertThat(bound, equalTo(
        args(new FunctionArgument("foo", structType),
             new FunctionArgument("bar", Nullable.TEXT))
        ));
  }

  @Test
  public void canBindAMixOfKeywordArgs() {
    ArgumentList bound = bind("[integer, foo: floating, text, bar: geometry]");
    assertThat(bound, equalTo(
        args(new FunctionArgument(0, Types.INTEGER),
             new FunctionArgument("foo", Types.FLOATING),
             new FunctionArgument(2, Types.TEXT),
             new FunctionArgument("bar", Types.GEOMETRY))
        ));
  }

  @Test
  public void cannotBindToUnknownType() {
    ParameterBindingException ex = bindThrows("[foo]");
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        GeneralProblems.get().noSuchObjectExists("foo", CanonicalType.class)
    )));
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        ExpressionProblems.get().notAValid(Type.class, "foo")
    )));
  }

  @Test
  public void cannotBindToInvalidType() {
    // add a linkded type, but this will blow up when the backing type is fetched
    project.getTypeSet().add("invalid", Resource.UNKNOWN, () -> ResultOrProblems.failed(Problem.error("boom")));

    ParameterBindingException ex = bindThrows("[invalid]");
    assertThat(ex.getProblem(), hasAncestorProblem(
        isError(GeneralProblems.class, "failedObjectLookedUp")
    ));

    ex = bindThrows("[lookup('invalid')]");
    assertThat(ex.getProblem(), hasAncestorProblem(
        isError(GeneralProblems.class, "failedObjectLookedUp")
    ));
  }

  @Test
  public void cannotBindToMalformedTypeExpression() {
    // can't lex the type expression
    ParameterBindingException ex = bindThrows("[ struct(foo: ]");
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        ExpressionProblems.get().notAValid(Type.class, "struct(foo:")
    )));
  }

  @Test
  public void cannotBindToUnknownTypeInComplexType() {
    // can lex it, but can't build the type
    ParameterBindingException ex = bindThrows("[ struct(foo: bar) ]");
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        ExpressionProblems.get().notAValid(Type.class, "struct(foo: bar)")
    )));
  }

  @Test
  public void cannotBindToBadExpressions() {
    // no comma separating types
    ParameterBindingException ex = bindThrows("[ integer integer ]");
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        ExpressionProblems.get().notAValid(Type.class, "integer integer")
    )));

    ex = bindThrows("[ integer, struct(foo: text) bogus ]");
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        ExpressionProblems.get().notAValid(Type.class, "struct(foo: text) bogus")
    )));

    // types shouldn't have operators in them
    ex = bindThrows("[ integer, + ]");
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        ExpressionProblems.get().notAValid(Type.class, "+")
    )));

    // the types in list shouldn't be quoted
    ex = bindThrows("[ list('text') ]");
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        ExpressionProblems.get().notAValid(Type.class, "list('text')")
    )));

    // enum only accepts constant values
    ex = bindThrows("[enum('foo', bar)]");
    assertThat(ex.getProblem(), hasAncestorProblem(equalIgnoringChildren(
        ExpressionProblems.get().notAValid(Type.class, "enum('foo', bar)")
    )));
  }

  private ArgumentList args(FunctionArgument... args) {
    return new ArgumentList(Arrays.asList(args));
  }

  private ArgumentList args(Type... argTypes) {
    List<FunctionArgument> args = new ArrayList<>();
    int i = 0;
    for (Type type : argTypes) {
      args.add(new FunctionArgument(i++, type));
    }
    return new ArgumentList(args);
  }

  private ArgumentList bind(String value) {
    return (ArgumentList) subject.bind(context, argsParameter, value);
  }

  private ParameterBindingException bindThrows(String value) {
    return Assert.assertThrows(ParameterBindingException.class, () -> bind(value));
  }

}
