/*
 * 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.Collections;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.ExpressionAggregationFunction;
import nz.org.riskscape.engine.rl.DefaultOperators;
import nz.org.riskscape.engine.rl.LanguageFunctions;
import nz.org.riskscape.engine.rl.LogicFunctions;
import nz.org.riskscape.engine.types.Nullable;
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.Problems;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

@SuppressWarnings("unchecked")
public class ExpressionAggregationFunctionTest extends ProjectTest {

  private RealizedAggregateExpression realized;
  private List<Tuple> tuples = Arrays.asList();
  ExpressionAggregationFunction function;

  @Before
  public void setup() {
    project.getFunctionSet().insertFirst(DefaultOperators.INSTANCE);
    project.getFunctionSet().addAll(LanguageFunctions.FUNCTIONS);
    project.getFunctionSet().addAll(LogicFunctions.LOGIC_FUNCTIONS);
  }

  @Test
  public void aSumExampleUsesOnlyReduce() throws Exception {
     function = ExpressionAggregationFunction.builder()
    .reduce("(l, r) -> l + r")
    .build();

    Struct inputType = norm(Types.INTEGER.asStruct());
    realized =
        function.realize(realizationContext, inputType,
            functionCall("foo(value)")).get();

    assertEquals(Types.INTEGER, realized.getResultType());

    // no tuples means null result
    assertNull(this.process());

    // should compute sum correctly
    tuples = tuples(inputType, "[1]", "[2]", "[3]");
    assertEquals(6L, process());

    // nulls values should still compute a result
    inputType = norm(Struct.of("value", Nullable.INTEGER));

    realized =
        function.realize(realizationContext, inputType,
            functionCall("foo(value)")).get();

    tuples = tuples(inputType, "[1]", "[2]", "[null_of('integer')]", "[3]");

    assertEquals(6L, process());
    // but the return type is nullable
    assertEquals(Nullable.INTEGER, realized.getResultType());

    // works with floating point as well
    inputType = norm(Types.FLOATING.asStruct());
    realized =
        function.realize(realizationContext, inputType,
            functionCall("foo(value)")).get();
    tuples = tuples(inputType, "[1.0]", "[2.0]", "[null_of('floating')]", "[3.0]");

    assertEquals(6D, process());
  }

  @Test
  public void aSumExampleCanHaveIdentity() throws Exception {
    function = ExpressionAggregationFunction.builder()
      .reduce("(l, r) -> l + r")
      .identity("0")
      .build();

    Struct inputType = norm(Types.INTEGER.asStruct());

    realized =
        function.realize(realizationContext, inputType, functionCall("foo(value)")).get();

    assertEquals(Types.INTEGER, realized.getResultType());

    // no tuples means identity result
    assertEquals(0L, this.process());

    // should compute sum correctly
    tuples = tuples(inputType, "[1]", "[2]", "[3]");
    assertEquals(6L, process());

    // nulls values should still compute a result
    inputType = norm(Nullable.INTEGER.asStruct());

    realized =
        function.realize(realizationContext, inputType,
            functionCall("foo(value)")).get();

    tuples = tuples(inputType, "[1]", "[2]", "[null_of('integer')]", "[3]");

    assertEquals(6L, process());

    tuples = tuples(inputType, "[null_of('integer')]", "[null_of('integer')]");
    assertEquals(0L, process());

    //   works with floating point as well - identity value is coerced
    inputType = norm(Types.FLOATING.asStruct());
    realized =
        function.realize(realizationContext, inputType,
            functionCall("foo(value)")).get();
    tuples = Collections.emptyList();

    assertEquals(0D, process());
  }


  @Test
  public void aMeanExampleWithAProcessor() throws Exception {
    function = ExpressionAggregationFunction.builder()
        .map("v -> {count: 1, total: v}")
        .reduce("(l, r) -> {count: l.count + r.count, total: l.total + r.total}")
        .process("v -> v.total / v.count")
        .build();
    Struct inputType = norm(Types.INTEGER.asStruct());

    realized =
        function.realize(realizationContext, inputType, functionCall("foo(value)")).get();

    assertEquals(Types.FLOATING, realized.getResultType());

    // no tuples means null. no identity
    assertNull(this.process());

    tuples = tuples(inputType, "[1]", "[2]", "[3]");
    assertEquals(2D, process());

    inputType = norm(Types.INTEGER.asStruct());
    realized =
        function.realize(realizationContext, inputType, functionCall("foo(value)")).get();
    tuples = tuples(inputType, "[1]", "[2]", "[null_of('integer')]", "[3]");

    // nulls don't break it
    assertEquals(2D, this.process());

    // all null, all the time
    tuples = tuples(inputType, "[null_of('integer')]", "[null_of('integer')]");
    assertNull(process());
  }

  @Test
  public void aMeanExampleWithIdentity() throws Exception {
    function = ExpressionAggregationFunction.builder()
        .map("v -> {count: 1, total: v}")
        .reduce("(l, r) -> {count: l.count + r.count, total: l.total + r.total}")
        .process("v -> v.total / v.count")
        .identity("1")
        .build();

    Struct inputType = norm(Types.INTEGER.asStruct());

    realized =
        function.realize(realizationContext, inputType, functionCall("foo(value)")).get();

    assertEquals(Types.FLOATING, realized.getResultType());

    // no tuples means identity result
    assertEquals(1D, this.process());

    tuples = tuples(inputType, "[1]", "[2]", "[3]");
    assertEquals(2D, process());

    inputType = norm(Nullable.INTEGER.asStruct());
    realized =
        function.realize(realizationContext, inputType, functionCall("foo(value)")).get();
    tuples = tuples(inputType, "[1]", "[2]", "[null_of('integer')]", "[3]");

    // nulls don't break it
    assertEquals(2D, this.process());
    assertEquals(Types.FLOATING, realized.getResultType());

    // all null, all the time
    tuples = tuples(inputType, "[null_of('integer')]", "[null_of('integer')]");
    assertEquals(1D, process());
  }

  @Test
  public void errorIfIdentityValueCanNotBeCoercedToMapType() throws Exception {
    function = ExpressionAggregationFunction.builder()
        .map("v -> {count: 1, total: v}")
        .reduce("(l, r) -> {count: l.count + r.count, total: l.total + r.total}")
        .process("v -> v.total / v.count")
        .identity("'foo'")
        .build();

    Struct inputType = norm(Types.INTEGER.asStruct());

    assertThat(
      function.realize(realizationContext, inputType, functionCall("foo(value)")),
      failedResult(
            hasAncestorProblem(is(TypeProblems.get().couldNotCoerce(Types.TEXT, Types.FLOATING))
        )
      )
    );
  }

  @Test
  public void willNotRealizeIfValueExpressionDoesNotRealize() {
    Struct inputType;

    function = ExpressionAggregationFunction.builder()
        .reduce("(l, r) -> l + r")
        .build();

    inputType = norm(Types.DATE.asStruct());

    assertThat(
      function.realize(realizationContext, inputType, functionCall("foo(values)")),
      failedResult(
         equalIgnoringChildren(Problems.foundWith(functionCall("foo(values)").getArguments().get(0)))
      )
    );


  }

  @Test
  public void willNotRealizeIfExpressionsDoNotRealize() {
    Struct inputType;

    function = ExpressionAggregationFunction.builder()
        .reduce("(l, r) -> l + r")
        .build();

    inputType = norm(Types.DATE.asStruct());

    assertThat(
      function.realize(realizationContext, inputType, functionCall("foo(value)")),
      failedResult(
        equalTo(
          ExpressionAggregationFunction.LocalProblems.get().typeNotSupportedForThisFunction(Types.DATE)
          .withChildren(
            ExpressionAggregationFunction.LocalProblems.get()
            .couldNotRealizeExpression("reduce", parse("(l, r) -> l + r"))
            .withChildren(
              ExpressionProblems.get().noSuchOperatorFunction("+", Arrays.asList(Types.DATE, Types.DATE))
            )
          )
        )
      )
    );

    function = ExpressionAggregationFunction.builder()
        .map("v -> v * 2")
        .reduce("(l, r) -> l")
        .build();

    assertThat(
      function.realize(realizationContext, inputType, functionCall("foo(value)")),
      failedResult(
        equalTo(
          ExpressionAggregationFunction.LocalProblems.get().typeNotSupportedForThisFunction(Types.DATE)
          .withChildren(
            ExpressionAggregationFunction.LocalProblems.get().couldNotRealizeExpression("map", parse("v -> v * 2"))
            .withChildren(
              ExpressionProblems.get().noSuchOperatorFunction("*", Arrays.asList(Types.DATE, Types.INTEGER))
            )
          )
        )
      )
    );


    function = ExpressionAggregationFunction.builder()
        .reduce("(l, r) -> l")
        .process("l -> l / 2.0")
        .build();

    assertThat(
      function.realize(realizationContext, inputType, functionCall("foo(value)")),
      failedResult(
        equalTo(
          ExpressionAggregationFunction.LocalProblems.get().typeNotSupportedForThisFunction(Types.DATE)
          .withChildren(
            ExpressionAggregationFunction.LocalProblems.get()
            .couldNotRealizeExpression("process", parse("l -> l / 2.0"))
            .withChildren(
              ExpressionProblems.get().noSuchOperatorFunction("/", Arrays.asList(Types.DATE, Types.FLOATING))
            )
          )
        )
      )
    );
  }

  private Object process() {
    boolean hasIdentity = function.hasIdentity();
    Accumulator acc = realized.newAccumulator();
    assertNotEquals(hasIdentity, acc.isEmpty());
    for (Tuple tuple : tuples) {
      acc.accumulate(tuple);
      assertFalse(acc.isEmpty());
    }
    Object serialResult = acc.process();

    Accumulator odd = realized.newAccumulator();
    assertNotEquals(hasIdentity, odd.isEmpty());
    Accumulator even = realized.newAccumulator();
    assertNotEquals(hasIdentity, even.isEmpty());
    int i = 0;
    for (Tuple tuple : tuples) {
      (i++ % 2 == 0 ? even : odd).accumulate(tuple);
    }

    Accumulator combined = odd.combine(even);
    assertEquals(i != 0 || hasIdentity, !acc.isEmpty());
    Object parallelResult = combined.process();

    assertEquals("parallel / serial mismatch", parallelResult, serialResult);

    return serialResult;
  }

  private Expression parse(String expr) {
    return expressionParser.parse(expr);
  }

  private FunctionCall functionCall(String fcExpr) {
    return parse(fcExpr).isA(FunctionCall.class).get();
  }

}
