/*
 * 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 static org.mockito.Mockito.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.function.Predicate;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.junit.Before;
import org.junit.Test;

import nz.org.riskscape.engine.pipeline.ExecutionContext;
import nz.org.riskscape.wizard.Answer;
import nz.org.riskscape.wizard.TestQuestionSet;
import nz.org.riskscape.wizard.Question;
import nz.org.riskscape.wizard.QuestionSet;
import nz.org.riskscape.wizard.Survey;
import nz.org.riskscape.wizard.bld.IncrementalBuildState;
import nz.org.riskscape.wizard.bld.change.NoChange;

public class QuestionTreeTest {

  Survey survey = mock(Survey.class);
  ExecutionContext context = mock(ExecutionContext.class);
  IncrementalBuildState buildState;
  QuestionSet set = new TestQuestionSet("qs", survey);
  QuestionSet others = new TestQuestionSet("qs2", survey);
  QuestionTree tree;

  @Before
  public void resetState() {
    buildState = IncrementalBuildState.empty(new IncrementalBuildState.Context(survey, context));
  }

  @Test
  public void testAnEmptyOne() {
    tree = QuestionTree.fromList(Collections.emptyList());
    assertNext();

    // a question from elsewhere doesn't upset it
    answer(q("foo").inSet(others), "yay");

    assertNext();
  }
  @Test
  public void testASingleQuestion() throws Exception {
    tree = QuestionTree.fromList(Arrays.asList(
      q("foo")
    ));

    assertNext("foo");
    answer("foo");
    assertNext();
  }

  @Test
  public void testAListOfIndependentQuestions() throws Exception {
    tree = QuestionTree.fromList(Arrays.asList(
      q("foo"),
      q("bar"),
      q("baz")
    ));

    // while we are here, check the skipping works OK
    assertThat(tree.getSkipped(buildState, q("foo")), empty());
    assertThat(tree.getSkipped(buildState, q("bar")), contains(q("foo")));
    assertThat(tree.getSkipped(buildState, q("baz")), contains(q("foo"), q("bar")));

    // move through them linearly
    assertNext("foo", "bar", "baz");

    answer("foo");
    assertNext("bar", "baz");

    answer("bar");
    assertNext("baz");

    answer("baz");
    assertNext();
  }

  @Test
  public void testAListOfDependentQuestions() throws Exception {
    Question foo = q("foo");
    Question bar = q("bar").dependsOn(foo);
    tree = QuestionTree.fromList(Arrays.asList(
      foo,
      bar,
      q("baz").dependsOn(bar)
    ));

    assertNext("foo");

    answer("foo");
    assertNext("bar");

    answer("bar");
    assertNext("baz");

    answer("baz");
    assertNext();
  }

  @Test
  public void testAListOfDependentQuestionsWithPreconditions() throws Exception {
    Question foo = q("foo");
    Question bar = q("bar").dependsOn(foo)
        .askWhen(ibs -> ibs.getResponse("qs", "foo", String.class).get().equals("true"));
    tree = QuestionTree.fromList(Arrays.asList(
      foo,
      bar,
      q("baz").dependsOn(bar)
    ));

    assertNext("foo");

    answer("foo", "true");
    assertNext("bar");

    answer("bar");
    assertNext("baz");

    answer("baz");
    assertNext();

    resetState();

    assertNext("foo");

    answer("foo", "false");
    assertNext();
  }

  @Test
  public void testAMixOfDependentAndIndependentQuestions() throws Exception {
    Question foo = q("foo");
    Question bar = q("bar");
    Question baz = q("baz");

    tree = QuestionTree.fromList(Arrays.asList(
      foo,
      q("foo-1").dependsOn(foo).askWhen(was("foo", "cool")),
      q("foo-2").dependsOn(foo),
      bar,
      q("baz"),
      q("baz-1").dependsOn(baz)
    ));

    assertNext("foo", "bar", "baz");

    // answer to foo means that foo-1 isn't applicable
    answer("foo");
    assertNext("foo-2");

    answer("foo-2");
    assertNext("bar", "baz");

    answer("bar");
    assertNext("baz");

    answer("baz");
    assertNext("baz-1");

    answer("baz-1");
    assertNext();
  }

  private Predicate<IncrementalBuildState> was(String questionName, String answer) {
    return ibs -> ibs.getResponse("qs", questionName, String.class).get().equals(answer);
  }

  private void assertNext(String... names) {

    if (names.length == 0) {
      assertThat(
        tree.getNextQuestions(buildState),
        empty()
      );
    } else {

      @SuppressWarnings("unchecked")
      Matcher<Question>[] matchers = Arrays.asList(names).stream().map(str -> named(str)).toArray(Matcher[]::new);

      assertThat(
        tree.getNextQuestions(buildState),
        contains(matchers)
      );
    }
  }

  private Matcher<Question> named(String questionName) {
    return new TypeSafeDiagnosingMatcher<Question>(Question.class) {

      @Override
      public void describeTo(Description arg0) {
        arg0.appendText("question named ").appendText(questionName);
      }

      @Override
      protected boolean matchesSafely(Question arg0, Description arg1) {
        arg1.appendText("question named ").appendText(arg0.getName());
        return arg0.getName().equals(questionName);
      }
    };
  }

  private void answer(String questionName) {
    answer(questionName, questionName);
  }

  private void answer(String questionName, Object with) {
    Question q = tree.findOne(node -> node.getQuestion().getName().equals(questionName)).get().getQuestion();
    answer(q, with);
  }

  private void answer(Question question, Object with) {
    buildState = new NoChange(Answer.single(question, with, with)).make(buildState).get();
  }

  private Question q(String name) {
    return new Question(name, String.class).inSet(set);
  }

}
