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

import nz.org.riskscape.engine.i18n.MessageFactory;
import nz.org.riskscape.engine.i18n.TranslationContext;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.TokenTypes;
import nz.org.riskscape.rl.ast.PropertyAccess;
import nz.org.riskscape.rl.ast.StructDeclaration;
import nz.org.riskscape.wizard.Answer;
import nz.org.riskscape.wizard.Choice;
import nz.org.riskscape.wizard.CliPrompter;
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 {@link StructDeclaration} or
 * {@link PropertyAccess} expression, e.g. something like 'foo as bar'.
 */
public class AttributeAsker extends BaseAsker {

  public interface Messages extends MessageFactory {

    String renameYesNo();

    String enterNewName();
  }

  private final Messages messages;

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

  @Override
  public boolean canAsk(IncrementalBuildState buildState, Question question) {
    // Questions generally use StructDeclaration to mean a single 'foo as bar'
    // attribute, rather than a whole big '{ foo: a, bar: b, ... }' declaration
    return StructDeclaration.class.isAssignableFrom(question.getParameterType())
        || PropertyAccess.class.isAssignableFrom(question.getParameterType());
  }

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

    Choice choice = pickChoice(
            question.getChoices(request.getBuildState()),
            prompter,
            prompter.getPrompt(request.getQuestion())
    );

    Optional<AttributeMetadata> metadata = choice.isA(AttributeMetadata.class);

    String expression;
    String newName;

    // There are times when an attribute doesn't always come from the input scope - it's something the wizard
    // has thrown in there itself (e.g. the 'Total' option in the report's aggregation questions)
    if (metadata.isPresent()) {
      AttributeMetadata targetAttr = metadata.get();
      expression = targetAttr.getFullyQualifiedName();
      newName = targetAttr.getName();
    } else {
      expression = choice.getValue();
      newName = choice.getLabel(translationContext);
    }

    // optionally let the user rename this attribute, if applicable
    boolean hasName = StructDeclaration.class.isAssignableFrom(question.getParameterType());
    if (hasName) {
      if (prompter.choose(messages.renameYesNo(), YES_NO_CHOICES).data) {
        newName = prompter.readlineWithTitle(messages.enterNewName());
      }

      // turn the user's response into a struct declaration expression that we can then bind
      expression = String.format("%s as %s", expression, TokenTypes.quoteIdent(newName));
    }

    return Answer.bind(request.getBuildState().getBindingContext(), question, expression);
  }
}
