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

import java.util.Collections;
import java.util.List;

import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.BaseRealizableFunction;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.function.UntypedFunction;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.types.FunctionType;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

/**
 * Function for estimating the area under a curve using the https://en.wikipedia.org/wiki/Trapezoidal_rule.  Accepts
 * a function as its first argument, then an interval defined by two points, `a` and `b`, and a number of intervals
 */
public class TrapezoidIntegrationFunction extends BaseRealizableFunction {

  interface LocalProblems extends ProblemFactory {
    Problem functionBadArgumentTypes(List<Type> actual);
    Problem functionBadReturnType(Type actual);
  }

  static final LocalProblems PROBLEMS = Problems.get(LocalProblems.class);

  public TrapezoidIntegrationFunction() {
    super(
      ArgumentList.create(
        "function", FunctionType.WILD,
        "a", Types.FLOATING,
        "b", Types.FLOATING,
        "intervals", Types.INTEGER
      ),
      Types.FLOATING
    );
  }

  @Override
  public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context, FunctionCall functionCall,
      List<Type> argumentTypes) {

    return ProblemException.catching(() -> {
      FunctionType functionType =
          Types.findOrThrow(arguments.get("function"), FunctionType.WILD, argumentTypes.get(0));

      if (functionType.getArgumentTypes().size() != 1
          || functionType.getArgumentTypes().get(0) != Types.FLOATING) {
        throw new ProblemException(PROBLEMS.functionBadArgumentTypes(functionType.getArgumentTypes()));
      }
      if (! functionType.getReturnType().isNumeric()) {
        throw new ProblemException(PROBLEMS.functionBadReturnType(functionType.getReturnType()));
      }

      Types.findOrThrow(arguments.get("a"), Types.FLOATING, argumentTypes.get(1));
      Types.findOrThrow(arguments.get("b"), Types.FLOATING, argumentTypes.get(2));
      Types.findOrThrow(arguments.get("intervals"), Types.INTEGER, argumentTypes.get(3));


      return RiskscapeFunction.create(this, argumentTypes, Types.FLOATING, args -> {
        UntypedFunction integrating = (UntypedFunction) args.get(0);
        double a = ((Number) args.get(1)).doubleValue();
        double b = ((Number) args.get(2)).doubleValue();
        // how many samples of the function we take
        double intervals = ((Number) args.get(3)).doubleValue();

        // distance between x values - deltaXK
        double spacing = Math.abs(b - a) / intervals;


        double sum = 0;
        // we remember the last x and y to avoid having to recompute things as we move across the intervals
        // we start at the lowest of a and b then add spacing on each iteration to move closer to the higher value.
        double lastX = Math.min(a, b);
        Double lastY = null;
        for (int i = 0; i < intervals; i++) {
          double x1 = lastX;
          double x2 = lastX + spacing;

          double y1;
          if (lastY == null) {
            y1 = ((Number) integrating.call(Collections.singletonList(x1))).doubleValue();
          } else {
            y1 = lastY;
          }
          double y2 = ((Number) integrating.call(Collections.singletonList(x2))).doubleValue();

          sum += (y1 + y2) / 2;

          lastX = x2;
          lastY  = y2;
        }

        return sum * spacing;
      });
    });

  }

}
