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

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

import java.util.Arrays;

import org.junit.Test;

import com.google.common.collect.Range;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
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.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.rl.ast.ExpressionProblems;

public class ListToTupleTest extends BaseExpressionRealizerTest {

  public ListToTupleTest() {
    project.getFunctionSet().add(new ListToTuple().identified("list_to_tuple"));
  }

  @Test
  public void canSplatLists() {
    Struct expectedType = Struct.of("splat0", Nullable.INTEGER, "splat1", Nullable.INTEGER);
    assertThat(evaluate("list_to_tuple([1,2], 2, 'splat')", Tuple.EMPTY_TUPLE),
        is(Tuple.ofValues(expectedType, 1L, 2L)));
    assertThat(realized.getResultType(), is(expectedType));

    // will drop list items beyond upTo
    assertThat(evaluate("list_to_tuple([1,2,3,4,5,6], 2, 'splat')", Tuple.EMPTY_TUPLE),
        is(Tuple.ofValues(expectedType, 1L, 2L)));

    // will pad missing list items with nulls
    assertThat(evaluate("list_to_tuple([1], 2, 'splat')", Tuple.EMPTY_TUPLE),
        is(Tuple.ofValues(expectedType, 1L, null)));
  }

  @Test
  public void canSplatListsPrefixIsOptional() {
    Struct expectedType = Struct.of("0", Nullable.INTEGER, "1", Nullable.INTEGER);
    assertThat(evaluate("list_to_tuple([1,2], 2)", Tuple.EMPTY_TUPLE),
        is(Tuple.ofValues(expectedType, 1L, 2L)));
    assertThat(realized.getResultType(), is(expectedType));
  }

  @Test
  public void canSplatListsOfStructs() {
    Struct itemType = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER);
    Struct expectedType = Struct.of("0", Nullable.of(itemType), "1", Nullable.of(itemType));

    assertThat(evaluate("list_to_tuple([{foo: 'foo0', bar: 10},{foo: 'foo1', bar: 11}], 2)", Tuple.EMPTY_TUPLE),
        is(Tuple.ofValues(expectedType,
            Tuple.ofValues(itemType, "foo0", 10L),
            Tuple.ofValues(itemType, "foo1", 11L)
        ))
    );
    assertThat(realized.getResultType(), is(expectedType));
  }

  @Test
  public void canSplatANullableList() {
    inputStruct = Struct.of("foo", Nullable.of(RSList.create(Types.TEXT)));
    Struct expectedType = Struct.of("splat0", Nullable.TEXT, "splat1", Nullable.TEXT);
    assertThat(
        evaluate("list_to_tuple(foo, 2, 'splat')", Tuple.ofValues((Struct)inputStruct, Arrays.asList("foo", "bar"))),
        is(Tuple.ofValues(expectedType, "foo", "bar")));
    assertThat(realized.getResultType(), is(expectedType));

    assertThat(
        evaluate("list_to_tuple(foo, 2, 'splat')", Tuple.ofValues((Struct)inputStruct)),
        is(Tuple.ofValues(expectedType)));
    assertThat(realized.getResultType(), is(expectedType));
  }

  @Test
  public void errorWhenUpToNotInteger() {
    assertThat(realizeOnly("list_to_tuple([1,2], 'end', 'prefix')", inputStruct), failedResult(hasAncestorProblem(
        is(TypeProblems.get().mismatch(new ListToTuple().getArguments().get("upto"), Types.INTEGER, Types.TEXT))
    )));
  }

  @Test
  public void errorWhenUpToIsZeroOrLess() {
    assertThat(realizeOnly("list_to_tuple([1,2], 0, 'prefix')", inputStruct), failedResult(hasAncestorProblem(
        isProblem(Severity.ERROR, GeneralProblems.class, "valueOutOfRange")
    )));
    assertThat(realizeOnly("list_to_tuple([1,2], -1, 'prefix')", inputStruct), failedResult(hasAncestorProblem(
        isProblem(Severity.ERROR, GeneralProblems.class, "valueOutOfRange")
    )));
    assertThat(realizeOnly("list_to_tuple([1,2], -100, 'prefix')", inputStruct), failedResult(hasAncestorProblem(
        isProblem(Severity.ERROR, GeneralProblems.class, "valueOutOfRange")
    )));
  }

  @Test
  public void errorWhenUpToNotConstant() {
    inputStruct = Struct.of("upto", Types.INTEGER);
    assertThat(realizeOnly("list_to_tuple([1,2], upto, 'prefix')", inputStruct), failedResult(hasAncestorProblem(
        is(ExpressionProblems.get().constantRequired(parse("upto")))
    )));
  }

  @Test
  public void errorWhenPrefixNotConstant() {
    inputStruct = Struct.of("prefix", Types.TEXT);
    assertThat(realizeOnly("list_to_tuple([1,2], 3, prefix)", inputStruct), failedResult(hasAncestorProblem(
        is(ExpressionProblems.get().constantRequired(parse("prefix")))
    )));
  }

  @Test
  public void errorWhenArgsCountWrong() {
    assertThat(realizeOnly("list_to_tuple([1,2])", inputStruct), failedResult(hasAncestorProblem(
        is(ArgsProblems.get().wrongNumber(Range.closed(2, 3), 1))
    )));

    assertThat(realizeOnly("list_to_tuple([1,2], 3, 'prefix', 'foo')", inputStruct), failedResult(hasAncestorProblem(
        is(ArgsProblems.get().wrongNumber(Range.closed(2, 3), 4))
    )));
  }

}
