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

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;

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

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.bind.ParamProblems;
import nz.org.riskscape.engine.cli.ExitException;
import nz.org.riskscape.engine.test.EngineTestPlugins;

@EngineTestPlugins({ "defaults", "beta" })
public class SubpipelineTest extends BaseModelRunCommandTest {

  @Test
  public void canRunModelWithRepeatedSubpipelines() throws Exception {
    runCommand.modelId = "repeated-subpipeline";
    runCommand.run();

    List<List<String>> results = openCsv("grouped-by-region.csv", "region", "count", "min_elevation", "max_elevation");
    assertThat(results, hasItem(
        Arrays.asList("Otago", "616", "0", "2058")
    ));

    results = openCsv("grouped-by-all.csv", "region", "count", "min_elevation", "max_elevation");
    assertThat(results, hasItem(
        Arrays.asList("all", "5768", "0", "2516")
    ));
  }

  @Test
  public void canRunModelWithNestedSubpipelines() throws Exception {
    runCommand.modelId = "sub-nested";
    runCommand.parameters = Lists.newArrayList("sub='subpipelines/nested2-pipeline.txt'");
    runCommand.run();

    List<List<String>> results = openCsv("subpipeline.csv", "foo", "nested1", "nested2");
    assertThat(results, hasItem(
        Arrays.asList("[1, 2, 3, 4]", "one", "two")
    ));
  }

  @Test
  public void recursionIsDetected() throws Exception {
    runCommand.modelId = "recursive";
    assertThat(assertFails(), contains(
        containsString("Failed to validate model for execution"),
        containsString("- Failed to validate `subpipeline` step on line 3 for execution"),
        allOf(
            containsString("- Failed to realize child pipeline from"),
            containsString("subpipelines/recursive-pipeline.txt")
        ),
        containsString("- Failed to validate `subpipeline` step (out) on line 6 for execution"),
        allOf(
            containsString("- Problems found with"),
            containsString("subpipelines/recursive-pipeline.txt")
        ),
        allOf(
            containsString("- Sub-pipeline recursion has been detected at"),
            containsString("subpipelines/recursive-pipeline.txt. A sub-pipeline can not include itself, "
                + "either directly, or as a sub-pipeline.")
        )
    ));
  }

  @Test
  public void badSubpipelineWillNotRealize() throws Exception {
    runCommand.modelId = "sub";
    runCommand.parameters = Lists.newArrayList("sub='subpipelines/will-not-realize.txt'");
    assertThat(assertFails(), contains(
        containsString("Failed to validate model for execution"),
        containsString("- Failed to validate `subpipeline` step on line 2 for execution"),
        allOf(
            containsString("- Failed to realize child pipeline from"),
            containsString("subpipelines/will-not-realize.txt")
        ),
        containsString("- Failed to validate `input` step on line 2 for execution"),
        containsString("- No such parameter argument 'foo' exists on step id 'input'")
    ));
  }

  @Test
  public void badSubpipelineSyntax() throws Exception {
    runCommand.modelId = "sub";
    runCommand.parameters = Lists.newArrayList("sub='subpipelines/bad-syntax.txt'");
    assertThat(assertFails(), contains(
        containsString("Failed to validate model for execution"),
        containsString("- Failed to validate `subpipeline` step on line 2 for execution"),
        allOf(
            containsString("- Problems found with"),
            containsString("subpipelines/bad-syntax.txt")
        ),
        containsString("- Got EOF before string was terminated at position 43")
    ));
  }

  @Test
  public void failsWhenParametersMissing() throws Exception {
    runCommand.modelId = "sub";
    runCommand.parameters = Lists.newArrayList("sub='subpipelines/filter.txt'");
    assertThat(assertFails(), contains(
        containsString("Failed to validate model for execution"),
        containsString("- Failed to validate `subpipeline` step on line 2 for execution"),
        allOf(
            containsString("- Problems found with"),
            containsString("subpipelines/filter.txt")
        ),
        containsString("- Parameter(s) [filter] required by sub-pipeline"),
        containsString("- '$filter' first declared on line 2, column 11")
    ));
  }

  @Test
  public void surplusParametersAreWarned() throws Exception {
    runCommand.modelId = "sub";
    runCommand.parameters = Lists.newArrayList("sub='subpipelines/nested2-pipeline.txt'");
    runCommand.run();

    // model runs normally and produces output
    List<List<String>> results = openCsv("subpipeline.csv", "foo", "nested2");
    assertThat(results, hasItem(
        Arrays.asList("[1, 2, 3, 4]", "two")
    ));

    assertThat(collectedSinkProblems, contains(
        Matchers.hasAncestorProblem(is(ParamProblems.get().ignored("p1")))
    ));
  }

  private List<String> assertFails() {
    ExitException ex = assertThrows(ExitException.class, () -> runCommand.run());
    return Lists.newArrayList(
        render(ex.getProblem()).split("\n")
    );
  }

}
