/*
 * 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 com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.math3.analysis.function.Power;
import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math3.distribution.LogNormalDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;

import lombok.NonNull;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;

/**
 * Some general purpose mathematics functions using the {@link RiskscapeFunction} interface for use within
 * the riskscape engine.
 */
public class Maths {

  private static final int THREE = 3;

  public static class FloatingFunction implements RiskscapeFunction {

    private java.util.function.DoubleFunction<Double> internal;

    public FloatingFunction(java.util.function.DoubleFunction<Double> internal) {
      this.internal = internal;
    }
    @Override
    public Object call(List<Object> args) {
      double xValue = (Double) Types.FLOATING.coerce(args.get(0));
      return internal.apply(xValue);
    }
    @Override
    public List<Type> getArgumentTypes() {
      return Collections.singletonList(Types.FLOATING);
    }

    @Override
    public Type getReturnType() {
      return Types.FLOATING;
    }
  }

  /**
   * A function that will defer to a {@link FloatingFunction} sourced from a supplier function.
   *
   * This allows the parameters of the {@link FloatingFunction} to be varied.
   */
  private static class MathsFunction implements RiskscapeFunction {

    private final java.util.function.Function<List<Double>, RiskscapeFunction> internal;
    private final List<Type> types;

    /**
     *
     * @param argCount number of arguments this functions will receive
     * @param internal Function that will return a {@link FloatingFunction} for the required maths function
     */
    MathsFunction(int argCount, java.util.function.Function<List<Double>, RiskscapeFunction> internal) {
      this.internal = internal;
      this.types = new ArrayList<>(argCount);
      for (int i = 0; i < argCount; i++) {
        types.add(Types.FLOATING);
      }
    }

    /**
     * Will obtain a {@link FloatingFunction} by applying internal with args 1 onwards.
     * Then returns the result of calling {@link FloatingFunction} with args 0
     */
    @Override
    public Object call(List<Object> args) {
      List<Double> doubles = new ArrayList<>();
      for (int i = 1; i < args.size(); i++) {
        doubles.add((Double) Types.FLOATING.coerce(args.get(i)));
      }
      //TODO consider if we should bother caching actual maths function
      return internal.apply(doubles).call(Lists.newArrayList(args.get(0)));
    }
    @Override
    public List<Type> getArgumentTypes() {
      return types;
    }

    @Override
    public Type getReturnType() {
      return Types.FLOATING;
    }

  }

  /**
   * See {@link PolynomialFunction#value(double)}
   * @return an {@link RiskscapeFunction} wrapping a {@link PolynomialFunction}.
   */
  public static RiskscapeFunction newPolynomial(double[] coefficients) {
    PolynomialFunction internal = new PolynomialFunction(coefficients);
    return new FloatingFunction((x) -> internal.value(x));
  }

  /**
   * Returns a function to calculate {@link PolynomialFunction#value(double)} when passed arguments;
   * 1) x
   * 2) 1st degree
   * ...
   * n+1) n'th degree
   *
   * @param numberOfCoefficients function should expect
   * @return an {@link RiskscapeFunction} wrapping a {@link PolynomialFunction}.
   */
  public static RiskscapeFunction newPolynomial(int numberOfCoefficients) {
    return new MathsFunction(numberOfCoefficients + 1, (p) -> {
      double[] doubles = new double[numberOfCoefficients];
      for (int i = 0; i < numberOfCoefficients; i++) {
        doubles[i] = p.get(i);
      }
      return Maths.newPolynomial(doubles);
    });
  }

  /**
   * See {@link Power#value(double)}
   * @return an {@link RiskscapeFunction} wrapping a {@link Power}
   */
  public static RiskscapeFunction newPower(double degree) {
    Power internal = new Power(degree);
    return new FloatingFunction((x) -> internal.value(x));
  }

  /**
   * Returns a function to calculate {@link Power#value(double)} when passed arguments:
   * 1) x
   * 2) degree
   * @return an {@link RiskscapeFunction} wrapping a {@link Power}
   */
  public static RiskscapeFunction newPower() {
    return new MathsFunction(2, (p) -> Maths.newPower(p.get(0)));
  }

  /**
   * See {@link NormalDistribution#cumulativeProbability(double)}
   * @return an {@link RiskscapeFunction} wrapping a {@link NormalDistribution}
   */
  public static RiskscapeFunction newCumulativeNormalDistribution(double mean, double stdDev) {
    NormalDistribution distrib = new NormalDistribution(mean, stdDev);
    return new FloatingFunction((x) -> distrib.cumulativeProbability(x));
  }

  /**
   * Returns a function to calculate {@link NormalDistribution#cumulativeProbability(double)} when passed arguments:
   * 1) x
   * 2) mean
   * 3) stdDev
   * @return an {@link RiskscapeFunction} wrapping a {@link NormalDistribution}
   */
  public static RiskscapeFunction newCumulativeNormalDistribution() {
    return new MathsFunction(THREE, (p) -> Maths.newCumulativeNormalDistribution(p.get(0), p.get(1)));
  }

  /**
   * See {@link LogNormalDistribution#cumulativeProbability(double)}
   * @return an {@link RiskscapeFunction} wrapping a {@link LogNormalDistribution}
   */
  public static RiskscapeFunction newCumulativeLogNormalDistribution(double scale, double shape) {
    LogNormalDistribution distrib = new LogNormalDistribution(scale, shape);
    return new FloatingFunction((x) -> distrib.cumulativeProbability(x));
  }

  /**
   * Returns a function to calculate {@link LogNormalDistribution#cumulativeProbability(double)} when passed arguments:
   * 1) x
   * 2) scale
   * 3) shape
   * @return an {@link RiskscapeFunction} wrapping a {@link NormalDistribution}
   */
  public static RiskscapeFunction newCumulativeLogNormalDistribution() {
    return new MathsFunction(THREE, (p) -> Maths.newCumulativeLogNormalDistribution(p.get(0), p.get(1)));
  }

  /**
   * Returns a function that always returns the same value, regardless of the given parameter.
   * @param constantValue the value to always return.
   * @return a new {@link RiskscapeFunction}
   */
  public static RiskscapeFunction newConstant(@NonNull Object constantValue) {
    Type riskscapeType = Types.fromJavaType(constantValue.getClass());
    return new RiskscapeFunction() {


      @Override
      public Type getReturnType() {
        return riskscapeType;
      }

      @Override
      public List<Type> getArgumentTypes() {
        return Collections.singletonList(riskscapeType);
      }

      @Override
      public Object call(List<Object> args) {
        return constantValue;
      }
    };
  }

}
