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

import static nz.org.riskscape.engine.Assert.*;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import java.util.Collections;

import org.junit.Test;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import nz.org.riskscape.engine.pipeline.RealizedPipeline;
import nz.org.riskscape.engine.pipeline.RealizedStep;
import nz.org.riskscape.engine.pipeline.SinkConstructor;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.rl.ast.PipelineDeclaration;
import nz.org.riskscape.wizard.Answer;
import nz.org.riskscape.wizard.TestQuestionSet;
import nz.org.riskscape.wizard.Question;
import nz.org.riskscape.wizard.Survey;
import nz.org.riskscape.wizard.bld.IncrementalBuildState.Context;
import nz.org.riskscape.wizard.bld.change.NoChange;

public class IncrementalBuildStateTest {

  private Context context = mock(Context.class);

  private IncrementalBuildState lastState = IncrementalBuildState.empty(context);

  private PipelineChange createdBy = mock(PipelineChange.class);



  @Test
  public void getRealizedStepReturnsLastStep() {
    RealizedStep last = mock(RealizedStep.class);
    when(last.getStepType()).thenAnswer(i -> Relation.class);

    IncrementalBuildState state = init(last);

    assertThat(state.getRealizedStep(), is(last));
  }

  @Test
  public void getRealizedStepIgnoresSinkStepsWhenAnotherIsPresent() {
    RealizedStep last = mock(RealizedStep.class);
    when(last.getStepType()).thenAnswer(i -> Relation.class);

    IncrementalBuildState state = init(sink(null), last);

    assertThat(state.getRealizedStep(), is(last));
  }

  @Test
  public void getRealizedStepReturnsSinksDependencyIfSameForAllSinks() {
    RealizedStep sinkSource = mock(RealizedStep.class);
    when(sinkSource.getStepType()).thenAnswer(i -> Relation.class);

    IncrementalBuildState state = init(sink(sinkSource), sink(sinkSource));

    assertThat(state.getRealizedStep(), is(sinkSource));
  }

  @Test
  public void getRealizedStepExceptionIfManyEndSteps() {
    RealizedStep sinkSource = mock(RealizedStep.class);
    when(sinkSource.getStepType()).thenAnswer(i -> Relation.class);

    IncrementalBuildState state = init(inputStep(), inputStep());

    assertThrows(IllegalStateException.class, () -> state.getRealizedStep());
  }

  @Test
  public void getRealizedStepExceptionWhenSinkEndStepsDoNotHaveSameDependency() {
    RealizedStep sinkSource = mock(RealizedStep.class);
    when(sinkSource.getStepType()).thenAnswer(i -> Relation.class);

    IncrementalBuildState state = init(sink(inputStep()), sink(inputStep()));

    assertThrows(IllegalStateException.class, () -> state.getRealizedStep());
  }

  //
  //
  // Answer testing methods
  //
  //

  TestQuestionSet questionSet = new TestQuestionSet("qs", Survey.EMPTY_SURVEY);
  Question fooQuestion = questionSet.add(new Question("foo", String.class)).optionalOne();
  Question barQuestion = questionSet.add(new Question("bar", String.class)).optionalOne();

  Question hiddenQuestion1 = questionSet.add(new Question("hidden1", String.class)).hidden();
  Question hiddenQuestion2 = questionSet.add(new Question("hidden2", String.class)).hidden();

  @Test
  public void wasAskedReturnsTrueWhenAnswered() throws Exception {
    assertFalse(lastState.wasAsked("qs", "foo"));
    lastState = new NoChange(Answer.strings(fooQuestion, "bar")).make(lastState).get();
    assertTrue(lastState.wasAsked("qs", "foo"));
    assertFalse(lastState.wasAsked("qs", "bar"));
  }

  @Test
  public void wasAskedReturnsTrueEvenWhenSkipped() throws Exception {
    assertFalse(lastState.wasAsked("qs", "foo"));
    lastState = NoChange.skip(lastState, Collections.singletonList(fooQuestion));
    assertTrue(lastState.wasAsked("qs", "foo"));
    assertFalse(lastState.wasAsked("qs", "bar"));
  }

