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

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

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.DefaultOperators;
import nz.org.riskscape.engine.rl.LanguageFunctions;
import nz.org.riskscape.engine.rl.LogicFunctions;
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.rl.ast.ExpressionProblems;

public class FilterListTest extends BaseExpressionRealizerTest {

  Struct itemType = Struct.of("foo", Types.TEXT, "bar", Nullable.INTEGER);
  RSList listType = RSList.create(Nullable.of(itemType));
  Struct inputType = Struct.of("items", listType);

  Tuple itemOne = Tuple.ofValues(itemType, "one", 1L);
  Tuple itemTwo = Tuple.ofValues(itemType, "two", 2L);
  Tuple itemThree = Tuple.ofValues(itemType, "three", null);

  FilterList filterList = new FilterList();

  @Before
  public void addFunctions() {
    project.getFunctionSet().add(filterList.identified("filter"));
    project.getFunctionSet().insertFirst(DefaultOperators.INSTANCE);
    project.getFunctionSet().addAll(LogicFunctions.LOGIC_FUNCTIONS);
    project.getFunctionSet().add(LanguageFunctions.NULL_OF);
  }

  @Test
  public void canFilterLists() {
    evaluate("filter(items, i ->  i.bar > 1)", inputOf(itemOne, itemTwo, itemThree));
    assertThat(realizationProblems, empty());
    assertThat(realized.getResultType(), equalTo(listType));
    assertThat(getEvaluated(), contains(
        itemTwo
    ));

    evaluate("filter(items, i ->  is_null(i.bar) or i.bar > 1)", inputOf(itemOne, itemTwo, itemThree));
    assertThat(realizationProblems, empty());
    assertThat(realized.getResultType(), equalTo(listType));
    assertThat(getEvaluated(), contains(
        itemTwo,
        itemThree
    ));
  }

  @Test
  public void nullTestResultIsFalsy() throws Exception {
    assertThat(
      evaluate("filter([1, 2, 3], x -> if(x = 1, then: true, else: null))", Tuple.EMPTY_TUPLE),
      equalTo(List.of(1L))
    );
  }

  @Test
  public void canFilterListsReturningGivenType() {
    evaluate("filter([1,2,3,4], i ->  i > 2)", Tuple.EMPTY_TUPLE);
    assertThat(realizationProblems, empty());
    // to show that we don't get nullables added if they don't exist in the input
    assertThat(realized.getResultType(), equalTo(RSList.create(Types.INTEGER)));
    assertEquals(evaluated, Arrays.asList(3L, 4L));
  }

  @Test
  public void canFilterListsContainingNullItems() {
    evaluate("filter(items, i ->  i.foo = 'one')", inputOf(null, itemOne, null, itemTwo, itemThree));
    assertThat(realizationProblems, empty());
    assertThat(realized.getResultType(), equalTo(listType));
    assertThat(getEvaluated(), contains(
        itemOne
    ));

    // can keep those null items too if we want to
    evaluate("filter(items, i ->  i.foo = 'one' or is_null(i))", inputOf(null, itemOne, null, itemTwo, itemThree));
    assertThat(realizationProblems, empty());
    assertThat(realized.getResultType(), equalTo(listType));
    assertThat(getEvaluated(), contains(
        null,
        itemOne,
        null
    ));
  }

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

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

  @Test
  public void errorWrongNumberOfArgs() {
    // not enough args
    evaluate("filter([1, 2, 3])", Tuple.EMPTY_TUPLE);

    assertThat(
        realizationProblems,
        contains(Matchers.hasAncestorProblem(
            equalTo(
                ArgsProblems.get().wrongNumber(2, 1))
        ))
    );

    // too many args
    evaluate("filter([1, 2, 3], i -> i > 2, 'foo')", Tuple.EMPTY_TUPLE);

    assertThat(
        realizationProblems,
        contains(Matchers.hasAncestorProblem(
            equalTo(
                ArgsProblems.get().wrongNumber(2, 3))
        ))
    );
  }

  @Test
  public void errorOnWrongArgType() {
    // iterable not a list
    evaluate("filter('foo', i -> i = 'foo')", Tuple.EMPTY_TUPLE);

    assertThat(
        realizationProblems,
        contains(Matchers.hasAncestorProblem(
            equalTo(
                ArgsProblems.mismatch(filterList.getArguments().get(0), Types.TEXT)
            )
        ))
    );

    // test not a lambda
    evaluate("filter([1,2,3], 'foo')", Tuple.EMPTY_TUPLE);

    assertThat(
        realizationProblems,
        contains(Matchers.hasAncestorProblem(
            equalTo(
                ArgsProblems.mismatch(filterList.getArguments().get(1), Types.TEXT)
            )
        ))
    );

  }

  @Test
  public void givesAnErrorIfWrongNumberOfLambdaArgs() throws Exception {
    evaluate("filter([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 givesAnErrorIfLambdaDoesNotReturnBoolean() throws Exception {
    evaluate("filter([1, 2, 3], (i) -> 'true')", Tuple.EMPTY_TUPLE);

    assertThat(
        realizationProblems,
        contains(Matchers.hasAncestorProblem(
            equalTo(FilterList.LOCAL_PROBLEMS.testLambdaRequireBooleanResult(Types.TEXT))
        ))
      );
  }

  List<Tuple> getEvaluated() {
    return (List<Tuple>) evaluated;
  }

  Tuple inputOf(Tuple... items) {
    return Tuple.ofValues(inputType, Arrays.asList(items));
  }

}
