/*
 * 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 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.Assert;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.StringFunctions;
import nz.org.riskscape.engine.lookup.LookupTable;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.EvalException;
import nz.org.riskscape.engine.rl.LanguageFunctions;
import nz.org.riskscape.engine.types.LookupTableType;
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.rl.ast.FunctionCall;

public class ToLookupTableScalarTest extends BaseExpressionRealizerTest{

  @Before
  public void setup() {
    project.getFunctionSet().add(new ToLookupTable().asRiskscapeFunction().identified("to_lookup_table"));
    project.getFunctionSet().add(LanguageFunctions.CONCAT);
    project.getFunctionSet().add(LanguageFunctions.NULL_OF);
    project.getFunctionSet().add(LanguageFunctions.MAP);
    project.getFunctionSet().addAll(StringFunctions.FUNCTIONS);
  }


  @Test
  public void canReduceKeyValueStructsToALookupTable() {
    LookupTable result = (LookupTable) evaluate("""
        to_lookup_table(
          [{key: 1, value: 'foo'}, {key: 2, value: 'bar'}, {key: 3, value: 'baz'}, {key: 2, value: 'barbar'}]
        )
        """,
        Tuple.EMPTY_TUPLE
      );

    assertThat(realized, hasProperty(
        "resultType",
        equalTo(LookupTableType.create(Types.INTEGER, RSList.create(Types.TEXT)))
    ));

    assertThat(result.lookup(1L), equalTo(List.of("foo")));
    // ensure that all the values are collected for key: 2
    assertThat(result.lookup(2L), equalTo(List.of("bar", "barbar")));
  }

  @Test
  public void canReduceTuplesDownToALookupTableWithUniqueMappings() {
    LookupTable result = (LookupTable) evaluate("""
        to_lookup_table(
          [{key: 1, value: 'foo'}, {key: 2, value: 'bar'}, {key: 3, value: 'baz'}],
          {unique: true}
        )
        """,
        Tuple.EMPTY_TUPLE
      );

    assertThat(realized, hasProperty(
        "resultType",
        equalTo(LookupTableType.create(Types.INTEGER, Types.TEXT))
    ));

    assertThat(result.lookup(1L), equalTo("foo"));
  }

  @Test
  public void failsIfListNotKeyValueStruct() throws Exception {
    evaluate("""
        to_lookup_table(
          [{keys: 1, value: 'foo'}]
        )
        """,
        Tuple.EMPTY_TUPLE
    );

    assertThat(
        realizationProblems,
        contains(Matchers.hasAncestorProblem(equalTo(TypeProblems.get().mismatch(
            expr.isA(FunctionCall.class).get().getArguments().get(0),
            RSList.create(Struct.of("key",  Types.ANYTHING, "value", Types.ANYTHING)),
            RSList.create(Struct.of("keys",  Types.INTEGER, "value", Types.TEXT))
        ))))
    );
  }

  @Test
  public void failsIfAttemptingToReduceUniquelyWithNonUniqueMappings() {
    EvalException ex = Assert.assertThrows(EvalException.class, () -> evaluate("""
        to_lookup_table(
          [{key: 1, value: 'foo'}, {key: 2, value: 'bar'}, {key: 1, value: 'baz'}],
          {unique: true}
        )
        """,
        Tuple.EMPTY_TUPLE
    ));

    assertThat(
        ex.getProblem(),
        Matchers.hasAncestorProblem(equalTo(ToLookupTable.PROBLEMS.keyNotUnique(1L, List.of("baz", "foo"))))
    );
  }

  @Test
  public void canReduceTuplesWithNullsInThem() {
    LookupTable result = (LookupTable) evaluate("""
        to_lookup_table(
          [
            {key: 1, value: 'foo'},
            {key: 2, value: null_of('text')},
            {key: 3, value: 'baz'}
          ],
          {unique: true}
        )
        """,
        Tuple.EMPTY_TUPLE
    );


    assertThat(realized, hasProperty(
        "resultType",
        // the value type has kept the nullable wrapping.
        equalTo(LookupTableType.create(Types.INTEGER, Nullable.TEXT))
    ));

    assertThat(result.lookup(1L), equalTo("foo"));
    assertThat(result.lookup(2L), nullValue());
  }

  @Test
  public void canReduceTuplesWithNullableKey() {
    LookupTable result = (LookupTable) evaluate("""
        to_lookup_table(
          [
            {key: 1, value: 'foo'},
            {key: null_of('integer'), value: 'bar'},
            {key: 3, value: 'baz'}
          ],
          {unique: true}
        )
        """,
        Tuple.EMPTY_TUPLE
    );


    assertThat(realized, hasProperty(
        "resultType",
        // the key type has kept the nullable wrapping.
        equalTo(LookupTableType.create(Nullable.INTEGER, Types.TEXT))
    ));

    assertThat(result.lookup(1L), equalTo("foo"));
    assertThat(result.lookup(null), equalTo("bar"));
    assertThat(result.lookup(3L), equalTo("baz"));
  }

  @Test
  public void canReduceNullTuples() {
    LookupTable result = (LookupTable) evaluate("""
        to_lookup_table(
          concat(
            [
              {key: 1, value: 'foo'},
              {key: 2, value: 'bar'},
              {key: 3, value: 'baz'},
            ],
            [null_of('struct(key: integer, value: text)')]
          ),
          {unique: true}
        )
        """,
        Tuple.EMPTY_TUPLE
    );


    assertThat(realized, hasProperty(
        "resultType",
        equalTo(LookupTableType.create(Types.INTEGER, Types.TEXT))
    ));

    assertThat(result.lookup(1L), equalTo("foo"));
  }

  @Test
  public void handlesANullListInput() {
    Struct itemType = Struct.of("key", Types.TEXT, "value", Types.TEXT);
    Struct inputType = Struct.of("list", Nullable.of(RSList.create(itemType)));
    assertThat(
        evaluate("to_lookup_table(list, {unique: true})", Tuple.ofValues(inputType)),
        is(nullValue())
    );
    assertThat(realized, hasProperty(
        "resultType",
        equalTo(Nullable.of(LookupTableType.create(Types.TEXT, Types.TEXT)))
    ));
  }

  @Test
  public void surplusKeysAreIgnored() {
    LookupTable result = (LookupTable) evaluate("""
        to_lookup_table(
          [
            {key: 1, value: 'foo', extra: true},
            {key: 2, value: 'bar', extra: true},
            {key: 3, value: 'baz', extra: true}
          ]
        )
        """,
        Tuple.EMPTY_TUPLE
    );


    assertThat(realized, hasProperty(
        "resultType",
        equalTo(LookupTableType.create(Types.INTEGER, RSList.create(Types.TEXT)))
    ));

    assertThat(result.lookup(1L), equalTo(List.of("foo")));
  }

  @Test
  public void canUseAMappingFunctionToConvertInput() {
    // this is just advertising that this is the way you adapt lists to be converted in to a lookup table
    LookupTable result = (LookupTable) evaluate("""
        to_lookup_table(
          map([1], element -> {key: element, value: str(element)}),
          {unique: true}
        )
        """,
        Tuple.EMPTY_TUPLE
    );

    assertThat(realized, hasProperty(
        "resultType",
        equalTo(LookupTableType.create(Types.INTEGER, Types.TEXT))
    ));

    assertThat(result.lookup(1L), equalTo("1"));
  }

  @Test
  public void canBuildLookupTableFromEmtpyList() {
    // sometimes lists are empty. we need to know the lookup is built as expected
    Struct itemType = Struct.of("key", Types.INTEGER, "value", Types.TEXT);
    Struct inputType = Struct.of("items", RSList.create(itemType));

    LookupTable result = (LookupTable) evaluate("""
        to_lookup_table(
          items,
          {unique: true}
        )
        """,
        Tuple.ofValues(inputType, Arrays.asList())
    );

    assertThat(realized, hasProperty(
        "resultType",
        equalTo(LookupTableType.create(Types.INTEGER, Types.TEXT))
    ));

    // we'll only ever get nullValues out
    assertThat(result.lookup(1L), nullValue());
    assertThat(result.lookup(10L), nullValue());
  }
}
