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

import static org.junit.Assert.*;

import org.hamcrest.Matchers;
import org.junit.Test;

import nz.org.riskscape.dsl.SourceLocation;
import nz.org.riskscape.engine.pipeline.PipelineProblems;
import nz.org.riskscape.rl.ast.PipelineDeclaration;
import nz.org.riskscape.rl.ast.StepDeclaration;
import nz.org.riskscape.rl.ast.StepLink;
import nz.org.riskscape.rl.ExpressionParser;

public class PipelineParserCycleDetectionTest {

  public static final StepNamingPolicy NAMING_POLICY = a -> sd -> sd.getName().orElse(sd.getIdent());

  @Test
  public void test() {
    // simplest possible
    assertCycleDetected("foo() -> foo", "foo() -> foo", 6, "foo", 0);

    // ref can proceed decl
    assertCycleDetected("foo -> foo()", "foo -> foo()", 4, "foo()", 0);

    // simplest possible, but aliased
    assertCycleDetected("foo() as bar -> bar", "foo() as bar -> bar", 13, "bar", 0);

    // one bit of indirection
    assertCycleDetected("foo() -> bar() -> foo", "bar() -> foo", 15, "foo", 0);

    // one bit of indirection, across two lines
    assertCycleDetected("foo()\n-> bar() -> foo", "bar() -> foo", new SourceLocation(15, 2, 10), "foo",
        SourceLocation.index(0));

    // one bit of indirection, across many lines - note that we use the line that the chain token is on
    assertCycleDetected("foo()\n-> bar()\n -> \nfoo", "bar() -> foo", new SourceLocation(16, 3, 2), "foo",
        SourceLocation.index(0));

    // cycle declared in different branch
    assertCycleDetected("foo() -> bar() -> baz()\nbar -> foo", "bar -> foo", new SourceLocation(28, 2, 5), "foo",
        SourceLocation.index(0));

    // cycle is not on the step
    assertCycleDetected("foo() \n -> bar \n -> baz() \n  -> \n bar()", "baz() -> bar()", new SourceLocation(29, 4, 3),
        "bar()", new SourceLocation(11, 2, 5));

    // convoluted example - note that the algorithm follows the branch to the end, so sees the line7 use of bar before
    // the cycle on line 6
    assertCycleDetected(
        "foo()\n"
        + "bar()\n"
        + "baz()\n"
        + "foo -> bar -> baz\n"
        + "foo -> cool -> story\n"
        + "story -> bar\n"
        + "cool -> bar",
        "story -> bar", new SourceLocation(63, 6, 7), "bar", new SourceLocation(78, 7, 9));

    // this is not a cycle, it's a fan out and in
    refuteCycleDetected("input() -> select() as compute -> join().lhs -> select() compute -> group() -> join.rhs");

    // check a double fan out and in
    refuteCycleDetected("foo() -> bar1() -> baz() -> nextbar1() -> lastbaz() \n"
        + "foo -> bar2() -> baz -> nextbar2() -> lastbaz");

  }

  private void assertCycleDetected(
      String astString,
      String offendingLinkString,
      int linkLoc,
      String offendingRefString,
      int refLoc
  ) {
    assertCycleDetected(astString, offendingLinkString, SourceLocation.index(linkLoc), offendingRefString,
        SourceLocation.index(refLoc));
  }

  private void assertCycleDetected(
      String astString,
      String offendingLinkString,
      SourceLocation lineNo,
      String offendingRefString,
      SourceLocation firstLineNo
  ) {
    PipelineDeclaration ast = ExpressionParser.INSTANCE.parsePipeline(astString);
    StepLink offendingLink = ExpressionParser.INSTANCE.parsePipeline(offendingLinkString).getFirst().getLink(0);
    StepDeclaration offendingDecl = ExpressionParser.INSTANCE.parsePipeline(offendingRefString).getFirst().getFirst();
    assertThat(
      ast.checkValid(ast.getStepNameFunction(NAMING_POLICY)).getProblems(),
      Matchers.contains(Matchers.equalTo(PipelineProblems.get().cycleDetected(
          offendingLink.toSource(),
          lineNo,
          offendingDecl.toSource(),
          firstLineNo
      )))
    );
  }

  private void refuteCycleDetected(
      String astString
  ) {

    PipelineDeclaration ast = ExpressionParser.INSTANCE.parsePipeline(astString);
    assertThat(
      ast.checkValid(ast.getStepNameFunction(NAMING_POLICY)).getProblems(),
      Matchers.empty()
    );
  }
}
