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

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import nz.org.riskscape.dsl.Token;
import nz.org.riskscape.engine.ArgsProblems;
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.types.TypeProblems;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.TokenTypes;

@RequiredArgsConstructor @EqualsAndHashCode(callSuper = false, of = {"identifier", "arguments"}) @Getter @Setter
public final class FunctionCall extends BaseExpr {

  public static final class Argument extends GenericArgument<Expression> {

    public Argument(Expression expression, Optional<Token> token) {
      super(expression, token);
    }

    public Argument(Expression expression, String keyword) {
      super(expression, Optional.of(Token.token(TokenTypes.KEY_IDENTIFIER, keyword)));
    }

    public Argument(Expression expression) {
      super(expression, Optional.empty());
    }

    /**
     * Attempts to realize and evaluate this argument against an empty {@link Struct}, returning useful
     * problems if the expression wasn't constant or if the returned type doesn't match the expected java type.
     *
     * {@link nz.org.riskscape.engine.rl.ExpressionRealizer#realizeConstant(Expression)} has more details.
     * @param <T> the expected object
     * @param requiredJavaType the java type that we expect the expression to yield.  Checked against the expression's
     * return type, not the actual constant value's class type.
     * @param requiredType a riskscape type to use in any error message that's generated
     */
    public <T> ResultOrProblems<T> evaluateConstant(RealizationContext context, Class<T> requiredJavaType,
        Type requiredType) {

      return context.getExpressionRealizer().realizeConstant(getValue()).flatMap(realized -> {
        // NB this checks the declared return type, rather than the evaluated return type, which might not always
        // be the right thing to do.  For now it stays like this, because I don't want to shave this particular yak
        // right now
        if (!requiredJavaType.isAssignableFrom(realized.getResultType().internalType())) {
          return ResultOrProblems.failed(
              TypeProblems.get().mismatch(getValue(), requiredType, realized.getResultType())
          );
        }

        Object returned = realized.evaluateConstant();

        if (returned == null) {
          // Note that if the expression is constant but returns null, this method returns a
          // ArgsProblems.constantNull. While this seems odd, this makes it much easier to handle the null behaviour
          // in practice.  Typically with arguments, we will try to evaluate them as constants first, then fall back
          // to normal.  In this case, the problem is ignored, and the user never sees it - we either test the
          // ResultOrProblems or do an orElse(null).
          //
          // In the case that the constant is required, the user correctly see a problem message that the constant
          // argument was null, e.g. Problems found with options - null is not an allowed value
          return ResultOrProblems.failed(ArgsProblems.get().constantNull());
        }
        return ResultOrProblems.of(requiredJavaType.cast(returned));
      });
    }

    /**
     * @deprecated use getValue() instead.
     */
    @Deprecated
    public Expression getExpression() {
      return getValue();
    }
  }

  private final Token identifier;
  private final List<Argument> arguments;
  private final Optional<Pair<Token, Token>> boundary;

  public FunctionCall(Token identifier, List<Argument> arguments, Token closing) {
    this(identifier, arguments, Optional.of(Pair.of(identifier, closing)));
  }

  public FunctionCall(Token identifier, List<Argument> arguments) {
    this(identifier, arguments, Optional.empty());
  }

  @Override
  protected void appendSource(StringBuilder appendTo) {
    appendTo.append(identifier.rawValue());
    join(appendTo, arguments, (sb, a) -> a.appendSource(sb), ", ", "(", ")");
  }

  public int keywordArgumentsOffset() {
    int i = 0;
    for (; i < arguments.size(); i++) {
      if (arguments.get(i).getName().isPresent()) {
        break;
      }
    }
    return i;
  }

  public boolean hasKeywordArguments() {
    return keywordArgumentsOffset() < arguments.size();
  }

  /**
   * @return argIndex of argument with name toFind, or -1 if not found
   */
  public int indexOfArgNamed(String toFind) {
    for (int i = 0; i < arguments.size(); i++) {
      Argument arg = arguments.get(i);
      if (arg.getName().map(name -> name.equals(toFind)).orElse(false)) {
        return i;
      }
    }
    return -1;
  }

  @Override
  public <T, R> R accept(ExpressionVisitor<T, R> visitor, T data) {
    return visitor.visit(this, data);
  }

  /**
   * Builds a list of all the arguments that were given before the first keyword argument appears
   *
   * Note that the parser is currently allowing (I think) positional elements to occur after keywords, which will break
   * this code.  We should probably stop this as I'm 99% sure we never want positional args to be interleaved with
   * keyword args
   */
  public List<Argument> getPositionalArguments() {
    List<Argument> positionals = new ArrayList<>(this.arguments.size());

    for (Argument argument : arguments) {
      if (argument.getNameToken().isPresent()) {
        return positionals;
      } else {
        positionals.add(argument);
      }
    }

    return positionals;
  }

  @Override
  public boolean isLiteral() {
    return false;
  }

}
