/*
 * 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 org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;

import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.Tuple;
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.rl.MathsFunctions;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.FunctionCall;

public abstract class BaseAggregationFunctionTest extends ProjectTest {

  public static final double TOLERANCE = 0.0000000001D;

  protected RealizedAggregateExpression realized;
  protected List<Tuple> tuples = Arrays.asList();
  protected AggregationFunction function;

  /**
   * When true {@link #process() } will assert that serialResult and parallelResult are equal.
   * But this may get tricky for result types with equals() that can't easily return true when the
   * results are equal but not the same (objects).
   *
   * Tests that set this to false should take other steps to ensure that serialResult and parallelResult
   * are consistent.
   */
  protected boolean assertSerialAndParallelEqual = true;
  protected Object serialResult;
  protected Object parallelResult;
  protected List<Problem> realizationProblems;

  public BaseAggregationFunctionTest() {
    project.getFunctionSet().insertFirst(DefaultOperators.INSTANCE);
    project.getFunctionSet().addAll(MathsFunctions.FUNCTIONS);
    project.getFunctionSet().addAll(LanguageFunctions.FUNCTIONS);
    project.getFunctionSet().addAll(LogicFunctions.LOGIC_FUNCTIONS);
  }

  protected ResultOrProblems<RealizedAggregateExpression> realizeAggregate(Type inputType, Expression expr) {
    ResultOrProblems<RealizedAggregateExpression> realizedOr =
        realizationContext.getExpressionRealizer().realizeAggregate(inputType, expr);

    realizationProblems = realizedOr.getProblems();
    realized = realizedOr.orElse(null);

    return realizedOr;
  }

  /**
   * Processes the tuples with the {@link AggregationFunction}.
   *
   * This process passes all of the tuples to:
   * - serial accumulation
   * - odd/even accumulations that are then combined.
   *
   * The result from both sets of accumulations is compared and must be equal.
   *
   * @return accumulated result
   */
  protected Object process() {
    if (realized == null) {
      fail("Expression did not realize - " + render(realizationProblems));
    }
    Accumulator acc = realized.newAccumulator();
    for (Tuple tuple : tuples) {
      acc.accumulate(tuple);
    }
    serialResult = acc.process();

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

    Accumulator combined = odd.combine(even);
    parallelResult = combined.process();

    if (assertSerialAndParallelEqual) {
      assertEquals("parallel / serial mismatch", parallelResult, serialResult);
    }

    return serialResult;
  }

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

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

}
