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

import static nz.org.riskscape.wizard.AnswerMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;

import org.junit.Test;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import nz.org.riskscape.engine.DefaultEngine;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.bind.ParamProblems;
import nz.org.riskscape.engine.i18n.MessageSource;
import nz.org.riskscape.engine.i18n.MutableMessageSource;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.wizard.bind.CompositeBinder;
import nz.org.riskscape.wizard.bld.IncrementalBuildState;
import nz.org.riskscape.wizard.bld.PipelineChange;
import nz.org.riskscape.wizard.survey2.QuestionTree;

public class ConfigParserSurvey2ReadingTest extends ProjectTest {

  Map<String, BiFunction<IncrementalBuildState, Answer, PipelineChange>> pickledAnswers =
      Maps.newHashMap();

  List<Question> questions = new ArrayList<>();
  Survey survey2 = new Survey() {

    @Override
    public String getId() {
      return "test";
    }

    @Override
    public MessageSource getMessageSource() {
      return new MutableMessageSource();
    }

    @Override
    public QuestionTree getQuestionTree(IncrementalBuildState buildState) {
      return QuestionTree.fromList(questions);
    }

    @Override
    public PipelineChange getPipelineChange(IncrementalBuildState buildState, Answer answer) {
      return pickledAnswers.getOrDefault(
          answer.getQuestion().getId(),
          (i, a) -> PipelineChange.noChange().apply(a)
      ).apply(buildState, answer);
    }

    @Override
    public boolean isFinished(IncrementalBuildState buildState) {
      return false;
    }

    @Override
    public List<QuestionSet> getApplicableQuestionSets(IncrementalBuildState buildState) {
      return Collections.emptyList();
    }

  };

  List<Answer> answers;
  QuestionSet qs = new EmptyQuestionSet("q", survey2);
  Map<String, List<?>> configToLoad = new HashMap<>();
  ResultOrProblems<IncrementalBuildState> loadedConfig;

  @Override
  public DefaultEngine createEngine() {
    DefaultEngine engine = super.createEngine();
    engine.getBinders().add(new CompositeBinder());
    return engine;
  }

  @Test
  public void canReadInASimpleSurveySuccessfully() throws Exception {
    question(new Question("1", String.class));
    question(new Question("2", String.class));
    question(new Question("3", String.class));

    addResponse("q.1", "cool");
    addResponse("q.2", "story");
    addResponse("q.3", "bro");

    read();

    assertThat(
      answers,
      contains(
        answerHasBoundValue("1", equalTo("cool")),
        answerHasBoundValue("2", equalTo("story")),
        answerHasBoundValue("3", equalTo("bro"))
      )
    );
  }

  @Composite @EqualsAndHashCode
  public static class NotTrivial {

    @CompositeField @Getter
    public String someField;

    public String getsIgnored;
  }

  @Test
  public void canReadAMap() throws Exception {
    question(new Question("1", NotTrivial.class));

    addResponse("q.1[some-field]", "cool");

    read();

    assertThat(
      answers,
      contains(
        allOf(
          answerHasOriginalResponse("1", equalTo(ImmutableMap.of("some-field", "cool"))),
          answerHasBoundValue(
            "1",
            Matchers.instanceOfAnd(NotTrivial.class, hasProperty("someField", equalTo("cool")))
          )
        )
      )
    );
  }

  @Test
  public void canReadMultipleResponses() throws Exception {
    question(new Question("1", String.class).optionalMany());

    addResponse("q.1[0]", "cool");
    addResponse("q.1[1]", "story");
    addResponse("q.1[2]", "bro");

    read();

    assertThat(
      answers,
      hasSize(1)
    );

    assertThat(answers.get(0).getOriginalResponses(), contains("cool", "story", "bro"));
  }

