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

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

import lombok.Getter;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.BinaryFunction;
import nz.org.riskscape.engine.function.ConstantFunction;
import nz.org.riskscape.engine.function.ExpressionAggregationFunction;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.function.IdentifiedFunction.Category;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.function.UnaryFunction;
import nz.org.riskscape.engine.function.agg.AggregationFunctionAdapter;
import nz.org.riskscape.engine.function.maths.Abs;
import nz.org.riskscape.engine.function.maths.Log;
import nz.org.riskscape.engine.function.maths.Log10;
import nz.org.riskscape.engine.function.maths.LogNormalCurveFunction;
import nz.org.riskscape.engine.function.maths.Max;
import nz.org.riskscape.engine.function.maths.Min;
import nz.org.riskscape.engine.function.maths.NormalCurveFunction;
import nz.org.riskscape.engine.function.maths.Polynomial;
import nz.org.riskscape.engine.function.maths.Pow;
import nz.org.riskscape.engine.function.maths.RandomChoice;
import nz.org.riskscape.engine.function.maths.RandomNorm;
import nz.org.riskscape.engine.function.maths.RandomUniform;
import nz.org.riskscape.engine.function.maths.Round;
import nz.org.riskscape.engine.function.maths.Scale;
import nz.org.riskscape.engine.rl.agg.AggregationFunction;
import nz.org.riskscape.engine.rl.agg.MedianAggregationFunction;
import nz.org.riskscape.engine.rl.agg.ModeAggregationFunction;
import nz.org.riskscape.engine.rl.agg.PercentileAggregationFunction;
import nz.org.riskscape.engine.rl.agg.StandardDeviationAggregationFunction;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;

/**
 * A set of useful maths functions for use with risk modelling
 *
 */
public class MathsFunctions {

