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

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.google.common.collect.Range;
import com.google.common.collect.Streams;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.typeset.TypeSet;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.FunctionCall;
import nz.org.riskscape.rl.ast.FunctionCall.Argument;


public class ArgumentList extends AbstractList<FunctionArgument> {

  public static ArgumentList fromArray(FunctionArgument... functionArguments) {
    return new ArgumentList(Arrays.asList(functionArguments));
  }

  /**
   * Creates an ArgumentList that matches the given struct. The keywords take the member names and are defined in the
   * order they appeared in the struct.
   */
  public static ArgumentList fromStruct(Struct struct) {
    return new ArgumentList(
        struct.getMembers().stream()
        .map(sm -> new FunctionArgument(sm.getKey(), sm.getType()))
        .collect(Collectors.toList()));
  }

  /**
   * @return an ArgumentList from an anonymous list of types
   */
  public static ArgumentList anonymous(List<Type> argTypes) {
    List<FunctionArgument> args = new ArrayList<>(argTypes.size());
    int index = 0;
    for (Type type : argTypes) {
      args.add(new FunctionArgument(index, type));
      index++;
    }
    return new ArgumentList(args);
  }

  /**
   * Create a new ArgumentList from the given list of FunctionArguments.  Note that the given arguments aren't cloned,
   * but are assigned their indices based on their position in the list.
   */
  public ArgumentList(List<FunctionArgument> asList) {
    this.arguments = asList;
    for (int i = 0; i < asList.size(); i++) {
      arguments.get(i).setIndex(i);
    }
  }

  /**
   * Create a no-arg list.  Mostly here for completeness/tests.
   */
  public static ArgumentList create() {
    return new ArgumentList(List.of());
  }

  /**
   * Create an unary argument list.  Shorthand for ArgumentList.fromArray(new FunctionArgument(kw0, arg0)).
   */
  public static ArgumentList create(String kw0, Type t0) {
    return new ArgumentList(Arrays.asList(
      new FunctionArgument(kw0, t0)
    ));
  }

  /**
   * Create a binary argument list.  Shorthand for ArgumentList.fromArray(new FunctionArgument(kw0, arg0), ...).
   */
  public static ArgumentList create(String kw0, Type t0, String kw1, Type t1) {
    return new ArgumentList(Arrays.asList(
      new FunctionArgument(kw0, t0),
      new FunctionArgument(kw1, t1)
    ));
  }

  /**
   * Create a ternary argument list.  Shorthand for ArgumentList.fromArray(new FunctionArgument(kw0, arg0), ...).
   */
  public static ArgumentList create(String kw0, Type t0, String kw1, Type t1, String kw2, Type t2) {
    return new ArgumentList(Arrays.asList(
      new FunctionArgument(kw0, t0),
      new FunctionArgument(kw1, t1),
      new FunctionArgument(kw2, t2)
    ));
  }

  /**
   * Create a quarternary argument list.  Shorthand for ArgumentList.fromArray(new FunctionArgument(kw0, arg0), ...).
   */
  public static ArgumentList create(
      String kw0, Type t0, String kw1, Type t1, String kw2, Type t2, String kw3, Type t3
  ) {
    return new ArgumentList(Arrays.asList(
      new FunctionArgument(kw0, t0),
      new FunctionArgument(kw1, t1),
      new FunctionArgument(kw2, t2),
      new FunctionArgument(kw3, t3)
    ));
  }


  private final List<FunctionArgument> arguments;
  // memoized for matching in constant expression
  private List<String> keywords;

  @Override
  public FunctionArgument get(int index) {
    return arguments.get(index);
  }

  /**
   * @return the maximum number of arguments accepted (including any optional/nullable ones)
   */
  @Override
  public int size() {
    return arguments.size();
  }

  /**
   * @return the range of arguments accepted. The lower bound includes only the required arguments,
   *         and the upper bound includes any optional (nullable) arguments
   */
  public Range<Integer> getArity() {
    return Range.closed(getMinimumSize(), size());
  }

