/*
 * 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 org.junit.Before;
import org.junit.Test;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.function.IdentifiedFunction.Category;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.rl.agg.AggregationFunction;
import nz.org.riskscape.engine.rl.agg.BaseAggregationFunctionTest;
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.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.rl.ast.ExpressionProblems;

public class BucketRangeFunctionTest extends BaseAggregationFunctionTest {

  Struct inputType = Types.INTEGER.asStruct();

  BucketRange bucketRange = new BucketRange(new BucketFunction());

  @Before
  public void setup() {
    project.getFunctionSet().add(
        AggregationFunction.asFunction(bucketRange).builtin("bucket_range", Category.MISC)
    );
  }

  @Test
  public void canBucketAllValuesByDefault() {
    tuples = ListRelation.ofValues(1L, 2L, 3L, 4L).getList();

    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(*),"
        + "  range: [0, 10]"
        + ")"));

    process();
    assertThat(serialResult, equalTo(tuple("{\"range_<_0\": 0, range_0_10: 4, \"range_10_+\": 0}")));

    tuples = ListRelation.ofValues(-10L, 1L, 2L, 3L, 4L, 100L).getList();
    process();
    assertThat(serialResult, equalTo(tuple("{\"range_<_0\": 1, range_0_10: 4, \"range_10_+\": 1}")));
  }

  @Test
  public void canBucketAllFloatingRangeValuesByDefault() {
    // same as last test, but with floating ranges this time
    tuples = ListRelation.ofValues(1L, 2L, 3L, 4L).getList();

    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(*),"
        + "  range: [1.1, 3.5]"
        + ")"));

    process();
    assertThat(serialResult, equalTo(tuple("{\"range_<_1_1\": 1, \"range_1_1_3_5\": 2, \"range_3_5_+\": 1}")));

    tuples = ListRelation.ofValues(-10L, 1L, 2L, 3L, 4L, 100L).getList();
    process();
    assertThat(serialResult, equalTo(tuple("{\"range_<_1_1\": 2, \"range_1_1_3_5\": 2, \"range_3_5_+\": 2}")));
  }

  @Test
  public void canCountOccurrencesWithinRanges() {
    tuples = ListRelation.ofValues(1L, 2L, 3L, 4L).getList();

    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(*),"
        + "  range: [0, 10, maxint()],"
        + "  options: { add_bounds: false }"
        + ")"));

    process();
    assertThat(serialResult, equalTo(tuple("{range_0_10: 4, \"range_10_+\": 0}")));

    tuples = ListRelation.ofValues(-10L, 1L, 2L, 3L, 4L, 100L).getList();

    process();
    // note that -10 gets ignored because it falls outside any bucket
    assertThat(serialResult, equalTo(tuple("{range_0_10: 4, \"range_10_+\": 1}")));
  }

  @Test
  public void canCountAndSumOccurrencesWithinRanges() {
    tuples = ListRelation.ofValues(1L, 2L, 3L, 4L, -1L, -2L, -3L, -4L).getList();

    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: abs(value * 4),"
        + "  select: {count(*) as count, sum(abs(value)) as sum},"
        + "  range: [0, 10, maxint()],"
        + "  options: { add_bounds: false }"
        + ")"));

    process();
    assertThat(serialResult, equalTo(tuple("{range_0_10: {count: 4, sum: 6}, \"range_10_+\": {count: 4, sum: 14}}")));
  }

  @Test
  public void canBucketNullableNumericValues() {
    // as most loss values end up as nullable, it's nice to be able to bucket them easily
    inputType = Nullable.INTEGER.asStruct();
    tuples = ListRelation.ofTypedValues(inputType, 1L, 2L, null, 3L, 4L, 10L).getList();

    realizeAggregate(inputType,
        parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(*),"
        + "  range: [0, 10, maxint()],"
        + "  options: { add_bounds: false }"
        + ")"));

    process();
    // note that null isn't bucketed/counted
    assertThat(serialResult, equalTo(tuple("{range_0_10: 4, \"range_10_+\": 1}")));

    // sanity-check that bucketing solely null values gives us zero
    tuples = ListRelation.ofTypedValues(inputType, null, null, null).getList();
    process();
    assertThat(serialResult, equalTo(tuple("{range_0_10: 0, \"range_10_+\": 0}")));
  }

  @Test
  public void canConcatenateLiteralRanges() {
    // this can be useful if you want the ranges to be partly parameterizable, but
    // also want certain values (e.g. maxint()) to always be present in the results
    tuples = ListRelation.ofValues(1L, 2L, 3L, 4L).getList();

    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(*),"
        + "  range: concat([0, 10], [maxint()])," + "  options: { add_bounds: false }"
        + ")"));

    process();
    assertThat(serialResult, equalTo(tuple("{range_0_10: 4, \"range_10_+\": 0}")));
  }

  @Test
  public void canSpecifyUnorderedRange() {
    tuples = ListRelation.ofValues(0L, 1L, 2L, 3L, 4L, 23L).getList();

    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(*),"
        + "  range: [ 10, 0, maxint(), 1 ]," + "  options: { add_bounds: false }"
        + ")"));

    process();
    assertThat(serialResult, equalTo(tuple("{range_0_1: 1, range_1_10: 4, \"range_10_+\": 1}")));
  }

  @Test
  public void cannotSpecifyNonNumericRange() {
    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(*),"
        + "  range: [ 'foo', 'bar', 'baz' ]"
        + ")"));

    assertThat(
        realizationProblems,
        contains(hasAncestorProblem(
        is(problemWith("range").withChildren(
                TypeProblems.get().listItemMismatch(Number.class, Types.TEXT)))
        ))
      );
  }

  @Test
  public void canSpecifyRangeWithMixedNumberTypes() {
    tuples = ListRelation.ofValues(0L, 1L, 2L, 3L, 4L, 23L).getList();

      // list of mixed number types -> list(floating)
    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(*),"
        + "  range: [ 0, 2.5, 10 ]"
        + ")"));

    process();
    assertThat(serialResult,
        equalTo(tuple("{\"range_<_0_0\": 0, \"range_0_0_2_5\": 3, \"range_2_5_10_0\": 2, \"range_10_0_+\": 1}")));
  }

  @Test
  public void canSpecifyRangeWithMixedNumberTypesAnd_add_bounds_false_GL1398() {
    tuples = ListRelation.ofValues(0L, 1L, 2L, 3L, 4L, 23L).getList();

      // list of mixed number types -> list(floating)
    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(*),"
        + "  range: [ 0, 2.5, 10 ],"
        + "  options: {add_bounds: false}"
        + ")"));

    process();
    assertThat(serialResult,
        equalTo(tuple("{\"range_0_0_2_5\": 3, \"range_2_5_10_0\": 2}")));
  }

  @Test
  public void pickMustBeAnExpressionThatIsComparableToTheRange() throws Exception {
    tuples = ListRelation.ofValues("1", "2", "3", "4").getList();
    inputType = Types.INTEGER.asStruct();

    // attribute doesn't exist
    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: vols,"
        + "  select: sum(int(value)),"
        + "  range: [0, 5, 10]"
        + ")"));

    assertThat(
      realizationProblems,
      contains(hasAncestorProblem(
      equalIgnoringChildren(problemWith("pick"))
      ))
    );

    // attribute doesn't compare (isn't numeric)
    inputType = Types.TEXT.asStruct();
    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: sum(int(value)),"
        + "  range: [0, 5, 10]"
        + ")"));

    assertThat(
      realizationProblems,
      contains(hasAncestorProblem(equalIgnoringChildren(
          ArgsProblems.get().notNumeric(bucketRange.getArguments().get(0), Types.TEXT)
      )))
    );
  }

  @Test
  public void rangeMustBeAConstantListWithAtLeastTwoElements() throws Exception {
    // range not constant
    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(value),"
        + "  range: [value, value]"
        + ")"));

    assertThat(
      realizationProblems,
      contains(hasAncestorProblem(equalTo(
        problemWith("range",
          ExpressionProblems.get().constantRequired(parse("[value, value]"))
        )
      )))
    );

    // range not a list
    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(value),"
        + "  range: {a: 1, b: 2}"
        + ")"));

    assertThat(
      realizationProblems,
      contains(hasAncestorProblem(equalTo(
        problemWith("range",
          TypeProblems.get().mismatch(
            parse("{a: 1, b: 2}"),
            RSList.LIST_ANYTHING,
            Struct.of("a", Types.INTEGER, "b", Types.INTEGER)
          )
        )
      )))
    );

    // range not big enough
    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(value),"
        + "  range: []"
        + ")"));

    assertThat(
      realizationProblems,
      contains(hasAncestorProblem(equalTo(
        problemWith("range").withChildren(
          GeneralProblems.get().badListLength("1+", 0)
        )
      )))
    );

    // range without bounds not big enough
    realizeAggregate(inputType, parse(""
        + "bucket_range("
        + "  pick: value,"
        + "  select: count(value),"
        + "  range: [0],"
        + "  options: {add_bounds: false}"
        + ")"));

    assertThat(
      realizationProblems,
      contains(hasAncestorProblem(equalTo(
        problemWith("range", GeneralProblems.get().badListLength("2+", 1))
      )))
    );
  }

  private Problem problemWith(String argsName, Problem... children) {
    return Problems.foundWith(bucketRange.getArguments().get(argsName), children);
  }
}