  @Test
  public void configCanSkipQuestions() throws Exception {
    question(new Question("1", String.class));
    question(new Question("2", String.class).optionalOne());
    question(new Question("3", String.class));

    addResponse("q.1", "cool");
    addResponse("q.3", "bro");

    read();

    assertThat(
      answers,
      contains(
        answerHasBoundValue("1", equalTo("cool")),
        skippedQuestion("2"),
        answerHasBoundValue("3", equalTo("bro"))
      )
    );
  }

  @Test
  public void anUnskippableQuestionGivesAWarning() throws Exception {
    question(new Question("1", String.class));
    question(new Question("2", String.class));

    addResponse("q.1", "cool");

    read();

    assertThat(
      answers,
      contains(
        answerHasBoundValue("1", equalTo("cool"))
      )
    );

    assertThat(
      loadedConfig.getProblems(),
      contains(
        ConfigParser.PROBLEMS.unfinishedSurvey("q.2")
      )
    );
  }

  @Test
  public void aFailedChangeGivesAnError() throws Exception {
    question(new Question("1", String.class));
    Question q2 = question(new Question("2", String.class));

    addResponse("q.1", "yeah");
    addResponse("q.2", "nah");

    pickledAnswers.put("q.2", (ibs, a) ->
      PipelineChange.failed(Arrays.asList(Problems.foundWith("negativity"))).apply(a)
    );

    read();


    assertThat(
      loadedConfig.getProblems(),
      contains(
        WizardProblems.get().configError().withChildren(
          ConfigParser.PROBLEMS.couldNotApplyChange(q2.toParameter())
          .withChildren(
            Problems.foundWith("negativity")
          )
        )
      )
    );
  }

  @Test
  public void anArityErrorGivesAnError() throws Exception {
    question(new Question("1", String.class));

    addResponse("q.1[0]", "cool");
    addResponse("q.1[1]", "story");
    addResponse("q.1[2]", "bro");

    read();

    assertThat(
      loadedConfig.getProblems(),
      contains(
        WizardProblems.get().configError().withChildren(ParamProblems.get().wrongNumberGiven(
          "q.1",
          Range.singleton(1).toString(),
          3
        ))
      )
    );
  }

  @Test
  public void surplusConfigGivesAWarning() throws Exception {
    question(new Question("1", String.class));
    question(new Question("2", String.class));

    addResponse("q.1", "cool");
    addResponse("q.2", "story");
    addResponse("q.3", "bro");

    read();

    assertThat(
      answers,
      contains(
        answerHasBoundValue("1", equalTo("cool")),
        answerHasBoundValue("2", equalTo("story"))
      )
    );

    assertThat(
      loadedConfig.getProblems(),
      contains(
        ParamProblems.get().ignored("[q.3]")
          .withChildren(ConfigParser.PROBLEMS.ignoredParamsTip())
      )
    );
  }

  @Test
  public void aBindingErrorIsReturned() throws Exception {
    Question q = question(new Question("1", Long.class));

    addResponse("q.1", "twelvety");

    read();

    assertThat(
      loadedConfig.getProblems(),
      contains(
        allOf(
          // I want to match a and b of a -> b -> c, due to crappy old problems in binding code
          Matchers.equalIgnoringChildren(WizardProblems.get().configError()),
          Matchers.hasAncestorProblem(
            Matchers.equalIgnoringChildren(Problems.foundWith(q.toParameter()).withChildren())
          )
        )
      )
    );
  }

  private void read() {
    ConfigParser parser = new ConfigParser(f -> survey2);

    loadedConfig = parser.loadConfig2(survey2, executionContext, configToLoad);

    if (loadedConfig.isPresent()) {
      answers = loadedConfig.getWithProblemsIgnored().getAllAnswers();
      Collections.reverse(answers);
    }
  }

  private void addResponse(String key, String value) {
    configToLoad.put(key, Arrays.asList(value));
  }

  private Question question(Question question) {
    question = question.inSet(qs);

    questions.add(question);

    return question;
  }

}