  /**
   * In general, {@link Nullable} argument types can be omitted from the function
   * call, as long as they are the last argument(s)
   *
   * @return the bare minimum number of non-nullable arguments that need to be supplied
   */
  private int getMinimumSize() {
    List<Type> argTypes = getArgumentTypes();
    int argNum;
    for (argNum = argTypes.size(); argNum > 0; argNum--) {
      if (!argTypes.get(argNum - 1).isNullable()) {
        break;
      }
    }
    return argNum;
  }

  /**
   * @return the FunctionArgument with the given keyword
   * @throws IllegalArgumentException if the keyword isn't defined in this {@link ArgumentList}
   */
  public FunctionArgument get(String keyword) {
    for (FunctionArgument functionArgument : arguments) {
      if (functionArgument.getKeyword().equals(keyword)) {
        return functionArgument;
      }
    }
    // coding error: we should generally always know the keyword arguments
    new IllegalArgumentException("no argument named " + keyword + " is declared");
    return null;
  }

  /**
   * @return true if this function declares an argument with the given keyword
   */
  public boolean hasArgument(String keyword) {
    return getKeywords().contains(keyword);
  }

  public List<String> getKeywords() {
    if (keywords == null) {
      keywords = arguments.stream().map(FunctionArgument::getKeyword).collect(Collectors.toList());
    }
    return keywords;
  }

  public List<Type> getArgumentTypes() {
    return stream().map(FunctionArgument::getType).collect(Collectors.toList());
  }

  /**
   * Returns the FunctionCall {@link Argument} (i.e. the actual value passed to the function),
   * as opposed to the {@link FunctionArgument} (i.e. the placeholder).
   */
  public Optional<Argument> getArgument(FunctionCall fc, String keywordName) {
    return get(keywordName).getFunctionCallArgument(fc);
  }

  public ResultOrProblems<Argument> getRequiredArgument(FunctionCall fc, String keyword) {
    return getArgument(fc, keyword).map(a -> ResultOrProblems.of(a)).orElse(ResultOrProblems.failed(
        ArgsProblems.get().required(keyword))
    );
  }

  /**
   * @return the actual type of the argument provided by the user, or an
   *         appropriate error if it doesn't match what was expected.
   */
  public <T extends Type> ResultOrProblems<T> getRequiredAs(List<Type> givenTypes, int argIndex,
      Class<T> requiredType) {
    FunctionArgument expected = get(argIndex);
    // first, sanity-check we don't overrun the list of args supplied
    if (givenTypes.size() <= argIndex) {
      return ResultOrProblems.failed(GeneralProblems.get().required(expected));
    }
    Type givenType = givenTypes.get(argIndex);
    if (!givenType.findAllowNull(requiredType).isPresent()) {
      return ResultOrProblems.failed(ArgsProblems.mismatch(expected, givenType));
    }
    return ResultOrProblems.of(givenType.findAllowNull(requiredType).get());
  }

  /**
   * Use {@link FunctionArgument#evaluateConstant(RealizationContext, FunctionCall, Class)} instead
   */
  @Deprecated
  public <T> ResultOrProblems<T> evaluateConstant(
      RealizationContext context,
      FunctionCall functionCall,
      String keyword,
      Class<T> requiredJavaType,
      Type requiredType
  ) {
    return get(keyword).evaluateConstant(context, functionCall, requiredJavaType);
  }

  /**
   * @return true if the given types are compatible with these arguments (i.e. can
   *         be realized), false if not
   */
  public boolean isCompatible(RealizationContext context, List<Type> givenTypes) {
    return getArgumentTypes().equals(givenTypes) || areArgsAssignable(context.getProject().getTypeSet(), givenTypes);
  }

  private boolean areArgsAssignable(TypeSet typeSet, List<Type> givenTypes) {
    return getArity().contains(givenTypes.size())
        && Streams.zip(givenTypes.stream(), getArgumentTypes().stream(), Pair::of)
            .allMatch(pair -> typeSet.isAssignable(pair.getLeft(), pair.getRight()));
  }

