/*
 * 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.wizard.ask;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.cli.ExitException;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.i18n.MessageFactory;
import nz.org.riskscape.engine.i18n.TranslationContext;
import nz.org.riskscape.engine.rl.FunctionCallPrototype;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.FunctionCall;
import nz.org.riskscape.wizard.Answer.Response;
import nz.org.riskscape.wizard.Answer;
import nz.org.riskscape.wizard.AskerHints;
import nz.org.riskscape.wizard.Choice;
import nz.org.riskscape.wizard.CliPrompter;
import nz.org.riskscape.wizard.Question;
import nz.org.riskscape.wizard.bld.IncrementalBuildState;
import nz.org.riskscape.wizard.survey2.Choices;

/**
 * An {@link Asker} for {@link FunctionCallPrototype}s that will ask extra questions if the chosen
 * aggregation function requires extra arguments for it's configuration.
 */
public class AggregationFunctionPrototypeAsker extends CompatAsker {

  public interface Messages extends MessageFactory {
    String noSuitableDefined(String collectionName);
  }

  private final Messages messages;

  /**
   * A place holder that will be added to the produced {@link FunctionCall} as
   * argument 0 which is always where aggregation functions expect the value expression to be.
   */
  static final String VALUE_PLACEHOLDER = "x";

  public AggregationFunctionPrototypeAsker(TranslationContext context) {
    super(context);
    this.messages = context.newFactory(Messages.class);
  }

  @Override
  public boolean canAsk(IncrementalBuildState buildState, Question question) {
    return question.getParameterType().equals(FunctionCallPrototype.class)
        && question.hasAnnotation(AskerHints.AGGREGATION);
  }

  public ResultOrProblems<Response> chooseAggregationFunction(CliPrompter cliPrompter,
      IncrementalBuildState buildState, Question question) {

    // Don't use question getChoices - we want a different set of options that
    // allows more customization than the non interactive version allows
    List<Choice> choices = Choices.forAggregation(buildState);

    // sanity-check there are actually some Identified things to choose from
    if (choices.size() == 0) {
      cliPrompter.printError(messages.noSuitableDefined(IdentifiedFunction.class.getSimpleName()));

      throw new ExitException(1, "Please ensure the --project file or --home directory being used has "
          + IdentifiedFunction.class.getSimpleName() + "s defined and try again");
    }

    Choice chosen = pickChoice(choices, cliPrompter, cliPrompter.getPrompt(question));
    return Answer.bind(buildState.getBindingContext(), question, chosen.getValue());
  }

  @Override
  public ResultOrProblems<Response> ask(CliPrompter cliPrompter, IncrementalBuildState buildState, Question question) {

    // response will be an identified function that contains an aggregation function
    ResultOrProblems<Response> responseOr = chooseAggregationFunction(cliPrompter, buildState, question);

    if (responseOr.hasErrors()) {
      return responseOr;
    }
    Response response = responseOr.get();

    FunctionCallPrototype aggFunctionPrototype = (FunctionCallPrototype) response.getBoundValue();
    IdentifiedFunction aggFunction = buildState.getBindingContext().bind(
        aggFunctionPrototype.getPrototype().getIdentifier().getValue(),
        IdentifiedFunction.class
    ).get(); // get because this should always work- not the user's fault if it doesn't

    if (aggFunction.getArguments().size() <= 1) {
      // If the the function has only one or less arguments then we are done.
      return responseOr;
    }

    Optional<RSList> firstArgList = aggFunction.getArgumentTypes().get(0).find(RSList.class);
    if (! firstArgList.isPresent()) {
      // If the first argument type is not a list type we are also done as aggregation functions require
      // the first arg to be a list. But some of the simple aggregations (those that don't have extra args)
      // are overloaded to take two numbers (e.g. min, max)
      return responseOr;
    }

    // We are building up the function call, so we need to start by adding a placeholder for the
    // value to aggregate argument
    aggFunctionPrototype.addArgument(Optional.empty(), VALUE_PLACEHOLDER);

    for (int i = 1; i < aggFunction.getArguments().size(); i++) {
      // aggregation functions may require some extra arguments, such as percentile(s) which need
      // the percentile(s) to aggregate to.
      FunctionArgument arg = aggFunction.getArguments().get(i);
      Type argType = arg.getType();
      boolean allowMany = false;
      Optional<RSList> listArg = arg.getType().find(RSList.class);

      if (listArg.isPresent()) {
        allowMany = true;
        argType = listArg.get().getMemberType();
      }

      // If the argument is named we will use that name in the function calls that get created.
      Optional<String> argName = Optional.empty();
      String argQuestion;
      if (arg.hasKeyword()) {
        argName = Optional.of(arg.getKeyword());
        argQuestion = String.format("Please specify a `%s` [%s] value to use for the '%s' aggregation",
            arg.getKeyword(), argType, aggFunction.getId());
      } else {
        argQuestion = String.format("Please specify argument %d [%s] to use for the '%s' aggregation",
          arg.getIndex() + 1, // humans tend to be 1 based (not zero)
          argType,
          aggFunction.getId());
      }

      List<String> argumentAnswers = Lists.newArrayList();
      argumentAnswers.add(cliPrompter.readlineWithTitle(cliPrompter.title(argQuestion)));

      while (allowMany && cliPrompter.askIf("Do you want to specify another value")) {
        argumentAnswers.add(cliPrompter.readlineWithTitle(cliPrompter.title(argQuestion)));
      }

      String argumentAnswer = argumentAnswers.get(0);
      if (allowMany) {
        argumentAnswer = argumentAnswers.stream()
            .collect(Collectors.joining(",", "[", "]"));
      }
      aggFunctionPrototype.setArgument(i, argName, argumentAnswer);
    }

    // now we build up the function call to return in the aggregation function prototype
    FunctionCall aggFunctionCall = aggFunctionPrototype.build();
    return ResultOrProblems.of(new Response(new FunctionCallPrototype(aggFunctionCall), aggFunctionCall.toSource()));
  }

}
