/*
 * 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 nz.org.riskscape.engine.Matchers.*;
import static nz.org.riskscape.engine.problem.ProblemMatchers.isProblem;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

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

import org.junit.Test;

import com.google.common.collect.Range;

import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.cli.ExitException;
import nz.org.riskscape.engine.pipeline.Pipeline;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.steps.Input;
import nz.org.riskscape.engine.steps.JoinStep;
import nz.org.riskscape.engine.test.EngineTestPlugins;

@EngineTestPlugins({ "defaults" })
public class JoinStepTest extends BaseModelRunCommandTest {

  @Test
  public void canJoinWithOldSyntax() throws Exception {
    evalCommand.pipelineFile = """
                               input(value: {bar: 'bar'}) as lhs
                               -> join(on: true)
                               -> save('joined')

                               input(value: {foo: 'foo'}) as rhs
                               -> join.rhs
                               """;
    evalCommand.run();
    assertThat(openCsv("joined.csv", "bar", "foo").stream().toList(), contains(
        contains("bar", "foo")
    ));
  }

  @Test
  public void rhsArgCanAcceptJustAStepName() throws Exception {
    evalCommand.pipelineFile = """
                               input(value: {bar: 'bar'}) as lhs
                               -> join(rhs: <- foo)
                               -> save('joined')

                               input(value: {foo: ['foo1', 'foo2', 'foo3']})
                               -> unnest(foo)
                               -> select({*}) as foo
                               """;
    evalCommand.run();

    assertThat(openCsv("joined.csv", "bar", "foo").stream().toList(), contains(
        contains("bar", "foo1"),
        contains("bar", "foo2"),
        contains("bar", "foo3")

    ));
  }

  @Test
  public void cannotMakeChangesToExternallyDefinedRHS() throws Exception {
    evalCommand.pipelineFile = """
                               input(value: {bar: 'bar'}) as lhs
                               -> join(on: true, rhs: <- foo -> filter(true))
                               -> save('joined')

                               input(value: {foo: 'foo'}) as foo
                               """;
    ExitException ex = assertThrows(ExitException.class, () -> evalCommand.run());
    String rendered = render(ex.getProblem());
    assertThat(rendered, allOf(
        containsString("Failed to validate `join` step"),
        containsString("'foo' step reference not allowed here.  The join step only")
    ));
  }

  @Test
  public void canJoinWithRhsArgFromSubPipe() throws Exception {
    evalCommand.pipelineFile = """
                               input(value: {bar: 'bar'}) as lhs
                               -> join(
                                    on: true,
                                    rhs: <- input(value: {foo: 'foo'})
                                  )
                               -> save('joined')
                               """;
    evalCommand.run();
    assertThat(openCsv("joined.csv", "bar", "foo").stream().toList(), contains(
        contains("bar", "foo")
    ));
  }

  @Test
  public void canJoinWithRhsArgFromSubPipeWithManySteps() throws Exception {
    evalCommand.pipelineFile = """
                               input(value: {bar: 'bar'}) as lhs
                               -> join(
                                    on: true,
                                    rhs: <- input(value: {foo: 'what'})
                                              -> select({foo: ['foo1', 'foo2', 'foo3']})
                                              # we tack more steps on in this chain to ensure that they
                                              # all get executed
                                              -> unnest(foo)
                                  )
                               -> save('joined')
                               """;
    evalCommand.run();
    assertThat(openCsv("joined.csv", "bar", "foo").stream().toList(), contains(
        contains("bar", "foo1"),
        contains("bar", "foo2"),
        contains("bar", "foo3")
    ));
  }

  @Test
  public void cannotSendRHSPipelineToExternalStep() throws Exception {
    evalCommand.pipelineFile = """
                               input(value: {bar: 'bar'}) as lhs
                               -> join(on: true, rhs: <- input(value: {foo: 'foo'}) -> from_rhs)
                               -> save('joined')

                               input(value: 'baz') -> save('from_rhs') as from_rhs
                               """;
    ExitException ex = assertThrows(ExitException.class, () -> evalCommand.run());
    String rendered = render(ex.getProblem());
    assertThat(rendered, allOf(
        containsString("Failed to validate `join` step"),
        containsString("'from_rhs' step reference not allowed here.")
    ));
  }

  @Test
  public void errorIfNoRhsArgFromMissingStep() throws Exception {
    evalCommand.pipelineFile = """
                               input(value: {bar: 'bar'}) as lhs
                               -> join(on: true, rhs: <- missing)
                               -> save('joined')
                               """;
    ExitException ex = assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(ex.getProblem(), Matchers.hasAncestorProblem(isError(Pipeline.ProblemCodes.STEP_NAME_UNKNOWN)));
  }

  @Test
  public void errorIfNoInputProvided() {
    evalCommand.pipelineFile = """
                               join(on: true)
                               -> save('joined')
                               """;
    ExitException ex = assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(ex.getProblem(), Matchers.hasAncestorProblem(
        isProblem(GeneralProblems.class,
            (r, p) -> p.badArity(r.eq(Input.class), r.any(), r.eq(Range.closed(1, 2)), r.eq(0)))
    ));
  }

  @Test
  public void errorIfRhsFromNamedInputNoLhsProvided() {
    evalCommand.pipelineFile = """
                               join(on: true)
                               -> save('joined')

                               input(value: {bar: 'bar'}) -> join.rhs
                               """;
    ExitException ex = assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(ex.getProblem(), Matchers.hasAncestorProblem(
        is(JoinStep.PROBLEMS.noLeftHandSide())
    ));
  }

  @Test
  public void errorIfSameInputUsedForLeftAndRight() {
    evalCommand.pipelineFile = """
                               input(value: {bar: 'bar'}) ->
                               join(on: true)
                               -> save('joined')

                               input -> join.rhs
                               """;
    ExitException ex = assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(ex.getProblem(), Matchers.hasAncestorProblem(
        isError(Pipeline.ProblemCodes.EDGE_ALREADY_EXISTS)
    ));
  }

  @Test
  public void errorIfSameStepUsedForBothSides() {
    evalCommand.pipelineFile = """
                               join(on: true)
                               -> save('joined')

                               input(value: {bar: 'bar'})
                               input -> join.lhs
                               input -> join.rhs
                               """;
    ExitException ex = assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(ex.getProblem(), Matchers.hasAncestorProblem(
        isError(Pipeline.ProblemCodes.EDGE_ALREADY_EXISTS)
    ));
  }

  @Test
  public void errorIfSameStepUsedForBothSidesRhsArg() {
    evalCommand.pipelineFile = """
                               join(on: true, rhs: <- input)
                               -> save('joined')

                               input(value: {bar: 'bar'})
                               input -> join.lhs
                               """;
    ExitException ex = assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(ex.getProblem(), Matchers.hasAncestorProblem(
        isError(Pipeline.ProblemCodes.EDGE_ALREADY_EXISTS)
    ));
  }

  @Test
  public void errorIfRhsFromArgNoLhsProvided() {
    evalCommand.pipelineFile = """
                               join(on: true, rhs: <- input(value: {bar: 'bar'}))
                               -> save('joined')
                               """;
    ExitException ex = assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(ex.getProblem(), Matchers.hasAncestorProblem(
        isProblem(GeneralProblems.class,
            (r, p) -> p.badArity(r.eq(Input.class), r.any(), r.eq(Range.closed(1, 2)), r.eq(0)))
    ));
  }

  @Test
  public void errorIfNoRhsProvided() throws Exception {
    evalCommand.pipelineFile = """
                               input(value: {bar: 'bar'}) as lhs
                               -> join(on: true)
                               -> save('joined')
                               """;
    ExitException ex = assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(ex.getProblem(), Matchers.hasAncestorProblem(is(JoinStep.PROBLEMS.noRightHandSide())));
  }

  @Test
  public void errorIfTwoRhsProvided() throws Exception {
    evalCommand.pipelineFile = """
                               input(value: {bar: 'bar'}) as lhs
                               -> join(on: true, rhs: <- input(value: {foo: 'foo'}))
                               -> save('joined')

                               input(value: {foo: 'foo'}) -> join.rhs
                               """;
    ExitException ex = assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(ex.getProblem(), Matchers.hasAncestorProblem(is(JoinStep.PROBLEMS.twoRightHandSides())));
  }
}
