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

import static nz.org.riskscape.engine.Matchers.*;

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

import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

import org.junit.Test;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.rl.agg.ListCollecting.LocalProblems;
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.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

@SuppressWarnings("unchecked")
public class PercentileAggregationFunctionTest extends BaseAggregationFunctionTest {

  @Test
  public void doesSinglePercentileAggregation() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("percentile(value, 50)")).get();

    Type resultType = Types.INTEGER;
    assertThat(realized.getResultType(), is(resultType));

    tuples = tuples(inputType, "[1]", "[2]", "[5]", "[4]", "[3]");
    assertThat(process(), is(3L));
  }

  @Test
  public void p75Percentile() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("percentile(value, 75)")).get();

    Type resultType = Types.INTEGER;
    assertThat(realized.getResultType(), is(resultType));

    tuples = LongStream.range(1, 101)
        .mapToObj(l -> Tuple.ofValues(inputType, l))
        .collect(Collectors.toList());
    assertThat(process(), is(76L));
  }

  @Test
  public void p90Percentile() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("percentile(value, 90)")).get();

    Type resultType = Types.INTEGER;
    assertThat(realized.getResultType(), is(resultType));

    tuples = LongStream.range(1, 101)
        .mapToObj(l -> Tuple.ofValues(inputType, l))
        .collect(Collectors.toList());
    assertThat(process(), is(91L));
  }

  @Test
  public void p95Percentile() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("percentile(value, 95)")).get();

    Type resultType = Types.INTEGER;
    assertThat(realized.getResultType(), is(resultType));

    tuples = LongStream.range(1, 101)
        .mapToObj(l -> Tuple.ofValues(inputType, l))
        .collect(Collectors.toList());
    assertThat(process(), is(96L));
  }

  @Test
  public void p99Percentile() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("percentile(value, 99)")).get();

    Type resultType = Types.INTEGER;
    assertThat(realized.getResultType(), is(resultType));

    tuples = LongStream.range(1, 101)
        .mapToObj(l -> Tuple.ofValues(inputType, l))
        .collect(Collectors.toList());
    assertThat(process(), is(100L));
  }

  @Test
  public void doesPercentileAggregationWithExclusiveMode() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("percentiles(value, [10,25,50,75,90])")).get();

    Struct resultType = Struct.of("P10", Types.INTEGER, "P25", Types.INTEGER, "P50", Types.INTEGER)
        .and("P75", Types.INTEGER).and("P90", Types.INTEGER);
    assertThat(realized.getResultType(), is(resultType));

    tuples = LongStream.range(1, 11)
        .mapToObj(l -> Tuple.ofValues(inputType, l))
        .collect(Collectors.toList());
    assertThat((Tuple) process(), is(Tuple.ofValues(resultType, 2L, 3L, 6L, 8L, 10L)));
  }

  @Test
  public void doesPercentileAggregation() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("percentiles(value, [0,50,100])")).get();

    Struct resultType = Struct.of("P00", Types.INTEGER, "P50", Types.INTEGER, "P100", Types.INTEGER);
    assertThat(realized.getResultType(), is(resultType));

    tuples = tuples(inputType, "[1]", "[2]", "[5]", "[4]", "[3]");
    assertThat((Tuple)process(), is(Tuple.ofValues(resultType, 1L, 3L, 5L)));
  }

  @Test
  public void doesPercentileAggregationFloating() {
    Struct inputType = norm(Types.FLOATING.asStruct());
    realized = realizeAggregate(inputType, parse("percentiles(value, [0,50,100])")).get();

    Struct resultType = Struct.of("P00", Types.FLOATING, "P50", Types.FLOATING, "P100", Types.FLOATING);
    assertThat(realized.getResultType(), is(resultType));

    tuples = tuples(inputType, "[0.1]", "[0.2]", "[0.5]", "[0.4]", "[0.3]");
    assertThat((Tuple)process(), is(Tuple.ofValues(resultType, 0.1D, 0.3D, 0.5D)));
  }

  @Test
  public void doesPercentileAggregationSingle() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("percentiles(value, [50])")).get();

    // A single percentile value gets wrapped in a struct. Maybe we'll add a function for only
    // one value that returns a simple type.
    Struct resultType = Struct.of("P50", Types.INTEGER);
    assertThat(realized.getResultType(), is(resultType));

    tuples = tuples(inputType, "[1]", "[2]", "[5]", "[4]", "[3]");
    assertThat((Tuple)process(), is(Tuple.ofValues(resultType, 3L)));
  }

  @Test
  public void nullValuesDoNotAffectResult() {
    Struct inputType = norm(Nullable.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("percentiles(value, [0, 100])")).get();

    // we check 0 and 100 percentile because if nulls were included in the list, then they should be
    // at the start but certainly not he middle of the list.
    Struct resultType = Struct.of("P00", Types.INTEGER, "P100", Types.INTEGER);
    assertThat(realized.getResultType(), is(Nullable.of(resultType)));

    assertThat(this.process(), is(nullValue()));

    tuples = tuples(inputType, "[]", "[2]", "[]", "[2]", "[5]", "[]", "[4]", "[]", "[3]");
    assertThat((Tuple)process(), is(Tuple.ofValues(resultType, 2L, 5L)));
  }

  @Test
  public void nullResultWhenNothingAccumulated() {
    Struct inputType = norm(Nullable.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("percentiles(value, [0, 100])")).get();

    Struct resultType = Struct.of("P00", Types.INTEGER, "P100", Types.INTEGER);
    assertThat(realized.getResultType(), is(Nullable.of(resultType)));

    assertThat(this.process(), is(nullValue()));
  }

  @Test
  public void percentileCalledAsFunction() {
    RSList listType = RSList.create(Types.INTEGER);
    Struct inputType = Struct.of("items", listType);
    RealizedExpression rExpr = realizationContext.getExpressionRealizer()
        .realize(inputType, parse("percentile(items, 75)")).get();

    Type resultType = Types.INTEGER;
    // result type is nullable because the list could be empty
    assertThat(rExpr.getResultType(), is(Nullable.of(resultType)));

    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, Arrays.asList())), is(nullValue()));

    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, Arrays.asList(3L, 4L, 3L, 5L))), is(5L));
  }

  @Test
  public void percentilesCanComeFromMathsExpresssions() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    realized = realizeAggregate(inputType, parse("percentiles(value, [0, 20 + 30, 30 * 2])")).get();

    Struct resultType = Struct.of("P00", Types.INTEGER, "P50", Types.INTEGER, "P60", Types.INTEGER);
    assertThat(realized.getResultType(), is(resultType));

    tuples = tuples(inputType, "[1]", "[2]", "[5]", "[4]", "[3]");
    assertThat((Tuple)process(), is(Tuple.ofValues(resultType, 1L, 3L, 4L)));
  }

  @Test
  public void percentilesCannotComeFromInputType() {
    Struct inputType = norm(Struct.of("value", Types.INTEGER, "percentiles", RSList.create(Types.INTEGER)));
    assertThat(realizeAggregate(inputType, parse("percentiles(value, percentiles)")), failedResult(hasAncestorProblem(
            is(ExpressionProblems.get().constantRequired(parse("percentiles")))
        )));
  }

  @Test
  public void errorWhenValueNotNumeric() {
    Struct inputType = norm(Types.TEXT.asStruct());
    assertThat(realizeAggregate(inputType, parse("percentiles(value, [0,50,100])")), failedResult(hasAncestorProblem(
        equalIgnoringChildren(
            LocalProblems.get().valueNotNumeric("percentiles", Types.TEXT))
        )));
  }

  @Test
  public void errorWhenPercentilesNotNumeric() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    assertThat(realizeAggregate(inputType, parse("percentiles(value, ['cat', 'dog'])")), failedResult(
        hasAncestorProblem(equalIgnoringChildren(
            TypeProblems.get().mismatch(new FunctionCall.Argument(parse("['cat', 'dog']")), Types.INTEGER, Types.TEXT)
        ))
    ));
  }

  @Test
  public void errorWhenPercentilesNotList() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    assertThat(realizeAggregate(inputType, parse("percentiles(value, 75)")), failedResult(hasAncestorProblem(
        equalIgnoringChildren(
            TypeProblems.get().mismatch(new FunctionCall.Argument(parse("75")),
                PercentileAggregationFunction.PERCENTILES_TYPE, Types.INTEGER))
    )));
  }

  @Test
  public void errorWhenPercentileNotNumeric() {
    Struct inputType = norm(Types.INTEGER.asStruct());
    assertThat(realizeAggregate(inputType, parse("percentile(value, 'cat')")), failedResult(hasAncestorProblem(
        equalIgnoringChildren(
            TypeProblems.get().mismatch(new FunctionCall.Argument(parse("'cat'")), Types.INTEGER, Types.TEXT))
    )));
  }

}
