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

import com.google.common.primitives.Doubles;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.defaults.interp.BilinearContinuousFunctionType.Options;
import nz.org.riskscape.defaults.interp.BilinearContinuousFunctionType.ZeroLoss;
import nz.org.riskscape.defaults.interp.CreateContinuousFunction.LocalProblems;
import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.RiskscapeFunction;
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.Struct.StructMember;
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.engine.util.FunctionCallOptions;
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;

public class CreateBilinearContinuousFunction implements RealizableFunction {

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

  private final ArgumentList arguments = ArgumentList.fromArray(
    new FunctionArgument("x-values", RSList.create(Types.ANYTHING)),
    new FunctionArgument("y-values", RSList.create(Types.ANYTHING)),
    new FunctionArgument("apply-to", new LambdaType("x-value", "y-value")),
    FunctionCallOptions.options(Options.class)
  );

  @RequiredArgsConstructor
  private class FunctionImpl implements RiskscapeFunction {

    @Getter
    private final List<Type> argumentTypes;

    @Getter
    private final BilinearContinuousFunctionType returnType;

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

      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() - 1 || argumentTypes.size() > arguments.size()) {
        throw new ProblemException(ArgsProblems.get()
            .wrongNumberRange(arguments.size() - 1, arguments.size(), argumentTypes.size()));
      }

      double[] xValues = extractSortedValues("x-values", argumentTypes.get(0), functionCall, context);
      double[] yValues = extractSortedValues("y-values", argumentTypes.get(1), functionCall, context);

      ScopedLambdaType lambdaType = Types.findOrThrow("apply-to",
          new ScopedLambdaType(Struct.EMPTY_STRUCT, "x", "y"), argumentTypes.get(2));

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

      Struct lambdaScope = lambdaType.buildCallingScopeType(Types.FLOATING, Types.FLOATING);

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

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

      Options options = FunctionCallOptions.bindOptionsOrThrow(Options.class, context, arguments, functionCall);
      // we need to extract the zero loss from the options ourselves here to ensure its compatible with
      // valueExpressions return type.
      Optional<ZeroLoss> zeroLoss = getZeroLoss(context, functionCall, valueExpression.getResultType());

      BilinearContinuousFunctionType returnType = new BilinearContinuousFunctionType.Builder(context).build(builder -> {
        builder.valueExpression = valueExpression;
        builder.xValues = xValues;
        builder.yValues = yValues;
        builder.zeroLoss = zeroLoss;
        builder.options = options;
      }).getOrThrow(PROBLEMS.couldNotCreateContinuousFunctionFromYValue(lambdaBody, valueExpression.getResultType()));

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

  /**
   * Extract the zero loss from the function call and ensure it is compatible with valueExpression's
   * return type.
   */
  private Optional<ZeroLoss> getZeroLoss(RealizationContext context, FunctionCall functionCall,
      Type valueExpressionType) throws ProblemException {
    Optional<ResultOrProblems<Tuple>> boundOptions = FunctionCallOptions.bindTuple(context, arguments, functionCall);
    if (boundOptions.isPresent()) {
      // function call contains options
      Tuple optionsTuple = boundOptions.get().getOrThrow();
      StructMember zeroLossMember = optionsTuple.getStruct().getMember("zero_loss").orElse(null);
      if (zeroLossMember != null) {
        // a zero loss is provided in those options
        // we coerce the given value to the valueExpressions return type to ensure the given zero loss
        // is safe to use.
        Type zeroLossType = zeroLossMember.getType();
        return Optional.of(
            new ZeroLoss(context.getTypeSet().findEquivalenceCoercer(zeroLossType, valueExpressionType)
                .map(c -> c.apply(optionsTuple.fetch("zero_loss")))
                .orElseThrow(() -> new ProblemException(Problems.foundWith(
                "zero_loss",
                TypeProblems.get().mismatch("zero_loss", valueExpressionType, zeroLossType)
            ))))
        );
      }
    }
    return Optional.empty();
  }

  private double[] extractSortedValues(String argumentName, Type argType,
      FunctionCall functionCall, RealizationContext context) throws ProblemException {
    RSList listType = Types.findOrThrow(argumentName, RSList.create(Types.ANYTHING), argType);
    if (!listType.getMemberType().isNumeric()) {
      throw new ProblemException(ArgsProblems.mismatch(arguments.get(argumentName), argType));
    }

    List<?> collection = arguments.getRequiredArgument(functionCall, argumentName)
        .flatMap(arg -> arg.evaluateConstant(context, List.class, RSList.LIST_ANYTHING)
        .composeProblems((sev, problems) -> Problems.foundWith(argumentName, problems))
        ).getOrThrow();

    @SuppressWarnings("unchecked")
    double[] values = Doubles.toArray((List<? extends Number>) collection);
    Arrays.sort(values);
    return values;
  }

  public RiskscapeFunction asFunction() {
    return RealizableFunction.asFunction(this, arguments, BilinearContinuousFunctionType.ANY_BILINEAR);
  }

}
