/*
 * 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 static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.junit.Before;

import nz.org.riskscape.config.Config;
import nz.org.riskscape.engine.DefaultEngine;
import nz.org.riskscape.engine.DefaultProject;
import nz.org.riskscape.engine.PluginProjectTest;
import nz.org.riskscape.engine.core.EnginePlugin;
import nz.org.riskscape.engine.defaults.Plugin;
import nz.org.riskscape.engine.plugin.BuiltInPluginDescriptor;
import nz.org.riskscape.engine.spi.EngineBootstrapper;
import nz.org.riskscape.wizard.Answer;
import nz.org.riskscape.wizard.Answer.Response;
import nz.org.riskscape.wizard.Question;
import nz.org.riskscape.wizard.bld.IncrementalBuildState;

public abstract class BaseSurvey2Test extends PluginProjectTest {

  protected IncrementalBuildState buildState;

  protected Plugin plugin;

  protected BaseSurvey survey;

  public Plugin getPlugin() {
    if (plugin == null) {
      plugin = BuiltInPluginDescriptor.testPlugin(Plugin.class);
    }
    return plugin;
  }

  @Override
  public List<nz.org.riskscape.engine.plugin.Plugin> getPlugins() {
    return Arrays.asList(
      new EnginePlugin(EnginePlugin.DESCRIPTOR),
      getPlugin()
    );
  }

  @Before
  public void setupSurveyFixtures() {
    survey = createSurvey();
    buildState = IncrementalBuildState.empty(new IncrementalBuildState.Context(survey, executionContext));
  }

  @Override
  protected void populateEngineWithDefaults(DefaultEngine newEngine) {
    EngineBootstrapper.bootstrap(extensionPoints, newEngine);

    plugin.initializeEngine(newEngine);
  }

  @Override
  public void addDefaultTypesToRegistry() throws Exception {
    // suppress adding of base types
  }


  @Override
  protected DefaultProject createProject() {
    DefaultProject newProject = new DefaultProject(engine, Config.EMPTY);

    plugin.initializeProject(newProject, engine);
    plugin.addFunctions(newProject, (p) -> System.err.println(p));
    return newProject;
  }



  protected abstract BaseSurvey createSurvey();

  protected void addInitialPipeline() {
    assertFalse(survey.isFinished(buildState));
    // skip our start phase that adds the initial pipeline DSL
    answer("question-choice-1", "start");
    skip("start");
  }

  protected void selectQuestionSet(String qsId) {
    if (buildState.isEmpty()) {
      addInitialPipeline();
      answer("question-choice-2", qsId);
    } else {
      // NB maybe we should centralize this?
      long counter = buildState.buildStateStream()
          .filter(ibs -> ibs.getQuestion().getParameterType().equals(PickQuestionSet.class))
          .count();
      answer("question-choice-" + (counter + 1), qsId);
    }
  }

  public void assertQuestionSetNotOffered() {
    // skip over our start phase that populates the pipeline
    answer("question-choice-1", "start");
    skip("start");

    // check there are no more question-sets to choose from
    assertThat(survey.getQuestionTree(buildState).getNextQuestions(buildState), empty());
  }

  public void assertNoMoreQuestions() {
    assertThat(survey.getQuestionTree(buildState).getNextQuestions(buildState), empty());
    assertTrue(survey.isFinished(buildState));
  }


  public void assertSuccessful() {
    if (!buildState.getRealizedPipeline().getFailures().isEmpty()) {
      fail(render(buildState.getRealizedPipeline().getFailures()));
    }
  }

  public Question pick(String questionName) {
    QuestionTree tree = survey.getQuestionTree(buildState);
    List<Question> nextQuestions = tree.getNextQuestions(buildState);
    Question picked = nextQuestions.stream().filter(q -> q.getName().equals(questionName)).findAny()
        .orElseThrow(() -> new AssertionError("no question named " + questionName + " among " + nextQuestions));

    if (picked.isRequired() && !PickQuestionSet.class.isAssignableFrom(picked.getParameterType())) {
      assertFalse(survey.isFinished(buildState));
    }

    // skip any questions that were before the one picked
    for (Question toSkip : tree.getSkipped(buildState, picked)) {
      buildState = survey.skip(buildState, toSkip).make(buildState).get();
    }
    return picked;
  }

  public void skip(String questionName) {
    Question picked = pick(questionName);
    buildState = survey.skip(buildState, picked).make(buildState).get();
    assertSuccessful(); // Check that skipping didn't result in anything bad - useful when debugging tests
  }

  // returns the underlying choices in the format/class you expect
  public <T> List<T> choices(String questionName, Class<T> expectedClass) {
    return pick(questionName).getChoices(buildState).stream()
        .map(choice -> choice.getDerivedFrom(expectedClass))
        .collect(Collectors.toList());
  }

  public void answer(String questionName, Object responseValue) {
    answer(pick(questionName), responseValue);
  }

  public void answer(Question picked, Object responseValue) {
    // stop accepting answer after failures
    assertSuccessful();

    Answer answer;
    if (picked.getParameterType().equals(PickQuestionSet.class)) {
      // special case for question sets
      answer = Answer.single(picked, new PickQuestionSet(responseValue.toString()), responseValue);
    } else {
      assertTrue(picked.isSingleValueQuestion());
      answer = Answer.single(picked, responseValue, responseValue);
    }

    buildState = survey
        .getPipelineChange(buildState, answer)
        .make(buildState)
        .get();
  }

  public void answers(String questionName, Object... responseValues) {
    assertSuccessful();
    Question picked = pick(questionName);
    assertFalse(picked.isSingleValueQuestion());
    List<Response> responses = new ArrayList<>();

    for (Object value : responseValues) {
      responses.add(Answer.bind(bindingContext, picked, value).get());
    }
    Answer answer = new Answer(picked, responses);
    buildState = survey.getPipelineChange(buildState, answer).make(buildState).get();
  }
}
