/*
 * 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 static nz.org.riskscape.wizard.CliPrompter.*;
import static nz.org.riskscape.wizard.ExpressionHelper.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.i18n.MessageFactory;
import nz.org.riskscape.engine.i18n.TranslationContext;
import nz.org.riskscape.engine.types.Enumeration;
import nz.org.riskscape.engine.types.Floating;
import nz.org.riskscape.engine.types.Integer;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Text;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.TokenTypes;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.wizard.Answer;
import nz.org.riskscape.wizard.CliChoice;
import nz.org.riskscape.wizard.CliPrompter;
import nz.org.riskscape.wizard.ExpressionHelper;
import nz.org.riskscape.wizard.ExpressionHelper.AttributeMetadata;
import nz.org.riskscape.wizard.Question;
import nz.org.riskscape.wizard.bld.IncrementalBuildState;

/**
 * {@link Asker} for getting an answer that is a boolean yielding {@link Expression}, such as for a
 * filter condition.
 */
public class BooleanExpressionAsker extends ExpressionAsker {

  public static final int DEFAULT_PAGE_SIZE = 20;

  private static final CliChoice<String> NEXT_PAGE = new CliChoice<>("Show more choices", "m", "NEXT PAGE");
  private static final CliChoice<String> PREV_PAGE = new CliChoice<>("Show previous choices", "p", "PREV PAGE");

  public interface Messages extends MessageFactory {

    String chooseComparison();

    String addAnotherValue();

    String tooManyChoices(int choiceCount);

    String enterValue();

    String chooseValue();

    String byAttributeDisclaimer();
  }

  /**
   * Represents the user choice in how to answer the attribute value part of the question, should there
   * be a lot of potential values in a list.
   */
  public enum ValueEntryMode {
    ENTER_VALUE,
    PAGED_LIST
  }

  /**
   * Comparison operators that are supported by the asker.
   */
  @RequiredArgsConstructor
  public enum Comparison {
    EQUAL("=", false),
    NOT_EQUAL("!=", false),
    LESS_THAN("<", true),
    LESS_THAN_EQUAL("<=", true),
    GREATER_THAN(">", true),
    GREATER_THAN_EQUAL(">=", true);

    @Getter
    private final String operator;

    private final boolean numericOnly;

    boolean applicableTo(boolean numericType) {
      if (numericOnly) {
        return numericType;
      }
      return true;
    }

    boolean isEquality() {
      return this == EQUAL || this == NOT_EQUAL;
    }
  }

  private final int pageSize;

  private final Messages messages;

  public BooleanExpressionAsker(TranslationContext messageSource) {
    this(messageSource, DEFAULT_PAGE_SIZE);
  }

  /**
   * Allows custom pageSize to be applied. Intended for testing purposes only.
   * @param pageSize
   */
  BooleanExpressionAsker(TranslationContext messageSource, int pageSize) {
    super(messageSource, Lists.newArrayList(TAG_EXPRESSION_TYPE_BOOLEAN));
    this.pageSize = pageSize;
    this.messages = messageSource.newFactory(Messages.class);
  }

