/*
 * 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.function.expression;

import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

import lombok.Getter;
import nz.org.riskscape.dsl.LexerException;
import nz.org.riskscape.dsl.ParseException;
import nz.org.riskscape.engine.Project;
import nz.org.riskscape.engine.bind.BoundJavaParameters;
import nz.org.riskscape.engine.bind.BoundParameters;
import nz.org.riskscape.engine.bind.JavaParameterSet;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.FunctionFramework;
import nz.org.riskscape.engine.function.FunctionFrameworkSupport;
import nz.org.riskscape.engine.function.FunctionMetadata;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.function.MetadataParams;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ExpressionParser;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.Lambda;

/**
 * Define RiskScape functions using RiskScape's built-in expression language (using lambda syntax)
 */
public class ExpressionFunctionFramework implements FunctionFramework, FunctionFrameworkSupport {

  interface LocalProblems extends ProblemFactory {
    Problem argCountMismatch(int typeCount, int argCount);

    Problem returnTypeCoercionFailed(Object value, Type actual, Type declared);
  }

  private static final ArgumentList NO_ARGS_GIVEN = new ArgumentList(List.of());

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

  private static MetadataParams getDefaultParams() {
    MetadataParams defaults = new MetadataParams();
    defaults.argumentTypes = NO_ARGS_GIVEN;
    defaults.returnType = Nullable.ANYTHING;
    return defaults;
  };

  public static final MetadataParams NONE_GIVEN = getDefaultParams();

  @Getter
  private final String id = "expression";

  @Getter
  private final JavaParameterSet<MetadataParams> parameterSet =
    JavaParameterSet.fromBindingInstance(MetadataParams.class, getDefaultParams());

  @Override
  public ResultOrProblems<IdentifiedFunction> build(String functionName, Project project, BoundParameters bound) {
    // build the function with the given metadata
    BoundJavaParameters<MetadataParams> bindResult = parameterSet.bindToObject(bound);
    MetadataParams params = bindResult.getBoundToObject();

    return loadFunctionFromParams(project.getEngine(), params)
        .flatMap(resource ->
            //  make sure the source parses in to a lambda expression
            parseFunctionFromResource(resource)
            .flatMap(parsedLambdaExpression ->
                // make sure argument-types agrees with lambda args, infer if not given
                checkArgsAndBuildMetadata(functionName, bindResult, parsedLambdaExpression)
                  .map(functionMetadata ->
                      // everything is present and correct
                      new RealizableExpressionFunction(functionMetadata, resource, parsedLambdaExpression).identified()
                  )
            )
        );
  }

  /**
   * Does some gerrymandering of the FunctionMetadata to cope with the fact that we 'pickle' the default params so that
   * the user doesn't have to supply return-type or argument-types unless they want to
   */
  private ResultOrProblems<FunctionMetadata> checkArgsAndBuildMetadata(
      String functionName,
      BoundJavaParameters<MetadataParams> bindResult,
      Lambda functionExpression
  ) {
    MetadataParams params = bindResult.getBoundToObject();
    final ArgumentList givenArgList = params.argumentTypes;

    // did the user explicitly supply an argument-types parameter?
    boolean argTypesParameterGiven = bindResult.getUnbound().containsKey("argument-types");

    if (argTypesParameterGiven) {
      // argument types specified explicitly, make sure the counts match
      if (givenArgList.size() != functionExpression.getArguments().size()) {
        return ResultOrProblems.failed(
            PROBLEMS.argCountMismatch(givenArgList.size(), functionExpression.getArguments().size())
        );
      }

      // if the given argument types were anonymous, we can infer names from the lambda expression - this will make the
      // function metadata look nicer when you run `function list`
      if (givenArgList.stream().anyMatch(Predicate.not(FunctionArgument::hasKeyword))) {
        params.argumentTypes = new ArgumentList(givenArgList
          .stream()
          .map(arg -> reKeyArgument(arg, functionExpression)).toList());
      }
    } else {
      // argument types not given, build some anything-type args from lambda (so later validation works and we have
      // something to show in the listing)
      List<FunctionArgument> formedArgs = functionExpression.getArguments().stream()
          .map(token -> new FunctionArgument(token.getValue(), Nullable.ANYTHING))
          .toList();

      params.argumentTypes = new ArgumentList(formedArgs);
    }

    return ResultOrProblems.of(params.toFunctionMetadata(functionName));
  }

  /**
   * @return a FunctionArgument with a keyword that matches the lambda expression's, unless it was explicitly given
   * a keyword in the type definition
   */
  private FunctionArgument reKeyArgument(FunctionArgument arg, Lambda lambda) {
    if (arg.hasKeyword()) {
      return arg;
    } else {
      return new FunctionArgument(lambda.getArguments().get(arg.getIndex()).getValue(), arg.getType());
    }
  }

  /**
   * Parse the function's expression, and make sure that it's a lambda
   */
  private ResultOrProblems<Lambda> parseFunctionFromResource(Resource source) {
    Expression expression;
    try {
      expression = ExpressionParser.INSTANCE.parse(source.getContentAsString());
    } catch (ParseException | LexerException e) {
      return ResultOrProblems.failed(Problems.caught(e));
    }

    return expression
        .isA(Lambda.class)
        .map(ResultOrProblems::of)
        .orElse(ResultOrProblems.failed(
            ExpressionProblems.get().mismatch(expression, Lambda.class, "(a, b) -> a + b")
        ));
  }

  @Override
  public boolean canBuild(Project project, Map<String, List<?>> unbound) {
    return MetadataParams.locationEndsWith(unbound, ".txt");
  }
}
