/*
 * 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 java.util.Collection;
import java.util.List;

import com.google.common.primitives.Doubles;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.rl.RealizableFunction;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.rl.ScopedLambdaExpression;
import nz.org.riskscape.engine.types.LambdaType;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.ScopedLambdaType;
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.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.Expression;
import nz.org.riskscape.rl.ast.FunctionCall;
import nz.org.riskscape.rl.ast.FunctionCall.Argument;
import nz.org.riskscape.rl.ast.Lambda;

/**
 * Builds a continuous function from a lambda expression and a series of x values to allow a complex function to be
 * estimated and then stacked on top of other functions to avoid the overhead in calling it gajjilions of times.
 *
 * This can be a useful optimisation in probabilistic modelling where hundreds of thousands of consequences needed to be
 * computed for each exposure.  We can coalesce nearby exposures to a particular site where a
 * hazard occurs, create a continuous function for each exposure with likely (numeric) hazard intensity values,
 * stack the functions at each site, then call the function once at each site to compute a consequence for the entire
 * site.  In the case of a non-trivial loss function and hundreds of thousands of exposures, this can reduce computation
 * time down dramatically.
 */
public class CreateContinuousFunction implements RealizableFunction {

  interface LocalProblems extends ProblemFactory {
    Problem couldNotCreateContinuousFunctionFromYValue(Expression lambdaExpression, Type yValueType);
  }

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

  private final ArgumentList arguments = ArgumentList.create(
    "x-values", RSList.create(Types.ANYTHING),
    "apply-to", new LambdaType("x-value"),
    "apply-log-to-x", Types.BOOLEAN
  );

  @RequiredArgsConstructor
  // TODO this is now the same as CreateBilinearContinuousFunction
  private class FunctionImpl implements RiskscapeFunction {

    @Getter
    private final List<Type> argumentTypes;

    @Getter
    private final LinearContinuousFunctionType returnType;

    @Override
    public Object call(List<Object> args) {
      ScopedLambdaExpression lambda = (ScopedLambdaExpression) args.get(1);

      return returnType.newFunction(lambda);
    }

  }
  @Override
  public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context, FunctionCall functionCall,
      List<Type> argumentTypes) {
    return ProblemException.catching(() -> {
      // Check there aren't to many arguments.
      if (argumentTypes.size() > arguments.size()) {
        throw new ProblemException(ArgsProblems.get().wrongNumber(arguments.size(), argumentTypes.size()));
      }
      if (argumentTypes.size() < 2) {
        // we require at least two arguments. if there are not at least two then we fail with expected: 2
        throw new ProblemException(ArgsProblems.get().wrongNumber(2, argumentTypes.size()));
      }

      RSList listType = Types.findOrThrow("x-values", RSList.create(Types.ANYTHING), argumentTypes.get(0));
      Argument xValuesArg = arguments.getRequiredArgument(functionCall, "x-values").getOrThrow();
      List<?> xValues = xValuesArg.evaluateConstant(context, List.class, RSList.create(Types.ANYTHING)).getOrThrow();

      if (!Number.class.isAssignableFrom(listType.getContainedType().internalType())) {
        throw new ProblemException(
            TypeProblems.get().mismatch("x-values", Number.class, listType.getContainedType().internalType()));
      }

      ScopedLambdaType type = Types.findOrThrow("apply-to",
          new ScopedLambdaType(Struct.EMPTY_STRUCT, "x"), argumentTypes.get(1));

      if (type.getArgs().size() != 1) {
        throw new ProblemException(ArgsProblems.mismatch(arguments.get("apply-to"), type));
      }

      Struct lambdaScope = type.buildCallingScopeType(Types.FLOATING);

      Argument applyToArg = arguments.getRequiredArgument(functionCall, "apply-to").getOrThrow();
      Expression lambdaBody = applyToArg.getExpression().isA(Lambda.class).get().getExpression();

      RealizedExpression expression = context.getExpressionRealizer().realize(lambdaScope, lambdaBody)
          .getOrThrow(Problems.foundWith("apply-to"));

      boolean applyLogToX;
      if (argumentTypes.size() == 3) {
        applyLogToX = arguments.evaluateConstant(context, functionCall, "apply-log-to-x", Boolean.class, Types.BOOLEAN)
        .getOrThrow();
      } else {
        applyLogToX = false;
      }

      LinearContinuousFunctionType returnType = new LinearContinuousFunctionBuilder(context).build(builder -> {
        builder.xType = Types.FLOATING;
        builder.xValues = Doubles.toArray((Collection<? extends Number>) xValues);
        builder.yExpression = expression;
        builder.logScale = applyLogToX;
      }).getOrThrow(PROBLEMS.couldNotCreateContinuousFunctionFromYValue(lambdaBody, expression.getResultType()));

      return new FunctionImpl(argumentTypes, returnType);
    });
  }

  public RiskscapeFunction asFunction() {
    return RealizableFunction.asFunction(this, arguments, LinearContinuousFunctionType.ANY);
  }
}
