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

import static org.junit.Assert.*;

import java.util.Optional;

import org.junit.Test;

import nz.org.riskscape.engine.OsUtils;
import nz.org.riskscape.rl.ExpressionParser;
import nz.org.riskscape.rl.ast.PipelineDeclaration;
import nz.org.riskscape.rl.ast.PipelineDeclaration.Found;
import nz.org.riskscape.rl.ast.StepDefinition;
import nz.org.riskscape.rl.ast.StepReference;

/**
 * Tests the API parts of the PipelineDeclaration class and its family - doesn't delve in to parsing routines etc
 */
public class PipelineASTTest {

  PipelineDeclaration parsed;

  @Test
  public void canProduceAUsefulConciseToString() throws Exception {
    assertEquals("PipelineDeclaration[foo]", parse("foo").toString());
    // chaining
    assertEquals("PipelineDeclaration[foo -> bar]", parse("foo -> bar").toString());
    // 2chainz
    assertEquals("PipelineDeclaration[foo -> bar, baz]", parse("foo -> bar baz").toString());
    // ? goes before name to show it's an implicit name in a step definition
    assertEquals("PipelineDeclaration[?bar()]", parse("bar()").toString());
    // alias is used over step id in a step definition - no ?
    assertEquals("PipelineDeclaration[bar()]", parse("foo() as bar").toString());
    // ellipsis used to show args given
    assertEquals("PipelineDeclaration[bar(…)]", parse("foo(cool) as bar").toString());
  }

  @Test
  public void canToSourceAST() throws Exception {
    assertEquals(String.format("foo()%s -> bar(1, 'two', 3.0)", OsUtils.LINE_SEPARATOR),
        parse("foo() -> bar(1, 'two', 3.0)").toSource());
    // whitespace is elided
    assertEquals(String.format("foo()%s -> bar(1, 'two', 3.0)", OsUtils.LINE_SEPARATOR),
        parse("  foo\n()  ->   bar(1, 'two'  , 3.0)").toSource());
  }

  @Test
  public void canSearchForSteps() throws Exception {
    // simple case
    parse("foo -> bar -> baz");
    Found pair = findStep("bar").orElse(null);
    assertEquals(new Found(parsed, parsed.getFirst(), new StepReference("bar")), pair);

    // missing case
    parse("foo -> bar");
    pair = findStep("baz").orElse(null);
    assertNull(pair);

    // step definition, not a reference
    parse("foo -> bar() -> baz");
    pair = findStep("bar").orElse(null);

    assertEquals(
      new Found(
        parsed,
        parsed.getFirst(),
        new StepDefinition("bar")
      ),
      pair
    );

    // duplicate case - finds the first one
    parse("foo -> bar -> baz bar() ");
    pair = findStep("bar").orElse(null);
    assertEquals(new Found(parsed, parsed.getFirst(), new StepReference("bar")), pair);
  }

  private Optional<Found> findStep(String withIdent) {
    return parsed.find((chain, step) -> step.getIdent().equals(withIdent));
  }

  @Test
  public void canCombineTwoASTs() throws Exception {
    PipelineDeclaration combined = parse("foo -> bar").add(parse("bar -> foo"));
    assertEquals(combined, parse("foo -> bar bar -> foo"));
  }

  @Test
  public void canReplaceAStepChain() throws Exception {
    parse("cat -> dog foo -> bar  bar() -> baz");

    PipelineDeclaration replaced = parsed.replace(
        findStep("foo").get().getChain(),
        parse("foo() as Foo -> bar() as Bar").getFirst()
    );

    assertEquals(
        String.format("cat%1$s -> dog%1$sfoo() as Foo%1$s -> bar() as Bar%1$sbar()%1$s -> baz",
            OsUtils.LINE_SEPARATOR),
        replaced.toSource());
  }

  @Test
  public void canAppendTwoStepChains() throws Exception {
    assertEquals(
        String.format("cat%1$s -> dog%1$s -> foo%1$s -> bar", OsUtils.LINE_SEPARATOR),
        parse("cat -> dog").getFirst().append(parse("foo -> bar").getFirst()).toSource()
    );
  }

  PipelineDeclaration parse(String source) {
    parsed = ExpressionParser.INSTANCE.parsePipeline(source);
    return parsed;
  }
}