  @Test
  public void isResponseGivenReturnsTrueWhenAnswered() throws Exception {
    assertFalse(lastState.isResponseGiven("qs", "foo"));
    lastState = new NoChange(Answer.strings(fooQuestion, "bar")).make(lastState).get();
    assertTrue(lastState.isResponseGiven("qs", "foo"));
    assertFalse(lastState.isResponseGiven("qs", "bar"));
  }

  @Test
  public void isResponseGivenReturnsFalseWhenSkipped() throws Exception {
    assertFalse(lastState.isResponseGiven("qs", "foo"));

    lastState = NoChange.skip(lastState, Collections.singletonList(fooQuestion));
    assertFalse(lastState.isResponseGiven("qs", "foo"));
    assertFalse(lastState.isResponseGiven("qs", "bar"));
  }

  @Test
  public void ifResponseGivenReturnsTrueWhenAnswered() throws Exception {
    assertFalse(lastState.ifResponseGiven("qs", "foo", String.class, x -> fail("callback should not be invoked")));
    lastState = new NoChange(Answer.strings(fooQuestion, "bar")).make(lastState).get();
    Question mockQuestion = mock(Question.class);
    assertTrue(lastState.ifResponseGiven("qs", "foo", String.class, x -> mockQuestion.getId()));
    verify(mockQuestion, times(1)).getId();
    assertFalse(lastState.ifResponseGiven("qs", "bar", String.class, x -> fail("callback should not be invoked")));
  }

  @Test
  public void ifResponseGivenReturnsFalseWhenSkipped() throws Exception {
    assertFalse(lastState.ifResponseGiven("qs", "foo", String.class, x -> fail("callback should not be invoked")));

    lastState = NoChange.skip(lastState, Collections.singletonList(fooQuestion));
    assertFalse(lastState.ifResponseGiven("qs", "foo", String.class, x -> fail("callback should not be invoked")));
    assertFalse(lastState.ifResponseGiven("qs", "bar", String.class, x -> fail("callback should not be invoked")));
  }

  @Test
  public void isQuestionSetAnsweredReturnsTrueWhenAnyQuestionInThatSetAreAnswered() throws Exception {
    assertFalse(lastState.isQuestionSetAnswered("qs"));
    assertFalse(lastState.isQuestionSetAnswered("bar"));

    lastState = NoChange.skip(lastState, Collections.singletonList(fooQuestion));

    assertTrue(lastState.isQuestionSetAnswered("qs"));
    assertFalse(lastState.isQuestionSetAnswered("bar"));

    TestQuestionSet barSet = new TestQuestionSet("bar", Survey.EMPTY_SURVEY);
    Question otherQuestion = barSet.add(new Question("barq", String.class));
    lastState = new NoChange(Answer.strings(otherQuestion, "bar")).make(lastState).get();

    // both question sets have been 'considered'
    assertTrue(lastState.isQuestionSetAnswered("qs"));
    assertTrue(lastState.isQuestionSetAnswered("bar"));
  }

  RealizedStep sink(RealizedStep source) {
    RealizedStep sink = mock(RealizedStep.class);
    when(sink.getStepType()).thenAnswer(i -> SinkConstructor.class);
    when(sink.getDependencies()).thenReturn(Lists.newArrayList(source));
    return sink;
  }

  RealizedStep inputStep() {
    RealizedStep inputStep = mock(RealizedStep.class);
    when(inputStep.getStepType()).thenAnswer(i -> Relation.class);
    return inputStep;
  }

  IncrementalBuildState init(RealizedStep... endSteps) {
    RealizedPipeline pipeline = mock(RealizedPipeline.class);
    when(pipeline.getEndSteps()).thenReturn(Sets.newHashSet(endSteps));

    return new IncrementalBuildState(context, lastState, createdBy, PipelineDeclaration.EMPTY, pipeline);
  }

}