  public static final List<IdentifiedFunction> FUNCTIONS = Arrays.asList(
      // exponenty stuff
      new Pow(),
      new Log(),
      new Log10(),

      new UnaryFunction<Double>(Types.FLOATING, Types.FLOATING, d -> Math.exp(d)).builtin(
          "exp",
          Category.MATHS),

      new UnaryFunction<Double>(Types.FLOATING, Types.FLOATING, d -> Math.sqrt(d)).identified(
          "square_root",
          "Get the square root of the given number",
          RiskscapeFunction.BUILT_IN,
          Category.MATHS),

      // integer/float manipulation
      new Abs(),
      new Min(),
      new Max(),
      new Round().builtin("round", Category.MATHS),

      new UnaryFunction<Double>(Types.FLOATING, Types.INTEGER, d -> (long) Math.ceil(d)).identified(
          "ceil",
          "Round number up to the closest integer",
          RiskscapeFunction.BUILT_IN,
          Category.MATHS),

      new UnaryFunction<Double>(Types.FLOATING, Types.INTEGER, d -> (long) Math.floor(d)).identified(
          "floor",
          "Round number down to the closest integer",
          RiskscapeFunction.BUILT_IN,
          Category.MATHS),

      new UnaryFunction<Object>(Types.ANYTHING, Types.FLOATING, a -> Types.FLOATING.coerce(a)).identified(
          "float",
          "Convert input to a 64 bit floating point number",
          RiskscapeFunction.BUILT_IN,
          Category.MATHS),

      new UnaryFunction<Object>(Types.ANYTHING, Types.SMALLFLOAT, a -> Types.SMALLFLOAT.coerce(a)).identified(
          "smallfloat",
          "Convert input to a small (32 bit) floating point number",
          RiskscapeFunction.BUILT_IN,
          Category.MATHS),

      new UnaryFunction<Object>(
          Types.ANYTHING,
          Types.INTEGER,
          a -> Math.round((double)Types.FLOATING.coerce(a))   //coerce to float then round, to get correct rounding
      ).identified(
          "int",
          "Convert input to a integer number",
          RiskscapeFunction.BUILT_IN,
          Category.MATHS),

      ConstantFunction.returning(Long.MAX_VALUE).builtin("maxint", Category.MATHS),
      ConstantFunction.returning(Long.MIN_VALUE).builtin("minint", Category.MATHS),
      ConstantFunction.returning(Double.MAX_VALUE).builtin("maxfloat", Category.MATHS),
      // fun fact - Double.MIN_VALUE is smallest positive number, whereas Long.MIN_VALUE is biggest negative value
      ConstantFunction.returning(-Double.MAX_VALUE).builtin("minfloat", Category.MATHS),
      ConstantFunction.returning(Float.MAX_VALUE).builtin("maxsmallfloat", Category.MATHS),
      ConstantFunction.returning(Float.MIN_VALUE).builtin("minsmallfloat", Category.MATHS),
      ConstantFunction.returning(Double.POSITIVE_INFINITY).builtin("inf", Category.MATHS),
      ConstantFunction.returning(Double.NEGATIVE_INFINITY).builtin("negative_inf", Category.MATHS),

      // stats
      new NormalCurveFunction("norm_cdf",
          (d, x) -> d.cumulativeProbability(x)),

      new NormalCurveFunction("norm_pdf",
          (d, x) -> d.density(x)),

      new NormalCurveFunction("norm_ppf",
          (d, x) -> d.inverseCumulativeProbability(x)),

      new LogNormalCurveFunction("lognorm_cdf",
          (d, x) -> d.cumulativeProbability(x)),

      new LogNormalCurveFunction("lognorm_pdf",
          (d, x) -> d.density(x)),

      new LogNormalCurveFunction("lognorm_ppf",
          (d, x) -> d.inverseCumulativeProbability(x)),

      new Polynomial(),

      new RandomUniform().builtin("random_uniform", Category.MATHS),

      new RandomNorm().builtin("random_norm", Category.MATHS),

      new BinaryFunction<Double, Double>(
          new FunctionArgument("dividend", Types.FLOATING),
          new FunctionArgument("divisor", Types.FLOATING),
          Types.FLOATING,
          (dividend, divisor) -> dividend % divisor
      ).builtin("modulo", Category.MATHS),

      new RandomChoice().builtin("random_choice", Category.MATHS),
      new Scale(),

      AggregationFunction.asFunction(ExpressionAggregationFunction.builder()
          .map("value -> {count: 1, value: value}")
          .reduce("(l, r) -> {count: l.count + r.count, value: l.value + r.value}")
          .process("last -> last.value / last.count")
          .build()
      ).builtin("mean", IdentifiedFunction.Category.MATHS),

      AggregationFunction.asFunction(ExpressionAggregationFunction.builder()
          .identity("0")
          // count non-null values. but if the value is boolean, only true is counted
          .map("v -> if_then_else(is_null(v) or v = false, 0, 1)")
          .reduce("(l, r) -> l + r")
          .build()
      ).builtin("count", IdentifiedFunction.Category.MATHS),

      AggregationFunction.asFunction(ExpressionAggregationFunction.builder()
          .reduce("(l, r) -> l + r")
          .build()
      ).builtin("sum", Category.MATHS),

      AggregationFunction.asFunction(new MedianAggregationFunction()
      ).builtin("median", IdentifiedFunction.Category.MATHS),

      AggregationFunction.asFunction(new ModeAggregationFunction()
      ).builtin("mode", IdentifiedFunction.Category.MATHS),

      new AggregationFunctionAdapter(new PercentileAggregationFunction()) {
        @Getter
        private final ArgumentList arguments = ArgumentList.create(
            "items", RSList.LIST_ANYTHING,
            "percentiles", RSList.create(Types.INTEGER)
        );

        @Override
        public List<Type> getArgumentTypes() {
          return getArguments().getArgumentTypes();
        }

      }.builtin("percentiles", IdentifiedFunction.Category.MATHS),

      new AggregationFunctionAdapter(new PercentileAggregationFunction.Single()) {
        @Getter
        private final ArgumentList arguments = ArgumentList.create(
            "items", RSList.LIST_ANYTHING,
            "percentile", Types.INTEGER
        );

        @Override
        public List<Type> getArgumentTypes() {
          return getArguments().getArgumentTypes();
        }

      }.builtin("percentile", IdentifiedFunction.Category.MATHS),

      AggregationFunction.asFunction(new StandardDeviationAggregationFunction()
      ).builtin("stddev", IdentifiedFunction.Category.MATHS)

  );

}
