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

import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;

import lombok.Getter;
import nz.org.riskscape.wizard.Question;
import nz.org.riskscape.wizard.bld.IncrementalBuildState;
import nz.org.riskscape.wizard.bld.PipelineChange;
import nz.org.riskscape.wizard.bld.dsl.BasicBuildPoint;
import nz.org.riskscape.wizard.bld.dsl.IncompletePipelineChange;
import nz.org.riskscape.wizard.bld.dsl.PipelineChangeInput;
import nz.org.riskscape.wizard.bld.dsl.PipelineChanger;
import nz.org.riskscape.wizard.bld.dsl.TypedPipelineChanger;

/**
 * Returned from a call to {@link DefaultQuestionSet2#addQuestion(String, Class)} to allow simpler declaration of
 * pipeline building following a question being answered
 */
@Getter
public class AddQuestion<T> {

  private final DefaultQuestionSet2 questionSet;

  private final Class<T> parameterType;
  private Question building;

  public AddQuestion(DefaultQuestionSet2 questionSet, String name, Class<T> parameterType) {
    this.questionSet = questionSet;
    this.building = new Question(name, parameterType).atLocation(questionSet.getDefaultLocation());
    this.parameterType = parameterType;
  }

  public AddQuestion(DefaultQuestionSet2 questionSet, Question q, Class<T> parameterType) {
    this.questionSet = questionSet;
    this.building = q.withType(parameterType).atLocation(questionSet.getDefaultLocation());
    this.parameterType = parameterType;
  }

  /**
   * Finish adding the question to the set by describing the change to make when it is answered.
   * Note this is only suitable for single-value Questions - for multi-value Questions use
   * {@link #thenForEach(BiFunction)}.
   * @return the question set to allow more questions to be added in a fluid style
   */
  public DefaultQuestionSet2 then(TypedPipelineChanger<T> changer) {
    questionSet.add(building);
    questionSet.addBuildPoint(new BasicBuildPoint(
        building.getName(),
        input -> changer.apply(
            new PipelineChangeInput(
                input.getBuildPoint(),
                input.getAnswer(),
                input.getBuildState()
            ),
            input.getResponse(parameterType)
        )
    ));

    return questionSet;
  }

  /**
   * Finish adding the question to the set by describing the change to make when it is answered
   * @return the question set to allow more questions to be added in a fluid style
   */
  public DefaultQuestionSet2 then(PipelineChanger changer) {
    questionSet.add(building);
    questionSet.addBuildPoint(new BasicBuildPoint(
        building.getName(),
        input -> changer.apply(
            new PipelineChangeInput(
                input.getBuildPoint(),
                input.getAnswer(),
                input.getBuildState()
            )
        )
    ));

    return questionSet;
  }

  /**
   * Same as {@link #then(TypedPipelineChanger)} but handles multi-valued Questions.
   * @return the question set to allow more questions to be added in a fluid style
   */
  public DefaultQuestionSet2 thenForEach(BiFunction<PipelineChangeInput, List<T>, IncompletePipelineChange> changer) {
    questionSet.add(building);
    questionSet.addBuildPoint(new BasicBuildPoint(
        building.getName(),
        input -> changer.apply(
            new PipelineChangeInput(
                input.getBuildPoint(),
                input.getAnswer(),
                input.getBuildState()
            ),
            input.getResponses(parameterType)
        )
    ));

    return questionSet;
  }

  /**
   * Allow arbitrary changes to the question by supplying a function that returns a new function, e.g.
   * `customizeQuestion(q -> q.optionalOne())`
   */
  public AddQuestion<T> customizeQuestion(Function<Question, Question> mutator) {
    building = mutator.apply(building);
    if (!building.getParameterType().equals(parameterType)) {
      throw new IllegalStateException("Can not change parameter type");
    }
    return this;
  }

  public AddQuestion<T> dependsOn(String questionNamed) {
    return dependsOn(questionSet.get(questionNamed));
  }

  public AddQuestion<T> dependsOn(Question dependency) {
    return customizeQuestion(q -> q.dependsOn(dependency));
  }

  /**
   * @return the question set to allow more questions to be added in a fluid style
   */
  public DefaultQuestionSet2 thenNoChange() {
    then((input) -> PipelineChange.noChange());
    return questionSet;
  }

  private Object getResponse(String questionName, IncrementalBuildState buildState) {
    return buildState.getAnswerTo(questionSet.getId(), questionName, Object.class);
  }

  public AddQuestion<T> askWhenResponseIs(String questionNamed, Object hasResponse) {
    return askWhenResponseIs(questionSet.get(questionNamed), hasResponse);
  }

  /**
   * Convenience for when a question depends on a previous question having been
   * answered, *and* that response must also have a certain value.
   */
  public AddQuestion<T> askWhenResponseIs(Question dependency, Object hasResponse) {
    return customizeQuestion(q -> q.dependsOn(dependency).askWhen(
        bs -> hasResponse.equals(getResponse(dependency.getName(), bs))
      ));
  }

  public AddQuestion<T> askWhenDependencyIs(Predicate<Object> predicate) {
    return customizeQuestion(q -> q.askWhen(bs ->
      bs.getAnswer(questionSet.getId(), building.getDependsOn().get().getName())
        .map(answer -> predicate.test(answer.getValueAs(Object.class)))
        .orElse(false)
    ));
  }

  /**
   * Only asks this question if the other question was not answered (i.e. skipped or not offered).
   */
  public AddQuestion<T> ifNotAnswered(String questionName) {
    return customizeQuestion(q -> q.askWhen(bs ->
      !bs.isResponseGiven(questionSet.getId(), questionName)
    ));
  }
}
