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

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

import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;

import com.google.common.collect.Range;

import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.bind.ParameterSet;
import nz.org.riskscape.engine.steps.RelationInputStep;
import nz.org.riskscape.pipeline.ast.PipelineASTMatchers;
import nz.org.riskscape.rl.ExpressionParser;
import nz.org.riskscape.rl.ast.AST;
import nz.org.riskscape.rl.ast.PipelineDeclaration;
import nz.org.riskscape.rl.ast.StepChain;

/**
 * Tests for the DefaultPipelineRealizer's ability to handle InputChain arguments.
 * InputChain represents the `<- step_chain` syntax that allows a pipeline branch.  This test is pretty anaemic
 * - the realizer is only responsibly for plumbing in the ast - nothing else.
 */
public class DefaultPipelineRealizerInputChainTest extends ProjectTest {


  private PipelineDeclaration parsed;
  private RealizedPipeline realized;

  ParameterSet params = ParameterSet.from(Parameter.required("param", StepChain.class));
  Step mockStep = mock(Step.class);
  ArgumentCaptor<RealizationInput> captor = ArgumentCaptor.forClass(RealizationInput.class);
  Step inputStep = new RelationInputStep(engine);

  @Before
  public void setup() {
    when(mockStep.getId()).thenReturn("step");
    // close over params ref so we can change the value per test
    when(mockStep.getParameterSet()).thenAnswer(inv -> params);
    when(mockStep.getInputArity()).thenReturn(Range.closedOpen(0, 1));
    when(mockStep.realize(any())).thenAnswer(inv -> {
      RealizationInput input = inv.getArgument(0);
      return input.getRealizedPipeline();
    });

    engine.getPipelineSteps().add(mockStep);

    engine.getPipelineSteps().add(inputStep);
  }

  @Test
  public void canRealizeStepWithStepChainArgs() throws Exception {
    parseAndRealize("step(<- input())");

    assertRealizedSuccessfully();

    assertParameterHasInputChainSource("param", "<- input()");
  }

  @Test
  public void canRealizeStepWithInputAndStepChainArgs() throws Exception {
    parseAndRealize("input(value: 'foo') -> step(<- input())");

    assertRealizedSuccessfully();

    assertParameterHasInputChainSource("param", "<- input()");

    assertDependencies(hasProperty("implementation", is(inputStep)));
  }

  @Test
  public void canRealizeStepThatRefersToASinglePipelineStep() throws Exception {

    parseAndRealize("""
        input(value: 'foo') as foo_input

        input(value: 'bar') as bar_input
        ->
        step(<- foo_input)
        """);

    assertRealizedSuccessfully();

    // we have the ast parameter
    assertParameterHasInputChainSource("param", "<- foo_input");

    // and both inputs as dependencies
    assertDependencies(
      is(realized.getStep("foo_input").get()),
      is(realized.getStep("bar_input").get())
    );

    // note that the mock step declares max arity of 1 - that's ignored for the purposes of input chain dependencies -
    // it's up to each step to
    assertFalse(mockStep.getInputArity().contains(2));
  }

  @Test
  public void canRealizeStepThatRefersToASinglePipelineStepThatIsDefinedAfter() throws Exception {

    // this is just confirming that the dependency building isn't relying on ast traversal order to work
    parseAndRealize("""
        input(value: 'bar') as bar_input
        ->
        step(<- foo_input)

        # comes after the reference
        input(value: 'foo') as foo_input
        """);

    assertRealizedSuccessfully();

    assertParameterHasInputChainSource("param", "<- foo_input");

    // and both inputs as dependencies
    assertDependencies(
        is(realized.getStep("foo_input").get()),
        is(realized.getStep("bar_input").get())
    );

    // note that the mock step declares max arity of 1 - that's ignored for the purposes of input chain dependencies -
    // it's up to each step to
    assertFalse(mockStep.getInputArity().contains(2));
  }

  @Test
  public void canRealizeStepThatRefersToAndDefinesPipelineSteps() throws Exception {

    parseAndRealize("""
        input(value: 'foo') as foo_input

        input(value: 'bar') as bar_input
        ->
        step(<- foo_input -> group(count(*)))
        """);

    assertRealizedSuccessfully();

    // we have the ast parameter
    assertParameterHasInputChainSource("param", "<- foo_input -> group(count(*))");

    // and both inputs as dependencies
    assertDependencies(
        is(realized.getStep("foo_input").get()),
        is(realized.getStep("bar_input").get())
    );
  }

  @Test
  public void canRealizeStepThatRefersToManyPipelineSteps() throws Exception {
    params = ParameterSet.from(params.get("param"), Parameter.required("other-param", StepChain.class));

    parseAndRealize("""
        input(value: 'foo') as foo_input
        input(value: 'bar') as bar_input

        input(value: 'baz') as baz_input
        ->
        step(
          <- foo_input,
          <- bar_input
        )
        """);

    assertRealizedSuccessfully();

    // we have both ast parameters
    assertParameterHasInputChainSource("param", "<- foo_input");
    assertParameterHasInputChainSource("other-param", "<- bar_input");

    assertDependencies(
        is(realized.getStep("foo_input").get()),
        is(realized.getStep("bar_input").get()),
        is(realized.getStep("baz_input").get())
    );
  }


  @Test
  public void getAnErrorIfAStepDoesNotExist() throws Exception {
    parseAndRealize("""
        step(
          <- missing_step
        )
        """);

    assertThat(realized.getFailures(), contains(
        Matchers.hasAncestorProblem(Matchers.isError(Pipeline.ProblemCodes.STEP_NAME_UNKNOWN))
    ));
  }

  private void parseAndRealize(String pipelineSource) {
    parsed = ExpressionParser.INSTANCE.parsePipeline(pipelineSource);
    realized = executionContext.getPipelineRealizer().realize(executionContext, parsed);
  }

  private void assertRealizedSuccessfully() {
    assertThat(realized.getFailures(), empty());
    verify(mockStep).realize(captor.capture());
  }

  private void assertParameterHasInputChainSource(String paramName, String expectedSource) {
    assertThat(
        (AST) captor.getValue().getParameters().get(paramName).get(0),
        PipelineASTMatchers.hasSource(expectedSource)
    );
  }
  @SafeVarargs
  private void assertDependencies(Matcher<RealizedStep>... matchers) {
    assertThat(
        captor.getValue().getDependencies(),
        containsInAnyOrder(matchers)
    );
  }

}