  @Override
  protected String askInteractively(CliPrompter cliPrompter, ExpressionHelper helper) {
    cliPrompter.println(messages.byAttributeDisclaimer());

    CliChoice<AttributeMetadata> targetAttr = cliPrompter.choose(expressionMessages.chooseAttribute(),
        getAttributeChoices(
            Lists.newArrayList(Text.class, Integer.class, Floating.class, Enumeration.class),
            helper
        )
    );

    boolean numericType = Nullable.unwrap(targetAttr.data.getType()).isNumeric();
    boolean textType = Nullable.unwrap(targetAttr.data.getType()).internalType().equals(String.class);

    List<CliChoice<Comparison>> choices = enumTranslator.getEntries(Comparison.class).stream()
        // Most of our comparisons only work for number types. So we filter them out
        // if the type is not a number
        .filter(e -> e.getValue().applicableTo(numericType))
        .map(e -> new CliChoice<Comparison>(e.getLabelOr(e.getValue().getOperator()), e.getValue()))
        .collect(Collectors.toList());

    Comparison comparison = cliPrompter.choose(messages.chooseComparison(), choices).data;

    // If we are doing an equality comparison then selecting from a list of known choices makes this easy.
    // That is a list of values that is used in the data, or maybe the allowed options from a set or enumeration.
    List<CliChoice<String>> knownChoices;
    if (comparison.isEquality()) {
      knownChoices = getValueChoices(targetAttr.data, helper);
    } else {
      knownChoices = Collections.emptyList();
    }

    List<String> attributeValues = new ArrayList<>();

    // function that will add the answer to the list of collected answers and return
    // true when answers are complete, or false otherwise.
    Function<String, Boolean> attributeAnswerProcessor = (attributeValue) -> {
      attributeValues.add(textType ? TokenTypes.quoteTextIfNeeded(attributeValue) : attributeValue);
      if (!(comparison == Comparison.EQUAL || comparison == Comparison.NOT_EQUAL)) {
        return true;
      }
      boolean addMore = cliPrompter.choose(messages.addAnotherValue(), YES_NO_CHOICES).data;
      return ! addMore;
    };

    if (knownChoices.isEmpty()) {
      // If we do not have any attribute values available we must ask user to enter text
      doTextEntry(cliPrompter, attributeAnswerProcessor);
    } else {
      int valueCount = knownChoices.size();
      if (valueCount <= pageSize) {
        doListEntry(knownChoices, cliPrompter, attributeAnswerProcessor);
      } else {
        // There are lots of choices. We need to ask user how to deal with them
        switch (cliPrompter.choose(
            messages.tooManyChoices(valueCount),
            getChoices(ValueEntryMode.class)).data) {
          case PAGED_LIST:
            doPagedListEntry(knownChoices, cliPrompter, attributeAnswerProcessor);
            break;
          default:
            doTextEntry(cliPrompter, attributeAnswerProcessor);
        }
      }
    }

    // We need to join up all the given answers into a single expression. We do this with 'or' for
    // equals and 'and' for not equals. For other comparisions this is a moot point as only one value
    // will exist, so the joiner doesn't actually get used for those.
    String joiner = " or ";
    if (comparison == Comparison.NOT_EQUAL) {
      joiner = " and ";
    }
    return attributeValues.stream()
        .map(value -> String.format("%s %s %s", targetAttr.data.getFullyQualifiedName(), comparison.getOperator(),
            value))
        .collect(Collectors.joining(joiner));
  }

  private void doTextEntry(CliPrompter cliPrompter, Function<String, Boolean> attributeAnswerProcessor) {
    while (true) {
      if (attributeAnswerProcessor.apply(cliPrompter.readlineWithTitle(messages.enterValue()))) {
        // answers are complete
        break;
      }
    }
  }

  private void doListEntry(List<CliChoice<String>> choices, CliPrompter cliPrompter,
      Function<String, Boolean> attributeAnswerProcessor) {
    while (true) {
      if (attributeAnswerProcessor.apply(cliPrompter.choose(messages.chooseValue(), choices).data)) {
        // answers are complete
        break;
      }
    }

  }

  private void doPagedListEntry(List<CliChoice<String>> choices, CliPrompter cliPrompter,
      Function<String, Boolean> attributeAnswerProcessor) {
    int page = 0;
    while (true) {
      int fromIdx = page * pageSize;
      int toIndex = Math.min(fromIdx + pageSize, choices.size());
      List<CliChoice<String>> choicesPage = Lists.newArrayList(choices.subList(fromIdx, toIndex));
      if (fromIdx > 0) {
        choicesPage.add(PREV_PAGE);
      }
      if (toIndex < choices.size()) {
        choicesPage.add(NEXT_PAGE);
      }
      CliChoice<String> choosen = cliPrompter.choose(messages.chooseValue(), choicesPage);
      if (choosen == NEXT_PAGE) {
        ++page;
      } else if (choosen == PREV_PAGE) {
        --page;
      } else if (attributeAnswerProcessor.apply(choosen.data)) {
        // answers are complete
        break;
      }
    }

  }

  @Override
  public ResultOrProblems<Answer.Response> ask(AskRequest input) {
    CliPrompter prompter = input.getCliPrompter();
    IncrementalBuildState state = input.getBuildState();
    Question question = input.getQuestion();

    ExpressionHelper helper = ExpressionHelper.create(state, question).get();

    prompter.println(prompter.getPrompt(question));

    return Answer.bind(
        state.getBindingContext(),
        question,
        askInteractively(prompter, helper));
  }
}