  /**
   * Convenience version of {@link nz.org.riskscape.engine.function.FunctionArgument#withExtraArgument
   * that accepts the keyword and type of the extra argument
   * @param keyword the keyword for the extra argument
   * @param type    the type of the extra argument
   * @return new argument list
   */
  public ArgumentList withExtraArgument(String keyword, Type type) {
    return withExtraArgument(new FunctionArgument(keyword, type));
  }

  /**
   * Return a new argument list which has the same arguments has this one but with extraArg appended.
   * @param extraArgs extra arguments to append to the new argument list
   * @return new argument list
   */
  public ArgumentList withExtraArgument(FunctionArgument... extraArgs) {
    List<FunctionArgument> newArguments = Lists.newArrayList(this);
    for (FunctionArgument extraArg: extraArgs) {
      newArguments.add(extraArg);
    }
    return new ArgumentList(newArguments);
  }

  /**
   * @return A list of problems from realization against the given types, or an
   *         empty list if there are no problems
   */
  public List<Problem> getProblems(RealizationContext context, List<Type> givenArgs) {
    return getProblems(context, givenArgs,
        (expected, given) -> Arrays.asList(ArgsProblems.mismatch(expected, given)));
  }

  /**
   * Same as {@link #getProblems(RealizationContext, List)} except it lets you
   * customize how argument/type mismatches are reported
   */
  public List<Problem> getProblems(RealizationContext context, List<Type> givenArgs,
      BiFunction<FunctionArgument, Type, List<Problem>> describeMismatch) {

    if (!getArity().contains(givenArgs.size())) {
      return Arrays.asList(ArgsProblems.get().wrongNumber(getArity(), givenArgs.size()));
    }

    List<Problem> problems = new ArrayList<>();
    TypeSet typeset = context.getProject().getTypeSet();
    for (int i = 0; i < givenArgs.size(); i++) {
      FunctionArgument expectedArg = get(i);
      Type givenType = givenArgs.get(i);

      if (!typeset.isAssignable(givenType, expectedArg.getType())) {
        // don't complain about coercible types here. A realizable function sometimes gets given
        // the original types as is (uncoerced), e.g. if not all arguments are coercible. Because
        // it's generally not the coercible argument that's the root problem, we'd just confuse
        // the user further by complaining about coercible types here
        // TODO this papers over issues with realizable functions in DefaultFunctionResolver
        // in order to give the user better errors. Long term we need a single source of truth
        if (!typeset.findEquivalenceCoercer(givenType, expectedArg.getType()).isPresent()) {
          problems.addAll(describeMismatch.apply(expectedArg, givenType));
        }
      }
    }

    if (problems.isEmpty() && !isCompatible(context, givenArgs)) {
      // if we didn't find an obviously incompatible type, then just give the user a vague error
      return Arrays.asList(ArgsProblems.get().realizableDidNotMatch(RiskscapeFunction.class, givenArgs));
    }
    return problems;
  }

  /**
   * Very basic arity validation for use within a
   * {@link ProblemException#catching(nz.org.riskscape.problem.ProblemException.Call)} block.
   *
   * Note that this method isn't appropriate for all functions, as we have foolishly overloaded nullability with an
   * argument being required, which isn't always the same thing.
   */
  public void validateArity(List<Type> givenArgs) throws ProblemException {
    if (!getArity().contains(givenArgs.size())) {

      Integer lowerEndpoint = getArity().lowerEndpoint();
      if (Range.singleton(lowerEndpoint).equals(getArity())) {
        // this makes test assertions etc less verbose
        throw new ProblemException(ArgsProblems.get().wrongNumber(lowerEndpoint, givenArgs.size()));
      } else {
        throw new ProblemException(ArgsProblems.get().wrongNumber(getArity(), givenArgs.size()));
      }
    }
  }
}
