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

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.rl.agg.Accumulator;
import nz.org.riskscape.engine.rl.agg.AggregationFunction;
import nz.org.riskscape.engine.rl.agg.RealizedAggregateExpression;
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.problem.ProblemException;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ExpressionParser;
import nz.org.riskscape.rl.ast.FunctionCall;

/**
 * Used for 'stacking' continuous functions on top of each other so that an accumulated numeric consequence can be
 * computed in one call.  See {@link CreateContinuousFunction} for more details.
 */
public class StackContinuousFunction implements AggregationFunction {

  private static final class AccumulatorImpl implements Accumulator {

    private final StackableContinuousState accumulator;
    private final StackableContinuousFunctionType functionType;
    private final RealizedExpression functionExpression;
    private final RealizedExpression combineValuesExpression;
    private boolean empty = true;
    private final Tuple combineValuesInput;

    AccumulatorImpl(
        StackableContinuousFunctionType<?> functionType,
        RealizedExpression functionExpression,
        RealizedExpression combineYValuesExpression
    ) {
      this.functionType = functionType;
      this.functionExpression = functionExpression;
      this.combineValuesExpression = combineYValuesExpression;
      accumulator = functionType.newAccumulator();

      this.combineValuesInput = new Tuple((Struct) combineYValuesExpression.getInputType());
    }

    @Override
    @SuppressWarnings("unchecked")
    public Accumulator combine(Accumulator rhs) {
      AccumulatorImpl impl = (AccumulatorImpl) rhs;

      if (this.empty) {
        return impl;
      }

      if (!impl.empty) {
        StackableContinuousState state = impl.accumulator;
        final int len = functionType.getSize();

        for (int i = 0; i < len; i++) {
          // set up tuple for reduction expression
          combineValuesInput.set(0, functionType.getValue(accumulator, i));
          combineValuesInput.set(1, functionType.getValue(state, i));

          // update accumulator with result
          functionType.setValue(accumulator, i, combineValuesExpression.evaluate(combineValuesInput));
        }
      }

      return this;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void accumulate(Object input) {
      StackableContinuousState state = (StackableContinuousState) functionExpression.evaluate(input);
      functionType.populate(state);

      if (empty) {
        empty = false;
        functionType.copyValues(state, accumulator);

      } else {
        // this looks like it can be DRYd up / simplified with combine
        final int len = functionType.getSize();
        for (int i = 0; i < len; i++) {
          // set up tuple for reduction expression
          combineValuesInput.set(0, functionType.getValue(accumulator, i));
          combineValuesInput.set(1, functionType.getValue(state, i));

          // update accumulator with result
          functionType.setValue(accumulator, i, combineValuesExpression.evaluate(combineValuesInput));
        }
      }
    }

    @Override
    public Object process() {
      return accumulator;
    }

    @Override
    public boolean isEmpty() {
      return empty;
    }

  }

  @Override
  public ResultOrProblems<RealizedAggregateExpression> realize(RealizationContext context, Type inputType,
      FunctionCall fc) {

    return ProblemException.catching(() -> {
      // Check there aren't to many arguments.
      // Check there aren't to many arguments.
      if (fc.getPositionalArguments().size() != 1) {
        throw new ProblemException(ArgsProblems.get().wrongNumber(1, fc.getPositionalArguments().size()));
      }

      RealizedExpression functionExpression =
          context.getExpressionRealizer().realize(inputType, fc.getArguments().get(0).getExpression()).getOrThrow();

      // TODO would be better to get rid of the specific types and instead use some composition to handle this - some
      // kind of interpolation helper?
      ContinuousFunctionType type =
          Types.findOrThrow("value", ContinuousFunctionType.ANY, functionExpression.getResultType());

      if (type instanceof StackableContinuousFunctionType<?> stackableFunctionType) {
        // otherwise we get struct member exceptions when combining - this papers over any "badly behaving"
        // functions that might not be normalizing their return type
        type.getValueType().findAllowNull(Struct.class).ifPresent(struct -> context.normalizeStruct(struct));

        Struct combineValuesInput = context.normalizeStruct(
          Struct.of("a", type.getValueType(), "b", type.getValueType())
        );

        RealizedExpression combineYValuesExpression = context.getExpressionRealizer().realize(
            combineValuesInput,
            ExpressionParser.parseString("a + b")
        ).getOrThrow();

        return RealizedAggregateExpression.create(inputType, functionExpression.getResultType(),
            fc, () -> new AccumulatorImpl(stackableFunctionType, functionExpression, combineYValuesExpression));
      } else {
        // continuous function types must override some methods to support stacking.
        // so we have an explicit check for the implemenations that support this (and they should have a
        // test to prove it)
        throw new ProblemException(TypeProblems.get().requiresOneOf(
            "value",
            Lists.newArrayList(LinearContinuousFunctionType.ANY, BilinearContinuousFunctionType.ANY_BILINEAR),
            type
        ));
      }
    });


  }

}
