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

import com.google.common.collect.Range;
import com.google.common.primitives.Doubles;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.bind.ParameterField;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.BaseRealizableFunction;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.relation.Relation;
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.RelationType;
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.engine.util.FunctionCallOptions;
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;

/**
 * Function that makes a {@link LinearContinuousState} from a relation.
 */
public class ToContinuousCurve extends BaseRealizableFunction {

  public interface LocalProblems extends ProblemFactory {

    /**
     * When an x value has been encountered multiple times.
     */
    Problem duplicateXValue(double x, Object amongst);

    /**
     * The expression is not suitable for use in interpolation, e.g. contains non-numbers
     */
    Problem badYValue(Expression offendingExpression);

    /**
     * There were no data points collected
     */
    Problem empty(int tuplesSize);
  }

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

  public static class Options {
    @ParameterField
    public boolean applyLogToX = false;
  }

  public static final ArgumentList ARGUMENTS = ArgumentList.fromArray(
      new FunctionArgument("relation", RelationType.WILD),
      new FunctionArgument("x-value", new LambdaType("row")),
      new FunctionArgument("y-value", new LambdaType("row")),
      FunctionCallOptions.options(Options.class)
  );

  public ToContinuousCurve() {
    super(ARGUMENTS, NonStackableLinearContinuousFunctionType.ANY);
  }

  @Override
  public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context, FunctionCall functionCall,
      List<Type> givenTypes) {
    return ProblemException.catching(() -> {
      if (givenTypes.size() < 3 || givenTypes.size() > ARGUMENTS.size()) {
        throw new ProblemException(
            ArgsProblems.get().wrongNumber(Range.closed(3, ARGUMENTS.size()), givenTypes.size())
        );
      }

     Type elementType = givenTypes.get(0).findAllowNull(RelationType.class)
         .<Type>map(RelationType::getMemberType)
         // or we can accept a list input (as long as it contains a struct member)
         .or(() -> givenTypes.get(0).findAllowNull(RSList.class)
             .map(RSList::getMemberType)
          )
         .orElseThrow(() -> new ProblemException(ArgsProblems.mismatch(ARGUMENTS.get("relation"), givenTypes.get(0))));

     LambdaArg xArg = buildLambdaArg(context, functionCall, givenTypes, elementType, "x-value");
     LambdaArg yArg = buildLambdaArg(context, functionCall, givenTypes, elementType, "y-value");

      Options options = FunctionCallOptions
          .bindOptions(Options.class, context, arguments, functionCall)
          .getOrThrow();

      // check x is a number up front- gives a nicer error message
      Type xArgType = xArg.expression.getResultType();
      if (!(xArgType.findAllowNull(Types.FLOATING.getClass()).isPresent()
          || xArgType.findAllowNull(Types.INTEGER.getClass()).isPresent())) {
        throw new ProblemException(TypeProblems.get().mismatch("x-value", Types.FLOATING, xArgType));
      }

      LinearContinuousFunctionBuilder builder = new LinearContinuousFunctionBuilder(context);
      builder.logScale = options.applyLogToX;
      builder.yExpressionType = Optional.of(yArg.expression.getResultType());
      // we always cast to a double
      builder.xType = Types.FLOATING;

      // NB: this works at the moment, but if we added more failure cases to the builder then it might not be true
      // and we'd want to "clean up" the problems between the different linear implementations at that point.
      NonStackableLinearContinuousFunctionType returnType = builder.buildNonStackable(b -> {})
          .getOrThrow(PROBLEMS.badYValue(yArg.expression.getExpression()));

      return RiskscapeFunction.create(this, givenTypes, returnType, args -> {
        Object input = args.get(0);
        List<Tuple> tuples;
        if (input instanceof Relation relation) {
          tuples = relation.stream().toList();
        } else if (input instanceof List list) {
          tuples = list;
        } else {
          throw new AssertionError("Unexpected list type - " + input);
        }

        // use linked lists for constant time insertion, trading off against using space while we collect all the values
        LinkedList<Double> xValues = new LinkedList<>();
        LinkedList<Object> yValues = new LinkedList<>();

        for (Object row : tuples) {
          Number x = (Number) xArg.evaluate(args, row);

          if (x == null) {
            continue;
          }

          double xValue = x.doubleValue();

          // find insertion index to maintain sort order
          int insertionIndex = findInsertionIndex(xValues, xValue, row);

          Object y = yArg.evaluate(args, row);

          if (y == null) {
            continue;
          }

          // x and y need to be in the same position
          xValues.add(insertionIndex, xValue);
          yValues.add(insertionIndex, y);

          // this is a somewhat expensive test, so limit it to unit tests
          assert isSorted(xValues);
        }

        if (xValues.isEmpty()) {
          throw new RiskscapeException(PROBLEMS.empty(tuples.size()));
        }

        return new NonStackableLinearContinuousState(Doubles.toArray(xValues), yValues.toArray());
      });
    });
  }

  // for assertions
  private boolean isSorted(LinkedList<Double> xValues) {
    List<Double> copy =  new ArrayList<>(xValues);

    copy.sort(Double::compareTo);

    return copy.equals(xValues);
  }

  // does a binary search for where the new x should go
  private int findInsertionIndex(LinkedList<Double> xValues, double x, Object context) {

    if (xValues.isEmpty()) {
      return 0;
    }

    int index = java.util.Collections.binarySearch(xValues, x);
    if (index >= 0) {
      throw new RiskscapeException(PROBLEMS.duplicateXValue(x, context));
    } else {
      // No exact match - binarySearch returns (-(insertion point) - 1)
      // Convert to the insertion point
      return -(index + 1);
    }
  }

  // helper for realizing and evaluating the lambda
  record LambdaArg(FunctionArgument arg, RealizedExpression expression) {

    public Object evaluate(List<Object> args, Object row) {
      ScopedLambdaExpression givenLambda = (ScopedLambdaExpression) args.get(arg.getIndex());

      Tuple combinedScope = givenLambda.buildCallingScope(expression.getInputType().asStruct(), row);
      return expression.evaluate(combinedScope);
    }
  }

  private LambdaArg buildLambdaArg(RealizationContext context, FunctionCall functionCall, List<Type> givenTypes,
      Type memberType, String argName) throws ProblemException {

    FunctionArgument functionArgument = ARGUMENTS.get(argName);

    // make sure it's there
    Argument argExpression = ARGUMENTS.getRequiredArgument(functionCall, argName).getOrThrow();

    Lambda lambdaExpression = argExpression.getValue().isA(Lambda.class).orElseThrow(() -> new ProblemException(
        TypeProblems.get().mismatch(argExpression, Lambda.class, argExpression.getValue().getClass())));

    // this has to be a lambda type, we've asserted it's a lambda expression above, so no need to handle the or case
    ScopedLambdaType lambdaType = givenTypes.get(functionArgument.getIndex()).find(ScopedLambdaType.class).get();

    Struct lambdaScopeType = lambdaType.buildCallingScopeType(memberType);
    RealizedExpression realizedExpression =
        context.getExpressionRealizer().realize(lambdaScopeType, lambdaExpression.getExpression()).getOrThrow();

    return new LambdaArg(functionArgument, realizedExpression);
  }
}
