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

import static nz.org.riskscape.engine.Matchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

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

import org.junit.Test;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.CompositeAggregationFunction.LocalProblems;
import nz.org.riskscape.engine.rl.RealizedExpression;
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.Types;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.Lambda;
import nz.org.riskscape.rl.ast.PropertyAccess;
import nz.org.riskscape.rl.ast.StructDeclaration;

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

  @Test
  public void canAggregateSimpleTypeManyWays() {
    // aggregating a simple type in this way is not the expected use. but this test is here to show
    // that it does work fine. but if we want to make this available to users we might want to alias
    // the name
    Struct inputType = norm(Struct.of("value", Types.INTEGER));
    realized = realizeAggregate(inputType,
        parse("aggregate_struct(value, {min: v -> min(v), max: v -> max(v), mode: v -> mode(v)})")).get();

    Struct resultType = Struct.of("min", Types.INTEGER, "max", Types.INTEGER, "mode", Types.INTEGER);
    assertThat(realized.getResultType(), is(resultType));

    tuples = tuples(inputType, "3", "4", "4", "7");
    assertThat(process(), is(Tuple.ofValues(resultType, 3L, 7L, 4L)));
  }

  @Test
  public void canAggregateTwoAttr() {
    Struct itemType = norm(Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER));
    Struct inputType = norm(Struct.of("value", itemType));
    realized = realizeAggregate(inputType,
        parse("aggregate_struct(value, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2)})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Types.FLOATING);
    assertThat(realized.getResultType(), is(resultType));

    tuples = tuples(itemType, "[4, 2]", "[2, 1]", "[8, 4]", "[10, 5]").stream()
        .map(t -> Tuple.ofValues(inputType, t))
        .collect(Collectors.toList());
    assertThat(process(), is(Tuple.ofValues(resultType, 6D, 3D)));
  }

  @Test
  public void canAggregateNullableItems() {

    // the struct is nullable, but the members are not - in this case we expect the result of aggregating the members
    // to be not nullable

    Struct itemType = Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER);
    Struct inputType = Struct.of("value", Nullable.of(itemType));

    realized = realizeAggregate(inputType,
        parse("aggregate_struct(value, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2)})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Types.FLOATING);
    assertThat(realized.getResultType(), is(resultType));

    tuples = new ArrayList<>();
    tuples.add(Tuple.ofValues(inputType, Tuple.ofValues(itemType, 4L, 3L)));
    tuples.add(null);
    tuples.add(Tuple.ofValues(inputType, Tuple.ofValues(itemType, 8L, 5L)));
    assertThat(process(), is(Tuple.ofValues(resultType, 6D, 4D)));
  }

  @Test
  public void canAggregateTwoAttrWhenOneIsNullable() {

    // the struct is not nullable, but one of the members are - in this case we expect result of aggregating the
    // nullable member to also be nullable.  An expression could if_null the value before aggregating it to
    // apply a default - this would remove the null-ness

    Struct itemType = norm(Struct.of("v1", Types.INTEGER, "v2", Nullable.INTEGER));
    Struct inputType = norm(Struct.of("value", itemType));
    realized = realizeAggregate(inputType,
        parse("aggregate_struct(value, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2)})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Nullable.FLOATING);
    assertThat(realized.getResultType(), is(resultType));

    tuples = tuples(itemType, "[4, 3]", "[2,]", "[8,]", "[10, 5]").stream()
        .map(t -> Tuple.ofValues(inputType, t))
        .collect(Collectors.toList());
    assertThat(process(), is(Tuple.ofValues(resultType, 6D, 4D)));
  }

  @Test
  public void canAggregateTwoAttrWhenOneIsNullableAndHasNoValues() {
    Struct itemType = norm(Struct.of("v1", Types.INTEGER, "v2", Nullable.INTEGER));
    Struct inputType = norm(Struct.of("value", itemType));
    realized = realizeAggregate(inputType,
        parse("aggregate_struct(value, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2)})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Nullable.FLOATING);
    assertThat(realized.getResultType(), is(resultType));

    tuples = tuples(itemType, "[4,]", "[2,]", "[8,]", "[10,]").stream()
        .map(t -> Tuple.ofValues(inputType, t))
        .collect(Collectors.toList());
    assertThat(process(), is(Tuple.ofValues(resultType, 6D)));
  }

  @Test
  public void willAggregateList() {
    Struct itemType = Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER);
    Struct inputType = Struct.of("values", RSList.create(itemType));

    RealizedExpression rExpr = realizationContext.getExpressionRealizer().realize(inputType,
        parse("aggregate_struct(values, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2)})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Types.FLOATING);
    assertThat(rExpr.getResultType(), is(Nullable.of(resultType)));

    tuples = tuples(itemType, "[4, 2]", "[2, 1]", "[8, 4]", "[10, 5]");

    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, tuples)), is(Tuple.ofValues(resultType, 6D, 3D)));
  }

  @Test
  public void willAggregateListWithANullableAttr() {
    Struct itemType = Struct.of("v1", Types.INTEGER, "v2", Nullable.INTEGER);
    Struct inputType = Struct.of("values", RSList.create(itemType));

    RealizedExpression rExpr = realizationContext.getExpressionRealizer().realize(inputType,
        parse("aggregate_struct(values, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2)})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Nullable.FLOATING);
    assertThat(rExpr.getResultType(), is(Nullable.of(resultType)));

    tuples = tuples(itemType, "[4, 3]", "[2,]", "[8,]", "[10, 5]");

    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, tuples)), is(Tuple.ofValues(resultType, 6D, 4D)));
  }

  @Test
  public void willAggregateListWithANullableItem() {
    Struct itemType = Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER);
    Struct inputType = Struct.of("values", RSList.create(Nullable.of(itemType)));

    RealizedExpression rExpr = realizationContext.getExpressionRealizer().realize(inputType,
        parse("aggregate_struct(values, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2)})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Types.FLOATING);
    assertThat(rExpr.getResultType(), is(Nullable.of(resultType)));

    tuples = new ArrayList<>();
    tuples.add(Tuple.ofValues(itemType, 1L, 4L));
    tuples.add(null);
    tuples.add(Tuple.ofValues(itemType, 2L, 5L));

    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, tuples)), is(Tuple.ofValues(resultType, 1.5D, 4.5D)));
  }

  @Test
  public void willAggregateListWithNoNullableItems() {
    Struct itemType = Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER);
    Struct inputType = Struct.of("values", RSList.create(Nullable.of(itemType)));

    RealizedExpression rExpr = realizationContext.getExpressionRealizer().realize(inputType,
        parse("aggregate_struct(values, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2)})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Types.FLOATING);
    assertThat(rExpr.getResultType(), is(Nullable.of(resultType)));

    tuples = new ArrayList<>();

    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, tuples)), nullValue());
  }

  @Test
  public void willAggregateListWithANullableAttrAndNoValues() {
    Struct itemType = Struct.of("v1", Types.INTEGER, "v2", Nullable.INTEGER);
    Struct inputType = Struct.of("values", RSList.create(itemType));

    RealizedExpression rExpr = realizationContext.getExpressionRealizer().realize(inputType,
        parse("aggregate_struct(values, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2)})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Nullable.FLOATING);
    assertThat(rExpr.getResultType(), is(Nullable.of(resultType)));

    tuples = tuples(itemType, "[4,]", "[2,]", "[8,]", "[10,]");

    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, tuples)), is(Tuple.ofValues(resultType, 6D)));
  }

  @Test
  public void willAggregateMappedList() {
    Struct itemType = Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER);
    Struct inputType = Struct.of("values", RSList.create(itemType));

    RealizedExpression rExpr = realizationContext.getExpressionRealizer().realize(inputType,
        parse("aggregate_struct(map(values, v -> {v1: v.v1 * 2, v2: v.v2 * 3}),"
            + " {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2)})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Types.FLOATING);
    assertThat(rExpr.getResultType(), is(Nullable.of(resultType)));

    tuples = tuples(itemType, "[4, 2]", "[2, 1]", "[8, 4]", "[10, 5]");

    assertThat(rExpr.evaluate(Tuple.ofValues(inputType, tuples)), is(Tuple.ofValues(resultType, 12D, 9D)));
  }

  @Test
  public void willAggregateEmptyListToNull() {
    Struct itemType = Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER);
    Struct inputType = Struct.of("values", RSList.create(itemType));

    RealizedExpression rExpr = realizationContext.getExpressionRealizer().realize(inputType,
        parse("aggregate_struct(values, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2)})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Types.FLOATING);
    assertThat(rExpr.getResultType(), is(Nullable.of(resultType)));

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

  @Test
  public void childAggregationUnknownAttr() {
    Struct itemType = norm(Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER));
    Struct inputType = norm(Struct.of("value", itemType));
    assertThat(realizeAggregate(inputType,
        parse("aggregate_struct(value, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2), v3: v -> v.v3})")),
        failedResult(hasAncestorProblem(
            is(ExpressionProblems.get().propertyOutsideOfAggregationFunction(PropertyAccess.of("v", "v3")))
        ))
    );
  }

  @Test
  public void errorWhenAggregationNotInStructDeclaration() {
    Struct itemType = norm(Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER, "v3", Types.TEXT));
    Struct inputType = norm(Struct.of("value", itemType));
    assertThat(realizeAggregate(inputType,
        parse("aggregate_struct(value, v -> mean(v.v1))")),
        failedResult(hasAncestorProblem(
            is(ExpressionProblems.get().mismatch(parse("v -> mean(v.v1)"), StructDeclaration.class,
                "{mean: v -> mean(v.attr)}"))
        ))
    );
  }

  @Test
  public void errorWhenAggregationNotInLambda() {
    Struct itemType = norm(Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER, "v3", Types.TEXT));
    Struct inputType = norm(Struct.of("value", itemType));
    assertThat(realizeAggregate(inputType,
        parse("aggregate_struct(value, {v1: mean(v.v1)})")),
        failedResult(hasAncestorProblem(
            is(ExpressionProblems.get().mismatch(parse("mean(v.v1)"), Lambda.class, "v -> mean(v.attr)"))
        ))
    );
  }

  @Test
  public void errorWhenArgsMissing() {
    Struct itemType = norm(Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER, "v3", Types.TEXT));
    Struct inputType = norm(Struct.of("value", itemType));
    assertThat(realizeAggregate(inputType,
        parse("aggregate_struct(value)")),
        failedResult(hasAncestorProblem(
            is(ArgsProblems.get().wrongNumber(2, 1))
        ))
    );
  }

  @Test
  public void errorWhenExtraArg() {
    Struct itemType = norm(Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER, "v3", Types.TEXT));
    Struct inputType = norm(Struct.of("value", itemType));
    assertThat(realizeAggregate(inputType,
        parse("aggregate_struct(value, {v1: (v, x) -> mean(v.v1)}, 'extra')")),
        failedResult(hasAncestorProblem(
            is(ArgsProblems.get().wrongNumber(2, 3))
        ))
    );
  }

  @Test
  public void errorWhenLambdaHasExtraArgs() {
    Struct itemType = norm(Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER, "v3", Types.TEXT));
    Struct inputType = norm(Struct.of("value", itemType));
    assertThat(realizeAggregate(inputType,
        parse("aggregate_struct(value, {v1: (v, x) -> mean(v.v1)})")),
        failedResult(hasAncestorProblem(
            is(ExpressionProblems.get().lambdaArityError(parse("(v, x) -> mean(v.v1)"), 2, 1))
        ))
    );
  }

  @Test
  public void errorWhenLambdaArgsDiffer() {
    Struct itemType = norm(Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER, "v3", Types.TEXT));
    Struct inputType = norm(Struct.of("value", itemType));
    assertThat(realizeAggregate(inputType,
        parse("aggregate_struct(value, {v1: v -> mean(v.v1), v2_mean: x -> mean(x.v2)})")),
        failedResult(hasAncestorProblem(
            is(LocalProblems.get().lambdaArgsDiffer("x", "v"))
        ))
    );
  }

  @Test
  public void aggregationIncludesStaticExpression() {
    Struct itemType = norm(Struct.of("v1", Types.INTEGER, "v2", Types.INTEGER));
    Struct inputType = norm(Struct.of("value", itemType));
    realized = realizeAggregate(inputType,
        parse("aggregate_struct(value, {v1_mean: v -> mean(v.v1), v2_mean: v -> mean(v.v2), sum: v -> 3 + 4})")).get();

    Struct resultType = Struct.of("v1_mean", Types.FLOATING, "v2_mean", Types.FLOATING, "sum", Types.INTEGER);
    assertThat(realized.getResultType(), is(resultType));

    tuples = tuples(itemType, "[4, 2]", "[2, 1]", "[8, 4]", "[10, 5]").stream()
        .map(t -> Tuple.ofValues(inputType, t))
        .collect(Collectors.toList());
    assertThat(process(), is(Tuple.ofValues(resultType, 6D, 3D, 7L)));
  }

}
