/*
 * 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 static nz.org.riskscape.engine.Assert.*;

import java.util.Arrays;

import org.junit.Test;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.bind.ParamProblems;
import nz.org.riskscape.engine.bind.impl.NumberBinder;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.EvalException;
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.Types;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.rl.ast.ExpressionProblems;

public class ListToColumnsTest extends BaseExpressionRealizerTest {

  public ListToColumnsTest() {
    project.getFunctionSet().add(new ListToColumns().identified("list_to_columns"));
  }

  @Test
  public void canSplatListsWithNames() {
    Struct expectedType = Struct.of("foo", Nullable.INTEGER, "bar", Nullable.INTEGER);
    assertThat(evaluateConstant("list_to_columns([1,2], {names: ['foo', 'bar']})"),
        is(Tuple.ofValues(expectedType, 1L, 2L)));

    assertThat(evaluateConstant("list_to_columns([1, 2, 3], {names: ['foo', 'bar']})"),
        is(Tuple.ofValues(expectedType, 1L, 2L)));

    // will pad missing list items with nulls
    assertThat(evaluateConstant("list_to_columns([1], {names: ['foo', 'bar']})"),
        is(Tuple.ofValues(expectedType, 1L, null)));
  }

  @Test
  public void canSplatListWithNamesAndPrefix() {
    // can prefix named items
    Struct expectedType = Struct.of("splat-foo", Nullable.INTEGER, "splat-bar", Nullable.INTEGER);
    assertThat(evaluateConstant("list_to_columns([1,2], {names: ['foo', 'bar'], prefix: 'splat-'})"),
        is(Tuple.ofValues(expectedType, 1L, 2L)));
  }


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

    // will drop list items beyond upTo
    assertThat(evaluate("list_to_columns([1,2,3,4,5,6], {number: 2})", Tuple.EMPTY_TUPLE),
        is(Tuple.ofValues(expectedType, 1L, 2L)));

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

  @Test
  public void canSplatListsWithNumColumnsAndPrefix() {
    Struct expectedType = Struct.of("splat1", Nullable.INTEGER, "splat2", Nullable.INTEGER);
    assertThat(evaluate("list_to_columns([1,2], {number: 2, prefix: 'splat'})", Tuple.EMPTY_TUPLE),
        is(Tuple.ofValues(expectedType, 1L, 2L)));
    assertThat(realized.getResultType(), is(expectedType));
  }

  @Test
  public void canSplatListWithNumColumsStartingAtFirstColumnNum() {
    assertThat(
        evaluateConstant("list_to_columns([1,2,3,4,5], {start_numbering: 5, number: 2, prefix: 'day'})"),
        is(Tuple.ofValues(Struct.of("day5", Nullable.INTEGER, "day6", Nullable.INTEGER), 1L, 2L)));

    assertThat(
        evaluateConstant("list_to_columns([1], {start_numbering: 5, number: 2, prefix: 'day'})"),
        is(Tuple.ofValues(Struct.of("day5", Nullable.INTEGER, "day6", Nullable.INTEGER), 1L, null)));

    assertThat(
        evaluateConstant("list_to_columns([1], {start_numbering: 0, number: 2, prefix: 'day'})"),
        is(Tuple.ofValues(Struct.of("day0", Nullable.INTEGER, "day1", Nullable.INTEGER), 1L, null)));

  }

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

    assertThat(evaluate("list_to_columns([{foo: 'foo0', bar: 10},{foo: 'foo1', bar: 11}], {number: 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 canProduceNoColumns() {
    // sometimes it can be useful to set number: 0 to remove all the attributes
    assertThat(evaluate("list_to_columns([1,2], columns: {number: 0})",
        Tuple.EMPTY_TUPLE),
        is(Tuple.EMPTY_TUPLE)
    );
    assertThat(realized.getResultType(), is(Struct.EMPTY_STRUCT));
  }

  @Test
  public void canOptOutOfNullableColumns() {
    Struct expectedType = Struct.of("foo", Types.INTEGER, "bar", Types.INTEGER);

    assertThat(evaluate("list_to_columns([1,2], columns: {names: ['foo', 'bar'], nullable: false})",
        Tuple.EMPTY_TUPLE),
        is(Tuple.ofValues(expectedType, 1L, 2L))
    );
    assertThat(realized.getResultType(), is(expectedType));
  }

  @Test
  public void canOptIntoNullableColumns() {
    // nullable is the default (but testing for completeness)
    Struct expectedType = Struct.of("foo", Nullable.INTEGER, "bar", Nullable.INTEGER);

    assertThat(evaluate("list_to_columns([1,2], columns: {names: ['foo', 'bar'], nullable: true})",
        Tuple.EMPTY_TUPLE),
        is(Tuple.ofValues(expectedType, 1L, 2L))
    );
    assertThat(realized.getResultType(), is(expectedType));
  }

  @Test
  public void evalFailsWhenInsufficientItemsAndNotNullable() {
    EvalException ex = assertThrows(EvalException.class, () ->
        evaluate("list_to_columns([1], columns: {names: ['foo', 'bar'], nullable: false})", Tuple.EMPTY_TUPLE));
    assertThat(ex.getProblem(), hasAncestorProblem(
        is(ListToColumns.PROBLEMS.insufficientListItemsEncountered(2, 1))
    ));

    // will also get the eval error if a null list was provided
    Struct inputType = Struct.of("items", Nullable.of(RSList.create(Types.INTEGER)));
    ex = assertThrows(EvalException.class, () ->
        evaluate(
          "list_to_columns(items, columns: {names: ['foo', 'bar'], nullable: false})",
          Tuple.ofValues(inputType)
        ));
    assertThat(ex.getProblem(), hasAncestorProblem(
        is(ListToColumns.PROBLEMS.insufficientListItemsEncountered(2, 0))
    ));
    // but realization would have been okay.
    assertThat(realizationProblems, empty());
    assertThat(realized.getResultType(), is(Struct.of("foo", Types.INTEGER, "bar", Types.INTEGER)));
  }

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

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

    assertThat(evaluate("list_to_columns(list: [{foo: 'foo0', bar: 10},{foo: 'foo1', bar: 11}], columns: {number: 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("splat1", Nullable.TEXT, "splat2", Nullable.TEXT);
    assertThat(
        evaluate("list_to_columns(foo, {number: 2, prefix: 'splat'})",
            Tuple.ofValues((Struct)inputStruct, Arrays.asList("foo", "bar"))),
        is(Tuple.ofValues(expectedType, "foo", "bar")));
    assertThat(realized.getResultType(), is(expectedType));

    assertThat(
        evaluate("list_to_columns(foo, {number: 2, prefix: 'splat'})", Tuple.ofValues((Struct)inputStruct)),
        is(Tuple.ofValues(expectedType)));
    assertThat(realized.getResultType(), is(expectedType));
  }

  @Test
  public void errorWhenOptionsInComplete() {
    assertThat(realizeOnly("list_to_columns([1,2], {})", inputStruct),
        failedResult(hasAncestorProblem(
            is(ParamProblems.oneOfTheseRequired("number", "names"))
        )));
  }

  @Test
  public void errorWhenOptionsIncompatible() {
    assertThat(realizeOnly("list_to_columns([1,2], {number: 2, names: ['foo', 'bar', 'baz']})", inputStruct),
        failedResult(hasAncestorProblem(
            is(ParamProblems.get().mutuallyExclusive("number", "names"))
        )));

    assertThat(realizeOnly("list_to_columns([1,2], {start_numbering: 2, names: ['foo', 'bar', 'baz']})", inputStruct),
        failedResult(hasAncestorProblem(
            is(ParamProblems.get().mutuallyExclusive("start_numbering", "names"))
        )));
  }

  @Test
  public void errorWhenOptionsAreWrongType() {
    assertThat(realizeOnly("list_to_columns([1,2], {number: 'foo'})", inputStruct),
        failedResult(hasAncestorProblem(
            is(NumberBinder.PROBLEMS.numberFormatException("foo", Integer.class))
        )));

    assertThat(realizeOnly("list_to_columns([1,2], {start_numbering: 'foo', number: 1})", inputStruct),
        failedResult(hasAncestorProblem(
            is(NumberBinder.PROBLEMS.numberFormatException("foo", Integer.class))
        )));
  }

  @Test
  public void errorWhenNumColumnsIsLessThanZero() {
    assertThat(realizeOnly("list_to_columns([1,2], {number: -1})", inputStruct), failedResult(hasAncestorProblem(
        isProblem(Severity.ERROR, GeneralProblems.class, "valueOutOfRange")
    )));
    assertThat(realizeOnly("list_to_columns([1,2], {number: -100})", inputStruct), failedResult(hasAncestorProblem(
        isProblem(Severity.ERROR, GeneralProblems.class, "valueOutOfRange")
    )));
  }

  @Test
  public void errorWhenOptionsNotConstant() {
    inputStruct = Struct.of("int", Types.INTEGER, "text", Types.TEXT);
    assertThat(realizeOnly("list_to_columns([1,2], {num_column: i})", inputStruct),
        failedResult(hasAncestorProblem(
        is(ExpressionProblems.get().constantRequired(parse("{num_column: i}")))
    )));

    assertThat(realizeOnly("list_to_columns([1,2], {num_column: 1, prefix: text})", inputStruct),
        failedResult(hasAncestorProblem(
        is(ExpressionProblems.get().constantRequired(parse("{num_column: 1, prefix: text}")))
    )));
  }

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

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

}
