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

import com.google.common.collect.ImmutableList;

import lombok.Getter;
import lombok.Setter;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.wizard.Answer;
import nz.org.riskscape.wizard.BaseQuestionSet;
import nz.org.riskscape.wizard.Question;
import nz.org.riskscape.wizard.Question.Hidden;
import nz.org.riskscape.wizard.QuestionSet;
import nz.org.riskscape.wizard.bld.IncrementalBuildState;
import nz.org.riskscape.wizard.bld.PipelineChange;
import nz.org.riskscape.wizard.bld.change.NoChange;
import nz.org.riskscape.wizard.bld.dsl.BuildPoint;
import nz.org.riskscape.wizard.bld.loc.ChangeLocation;

/**
 * A {@link QuestionSet} that work on a static list of {@link Question}s and {@link BuildPoint}s to satisfy the
 * API contract
 */
public class DefaultQuestionSet2 extends BaseQuestionSet {

  @Getter
  private final Phase phase;

  public DefaultQuestionSet2(String id, Phase phase) {
    super(id, phase.getSurvey());
    this.phase = phase;
  }

  public DefaultQuestionSet2(String name, String discriminator, Phase phase) {
    super(name, discriminator, phase.getSurvey());
    this.phase = phase;
  }

  private final List<Question> list = new ArrayList<>();
  @Getter
  private final List<BuildPoint> buildPoints = new ArrayList<>();

  /**
   * A default location that gets assigned to Questions added via the `addQuestion` method when they are added to this
   * set.  Defaults to the same thing as Question defaults to
   */
  @Getter @Setter
  private ChangeLocation defaultLocation = new Question("", Void.class).getChangeLocation();

  /**
   * Adds a potential build point to the question set, i.e. if certain conditions are met then apply a
   * given pipeline change.
   */
  public void addBuildPoint(BuildPoint point) {
    this.buildPoints.add(point);
  }

  /**
   * Start adding a question to this question set.  Note that {@link AddQuestion}.then must be called to actually add
   * it
   * @param name the name of the question
   * @param parameterType the type of the response wanted for this question
   */
  public <T> AddQuestion<T> addQuestion(String name, Class<T> parameterType) {
    return new AddQuestion<>(this, name, parameterType);
  }

  /**
   * Adds a hidden question ({@link Question#hidden()}) to the set
   */
  public AddQuestion<Hidden> addHiddenQuestion(String name) {
    return new AddQuestion<>(this, new Question(name, Hidden.class).hidden(), Question.Hidden.class);
  }

  Question add(Question question) {
    question = question.inSet(this);
    list.add(question);
    return question;
  }

  public Question get(String questionName) {
    for (Question question : list) {
      if (question.getName().equals(questionName)) {
        return question;
      }
    }
    throw new IllegalArgumentException("no such question: " + questionName);
  }

  public boolean remove(Question question) {
    return list.remove(question);
  }

  public boolean contains(Question question) {
    return list.contains(question);
  }

  /**
   * Returns Parameters that represent this set of questions. Note that this is the full set of Questions
   * (i.e. it doesn't exclude any mutually exclusive questions).
   */
  public List<Parameter> getParameters() {
    return list.stream()
        .map(question -> question.toParameter())
        .collect(Collectors.toList());
  }

  @Override
  public List<Question> getQuestions() {
    return ImmutableList.copyOf(list);
  }

  @Override
  public PipelineChange getPipelineChange(IncrementalBuildState buildState, Answer answer) {
    for (BuildPoint buildPoint : buildPoints) {
      // TODO allow multiple to apply?  or validate that many didn't apply?
      Optional<PipelineChange> change = buildPoint.getChange(buildState, answer);

      if (change.isPresent()) {
        return change.get();
      }
    }

    return new NoChange(answer);
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("QuestionSet[");
    builder.append("id=").append(id);
    builder.append(" questions=");
    boolean first = true;
    for (Question question : list) {
      if (!first) {
        builder.append(", ");
      }
      builder.append(question.getName());
      first = false;
    }
    builder.append("]");
    return builder.toString();
  }
}
