/*
 * 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.Locale;
import java.util.Optional;

import lombok.extern.slf4j.Slf4j;
import nz.org.riskscape.engine.i18n.EnumTranslator;
import nz.org.riskscape.engine.i18n.EnumTranslator.EnumEntry;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.engine.i18n.MessageSource;
import nz.org.riskscape.engine.i18n.TranslationContext;
import nz.org.riskscape.picocli.CommandLine.Help.Ansi.Text;
import nz.org.riskscape.wizard.Answer;
import nz.org.riskscape.wizard.Choice;
import nz.org.riskscape.wizard.CliChoice;
import nz.org.riskscape.wizard.CliPrompter;

/**
 * Base implementation of an Asker that cuts down on boiler plate and also binds the user's input (for validation
 * purposes) before returning the unbound value back to the survey (to make sure that it will bind and the UI isn't
 * doing some magic it's not allowed to - keep in mind that while this UI is part of the same process as the riskscape
 * engine, the wizard has been built so that it can work with a future web UI without huge amounts of re-work)
 */
@Slf4j
public abstract class BaseAsker implements Asker {

  protected final TranslationContext translationContext;

  protected final EnumTranslator enumTranslator;

  public BaseAsker(TranslationContext context) {
    this.translationContext = context;
    this.enumTranslator = new EnumTranslator(context);
  }
  /**
   * @return a list of (translated) {@link CliChoice}s for a given enum, that the user can pick between
   */
  protected <T extends Enum<?>> List<CliChoice<T>> getChoices(Class<T> enumClass) {
    return enumTranslator.getEntries(enumClass).stream()
        .map(e -> toChoice(e))
        .toList();
  }

  /**
   * Allows individual Askers to potentially override how enums get displayed to the user
   */
  protected <T extends Enum<?>> CliChoice<T> toChoice(EnumEntry<T> entry) {
    return new CliChoice<>(entry.getLabel(), entry.getValue());
  }

  protected String getMessage(String suffix, Object... args) {
    return getOptionalMessage(suffix, args).orElseGet(() -> {
      log.warn("Failed i18n lookup for class {} and suffix {}", getClass(), suffix);
      return "???" + getClass().getName() + "." + suffix + "???";
    });
  }

  /**
   * Search for a message for this class, conventionally by prepending the class's name to the code, searching through
   * the class hierarchy as well as looking for short class names as well as long names.
   *
   * Searches through wizard resources only (for now - we may fall back to help text for enums for example?)
   *
   * For example, a class com.Foo than extends org.Bar would search for messages under 'com.Foo', 'Foo', 'org.Bar', and
   * then 'Bar'.
   *
   * @param suffix a message key to append to the class derived part of the code
   * @param args args to interpolate in to the message
   * @return a message, or empty if none could be found
   */
  protected Optional<String> getOptionalMessage(String suffix, Object... args) {
    Class<?> ptr = getClass();
    while (!ptr.equals(Object.class)) {
      String code = ptr.getCanonicalName() + "." + suffix;
      String resolved = translationContext.getMessage(code, args);

      if (resolved != null) {
        return Optional.of(resolved);
      }

      code = ptr.getSimpleName() + "." + suffix;
      resolved = translationContext.getMessage(code, args);

      if (resolved != null) {
        return Optional.of(resolved);
      }

      ptr = ptr.getSuperclass();
    }

    return Optional.empty();
  }

  /**
   * Get a bound value from the user - note that the response's original input is returned from
   * {@link #askUnbound(AskRequest)}.  This is partly here because the original API exposed this method on the
   * interface, and keeping this method here keeps the refactoring/change noise down to a minimum while allowing the
   * interface to change in the way we want to preserve the right amount of encapsulation
   */
  public abstract ResultOrProblems<Answer.Response> ask(AskRequest input);

  @Override
  public ResultOrProblems<Object> askUnbound(AskRequest input) {
    return ask(input).map(r -> r.getOriginalInput());
  }

  protected Locale getLocale() {
    return translationContext.getLocale();
  }

  protected MessageSource getMessageSource() {
    return translationContext.getMessageSource();
  }

  public Choice pickChoice(List<Choice> choices, CliPrompter prompter, Text prompt) {
    // convert from the new-style Choice to old-style CliChoice that the prompter is used to
    CliChoice<Choice> chosen = prompter.choose(
        prompt,
        choices.stream()
          .map(c -> toChoice(c))
          .toList()
    );
    return chosen.data;
  }

  private CliChoice<Choice> toChoice(Choice choice) {
    return new CliChoice<Choice>(choice.getLabel(translationContext), choice)
        .subtitled(choice.getDescription(translationContext));
  }
}
