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

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

import java.util.Arrays;
import java.util.Collections;

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

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.StringFunctions;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.DefaultOperators;
import nz.org.riskscape.engine.rl.LogicFunctions;
import nz.org.riskscape.engine.rl.MathsFunctions;
import nz.org.riskscape.engine.types.LambdaType;
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.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

public class MapListFunctionTest extends BaseExpressionRealizerTest {

  @Before
  public void addFunctions() {
    project.getFunctionSet().add(new MapList().identified("map"));
    project.getFunctionSet().insertFirst(DefaultOperators.INSTANCE);
    project.getFunctionSet().addAll(MathsFunctions.FUNCTIONS);
    project.getFunctionSet().addAll(StringFunctions.FUNCTIONS);
    project.getFunctionSet().addAll(LogicFunctions.LOGIC_FUNCTIONS);
  }

  @Test
  public void canDoSomeMathsOnElementsOfaList() throws Exception {
    evaluate("map([1, 2, 3], el -> el + el)", Tuple.EMPTY_TUPLE);
    assertThat(realizationProblems, empty());
    assertThat(realized.getResultType(), equalTo(RSList.create(Types.INTEGER)));
    assertEquals(
      evaluated,
      Arrays.asList(2L, 4L, 6L)
    );
  }

  @Test
  public void canConvertElementsOfOneListToAnotherType() throws Exception {
    evaluate("map([1, 2, 3], el -> '$' + str(el))", Tuple.EMPTY_TUPLE);
    assertThat(realizationProblems, empty());
    assertThat(realized.getResultType(), equalTo(RSList.create(Types.TEXT)));
    assertEquals(
      evaluated,
      Arrays.asList("$1", "$2", "$3")
    );
  }

  @Test
  public void realizationFailsIfExpressionDoesNotRealizeAgainstInput() throws Exception {
    evaluate("map([1, 2, 3], el -> '$' + el)", Tuple.EMPTY_TUPLE);
    assertThat(
      realizationProblems,
      contains(
        Matchers.hasAncestorProblem(
          Matchers.equalIgnoringChildren(
              ExpressionProblems.get().failedToRealize(
                  parse("'$' + el"),
                  Struct.of("el", Types.INTEGER)
              )
          )
        )
      )
    );
  }

  @Test
  public void realizationFailsIfExpressionDoesNotRealizeAgainstInputAndNotAList() throws Exception {
    evaluate("map(1, el -> '$' + el)", Tuple.EMPTY_TUPLE);
    assertThat(
      realizationProblems,
      contains(
        Matchers.hasAncestorProblem(
          Matchers.equalIgnoringChildren(
              ExpressionProblems.get().failedToRealize(
                  parse("'$' + el"),
                  Struct.of("el", Types.INTEGER)
              )
          )
        )
      )
    );
  }

  @Test
  public void anEmptyListIsMappedToAnotherEmptyList() throws Exception {
    Struct inputType = Struct.of("list", RSList.create(Types.INTEGER));
    evaluate("map(list, el -> '$' + str(el))", Tuple.ofValues(inputType, Collections.emptyList()));
    assertThat(realizationProblems, empty());
    assertThat(realized.getResultType(), equalTo(RSList.create(Types.TEXT)));
    assertEquals(
      evaluated,
      Collections.emptyList()
    );
  }

  @Test
  public void listElementNameReplacesAnythingElseInScope() throws Exception {
    // foo is replaced, bar is from the scope
    evaluate("map([1, 2, 3], foo -> foo + bar)", tuple("{foo: 3.0, bar: 5}"));
    assertThat(realizationProblems, empty());
    assertThat(realized.getResultType(), equalTo(RSList.create(Types.INTEGER)));
    assertEquals(
      evaluated,
      Arrays.asList(6L, 7L, 8L)
    );
  }

  @Test
  public void callsTheExpressionIfArgNotAList() {
    evaluate("map(1, foo -> foo + 2)", Tuple.EMPTY_TUPLE);
    assertThat(realizationProblems, empty());
    assertThat(realized.getResultType(), equalTo(Types.INTEGER));
    assertEquals(
      evaluated,
      3L
    );
  }

  @Test
  public void canMapANullableList() {
    Type listType = Nullable.of(RSList.create(Types.INTEGER));
    Struct inputType = Struct.of("value", listType);

    assertThat(evaluate("map(value, i -> i + i)", Tuple.ofValues(inputType)), nullValue());
    assertThat(realized.getResultType(), is(listType));

    assertThat(evaluate("map(value, i -> i + i)", Tuple.ofValues(inputType, Lists.newArrayList(1L, 2L, 3L))),
        is(Lists.newArrayList(2L, 4L, 6L)));
    assertThat(realized.getResultType(), is(listType));
  }

  @Test
  public void canMapANullableItem() {
    Type itemType = Nullable.INTEGER;
    Struct inputType = Struct.of("value", itemType);

    assertThat(evaluate("map(value, i -> i + i)", Tuple.ofValues(inputType)), nullValue());
    assertThat(realized.getResultType(), is(itemType));

    assertThat(evaluate("map(value, i -> i + i)", Tuple.ofValues(inputType, 3L)), is(6L));
    assertThat(realized.getResultType(), is(itemType));
  }

  @Test
  public void canMapUsingOuterScope() {
    Struct inputType = Struct.of("mode", Types.TEXT, "items", RSList.create(Types.INTEGER));
    Tuple input1 = Tuple.ofValues(inputType, "foo", Arrays.asList(1L, 2L));
    Tuple input2 = Tuple.ofValues(inputType, "bar", Arrays.asList(1L, 2L));

    assertEquals(
        evaluate("map(items, i -> if(mode = 'foo', i, i * 2))", input1),
        Arrays.asList(1L, 2L)
    );
    assertEquals(
        evaluate("map(items, i -> if(mode = 'foo', i, i * 2))", input2),
        Arrays.asList(2L, 4L)
    );
  }

  @Test
  public void givesAnErrorIfNotGivenALambda() throws Exception {
    evaluate("map([1, 2, 3], 1)", Tuple.EMPTY_TUPLE);

    assertThat(
        realizationProblems,
        contains(Matchers.hasAncestorProblem(
            equalTo(Problems.get(TypeProblems.class).mismatch(
                new FunctionCall.Argument(parse("1")),
                new LambdaType("foo"),
                Types.INTEGER
            ))
        ))
    );
  }

  @Test
  public void givesAnErrorIfWrongNumberOfLambdaArgs() throws Exception {
    evaluate("map([1, 2, 3], (foo, bar) -> foo + bar)", Tuple.EMPTY_TUPLE);

    assertThat(
        realizationProblems,
        contains(Matchers.hasAncestorProblem(
            equalTo(ExpressionProblems.get().lambdaArityError(parse("(foo, bar) -> foo + bar"), 2, 1))
        ))
      );
  }

  @Test
  public void canCloseOverScopeWithoutSideEffects_GL1414() throws Exception {
    assertThat(
        evaluate("map([1, 2, 3], (el) -> *)", Tuple.EMPTY_TUPLE),
        equalTo(tuples("[{el: 1}, {el: 2}, {el: 3}]"))
    );
  }
}
