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

import static nz.org.riskscape.engine.Matchers.*;
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.defaults.function.ToLookupTable;
import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.function.IdentifiedFunction.Category;
import nz.org.riskscape.engine.lookup.LookupTable;
import nz.org.riskscape.engine.rl.agg.BaseAggregationFunctionTest;
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 ToLookupTableTest extends BaseAggregationFunctionTest {

  Struct inputType = Struct.of("key", Types.TEXT, "value", Types.INTEGER);

  @Before
  public void setup() {
    project.getFunctionSet().add(new ToLookupTable().asRiskscapeFunction().builtin("to_lookup_table", Category.MISC));
  }

  @Test
  public void canReduceTuplesDownToALookupTableWithUniqueMappings() {
    tuples = tuples(inputType, "['foo', 1]", "['bar', 2]", "['baz', 3]");

    realizeAggregate(inputType, parse("to_lookup_table(key, value, {unique: true})"));

    Object resultObject = process();
    assertThat(realized.getResultType(), equalTo(new LookupTableType(Types.TEXT, Types.INTEGER)));

    assertThat(resultObject, isA(LookupTable.class));
    LookupTable result = (LookupTable) resultObject;

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

  @Test
  public void failsIfAttemptingToReduceUniquelyWithNonUniqueMappings() {
    tuples = tuples(inputType, "['foo', 1]", "['foo', 2]");

    realizeAggregate(inputType, parse("to_lookup_table(key, value, {unique: true})"));

    RiskscapeException ex = Assert.assertThrows(RiskscapeException.class, () -> process());
    assertThat(ex.getProblem(), equalTo(ToLookupTable.PROBLEMS.keyNotUnique("foo", Arrays.asList(2L, 1L))));
    assertThat(realized.getResultType(), equalTo(new LookupTableType(Types.TEXT, Types.INTEGER)));
  }

  @Test
  public void canReduceTuplesDownToALookupTable() throws Exception {
    this.assertSerialAndParallelEqual = false;
    tuples = tuples(inputType, "['foo', 1]", "['bar', 2]", "['baz', 3]", "['foo', 2]");

    realizeAggregate(inputType, parse("to_lookup_table(key, value)"));

    process();

    assertThat(realized.getResultType(), equalTo(new LookupTableType(Types.TEXT, RSList.create(Types.INTEGER))));

    for (Object resultObject : Arrays.asList(serialResult, parallelResult)) {
      assertThat(resultObject, isA(LookupTable.class));
      LookupTable result = (LookupTable) resultObject;

      assertThat((List<?>) result.lookup("foo"), containsInAnyOrder(1L, 2L));
      assertThat((List<?>) result.lookup("bar"), contains(2L));
      assertThat((List<?>) result.lookup("baz"), contains(3L));
    }
  }

  @Test
  public void canReduceTuplesWithNullsInThem() throws Exception {
    this.assertSerialAndParallelEqual = false;
    inputType = Struct.of("key", Nullable.TEXT, "value", Nullable.INTEGER);
    tuples = tuples(
        inputType,
        "['foo', 1]",
        "['bar', 2]",
        "['baz', 3]",
        "['foo', null_of('integer')]",
        "[null_of('text'), 4]",
        "[null_of('text'), 5]"
    );

    realizeAggregate(inputType, parse("to_lookup_table(key, value)"));

    assertThat(realized.getResultType(), equalTo(new LookupTableType(Nullable.TEXT, RSList.create(Nullable.INTEGER))));

    process();

    for (Object resultObject : Arrays.asList(serialResult, parallelResult)) {
      assertThat(resultObject, isA(LookupTable.class));
      LookupTable result = (LookupTable) resultObject;

      assertThat((List<?>) result.lookup("foo"), containsInAnyOrder(equalTo(1L), nullValue()));
      assertThat((List<?>) result.lookup("bar"), contains(2L));
      assertThat((List<?>) result.lookup("baz"), contains(3L));
      assertThat((List<?>) result.lookup(null), containsInAnyOrder(4L, 5L));
    }
  }

  @Test
  public void failsToRealizeIfThirdArgNotAStruct() throws Exception {
    FunctionCall fc = parse("to_lookup_table(key, value, true)").isA(FunctionCall.class).get();
    realizeAggregate(inputType, fc);

    assertThat(
        realizationProblems,
        contains(hasAncestorProblem(equalTo(
            TypeProblems.get().mismatch(parse("true"), Struct.of("unique", Types.BOOLEAN), Types.BOOLEAN)
        )))
    );
  }
}
