/*
 * 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.junit.Assert.*;
import static org.mockito.Mockito.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.google.common.collect.ImmutableMap;

import nz.org.riskscape.engine.relation.EmptyRelation;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.rl.ast.PipelineDeclaration;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.problem.Problems;

public class RealizedPipelineCloningTest {

  ExecutionContext context = mock(ExecutionContext.class);
  Relation relation = new EmptyRelation(Types.TEXT.asStruct());
  Map<String, List<?>> fooStepParameters = ImmutableMap.of("foo", Arrays.asList("baz", "bar"));

  RealizedPipeline newPipeline(RealizedStep... steps) {
    return new RealizedPipeline(
        context,
        PipelineDeclaration.EMPTY,
        List.of(steps)
    );
  }

  RealizedStep stepOne = RealizedStep.named("foo");
  RealizedStep stepTwo = RealizedStep.named("bar");
  RealizedStep stepThree = RealizedStep.named("baz");


  @Test
  public void cloneASingleStepPipeline() {
    stepOne = stepOne.withParameters(fooStepParameters);
    RealizedPipeline realizedPipeline = newPipeline(stepOne);

    RealizedPipeline cloned = realizedPipeline.clone();
    assertSame(realizedPipeline.getAst(), cloned.getAst());
    assertSame(realizedPipeline.getContext(), cloned.getContext());
    assertClone(realizedPipeline.getRealizedSteps(), cloned.getRealizedSteps());

    assertClone(stepOne, cloned.getStep("foo").get());
  }

  @Test
  public void cloneATwoStepPipeline() throws Exception {
    stepTwo = stepTwo.withDependencies(stepOne);
    RealizedPipeline realizedPipeline = newPipeline(stepOne, stepTwo);

    RealizedPipeline clone = realizedPipeline.clone();

    RealizedStep cloneStepOne = clone.getStep("foo").get();
    RealizedStep cloneStepTwo = clone.getStep("bar").get();
    assertClone(stepOne, cloneStepOne);
    assertClone(stepTwo, cloneStepTwo);

    // now check the dependencies point to the clones
    assertThat(clone.getDependents(cloneStepOne), contains(sameInstance(cloneStepTwo)));
    assertTrue(cloneStepOne.getDependencies().isEmpty());

    assertThat(cloneStepTwo.getDependencies(), contains(sameInstance(cloneStepOne)));
    assertTrue(clone.getDependents(cloneStepTwo).isEmpty());

    assertThat(clone.getEndSteps(), contains(cloneStepTwo));
  }

  @Test
  public void canDrainWarnings() throws Exception {
    Problem warningOne = Problems.foundWith("us").withSeverity(Severity.WARNING);
    Problem warningTwo = Problems.foundWith("step1").withSeverity(Severity.WARNING);
    stepOne = stepOne.withProblems(warningOne);
    stepTwo = stepTwo.withProblems(warningTwo).withDependencies(stepOne);
    Problem pipelineWarning = Problems.foundWith("you").withSeverity(Severity.WARNING);
    RealizedPipeline realizedPipeline = new RealizedPipeline(context, PipelineDeclaration.EMPTY,
        List.of(stepOne, stepTwo), Arrays.asList(pipelineWarning));

    // they are warnings, not errors
    assertThat(realizedPipeline.getFailures(), hasSize(0));

    List<Problem> collected = new ArrayList<>();
    RealizedPipeline drained = realizedPipeline.drainWarnings(collected::add);
    assertThat(collected, containsInAnyOrder(pipelineWarning, Problems.foundWith(stepOne.getAst(), warningOne),
        Problems.foundWith(stepTwo.getAst(), warningTwo)));

    RealizedStep cloneStepOne = drained.getStep("foo").get();
    RealizedStep cloneStepTwo = drained.getStep("bar").get();

    // step results now differ because warnings have been drained
    assertNotEquals(stepOne.getResult(), cloneStepOne.getResult());
    assertEquals(stepOne.getResult().getWithProblemsIgnored(), cloneStepOne.getResult().get());

    // but everything else should be equivalent
    assertClone(realizedPipeline.getDependents(stepOne), drained.getDependents(cloneStepOne));
    assertClone(stepTwo.getDependencies(), cloneStepTwo.getDependencies());
    assertSame(stepTwo.getProduces(), cloneStepTwo.getProduces());

    // check the dependencies point to the clones
    assertThat(drained.getDependents(cloneStepOne), contains(sameInstance(cloneStepTwo)));
    assertTrue(cloneStepOne.getDependencies().isEmpty());
    assertThat(cloneStepTwo.getDependencies(), contains(sameInstance(cloneStepOne)));
    assertTrue(drained.getDependents(cloneStepTwo).isEmpty());

    // warnings should now have been removed from the cloned pipeline steps
    assertThat(cloneStepOne.getProblems(), empty());
    assertThat(cloneStepTwo.getProblems(), empty());

    // check they were removed from the cloned pipeline
    collected.clear();
    drained = drained.drainWarnings(collected::add);
    assertThat(collected, hasSize(0));
  }

  @Test
  public void cloneAFanOutPipeline() throws Exception {
    stepTwo = stepTwo.withDependencies(stepOne);
    stepThree = stepThree.withDependencies(stepOne);
    RealizedPipeline realizedPipeline = newPipeline(stepOne, stepTwo, stepThree);
    RealizedPipeline clone = realizedPipeline.clone();

    RealizedStep cloneStepOne = clone.getStep("foo").get();
    RealizedStep cloneStepTwo = clone.getStep("bar").get();
    RealizedStep cloneStepThree = clone.getStep("baz").get();
    assertClone(stepOne, cloneStepOne);
    assertClone(stepTwo, cloneStepTwo);
    assertClone(stepThree, cloneStepThree);

    // now check the dependencies point to the clones
    assertThat(
        clone.getDependents(cloneStepOne),
        containsInAnyOrder(sameInstance(cloneStepTwo), sameInstance(cloneStepThree))
    );
    assertTrue(cloneStepOne.getDependencies().isEmpty());

    assertThat(cloneStepTwo.getDependencies(), contains(sameInstance(cloneStepOne)));
    assertTrue(clone.getDependents(cloneStepTwo).isEmpty());

    assertThat(cloneStepThree.getDependencies(), contains(sameInstance(cloneStepOne)));
    assertTrue(clone.getDependents(cloneStepThree).isEmpty());
  }

  @Test
  public void cloneAJoinedPipeline() throws Exception {
    stepThree  = stepThree.withDependencies(stepOne, stepTwo);
    RealizedPipeline realizedPipeline = newPipeline(stepOne, stepTwo, stepThree);

    RealizedPipeline clone = realizedPipeline.clone();

    RealizedStep cloneStepOne = clone.getStep("foo").get();
    RealizedStep cloneStepTwo = clone.getStep("bar").get();
    RealizedStep cloneStepThree = clone.getStep("baz").get();
    assertClone(stepOne, cloneStepOne);
    assertClone(stepTwo, cloneStepTwo);
    assertClone(stepThree, cloneStepThree);

    // now check the dependencies point to the clones
    assertThat(clone.getDependents(cloneStepOne), contains(sameInstance(cloneStepThree)));
    assertTrue(cloneStepOne.getDependencies().isEmpty());

    assertThat(clone.getDependents(cloneStepTwo), contains(sameInstance(cloneStepThree)));
    assertTrue(cloneStepTwo.getDependencies().isEmpty());

    assertThat(
        cloneStepThree.getDependencies(),
        containsInAnyOrder(sameInstance(cloneStepTwo), sameInstance(cloneStepOne))
    );
    assertTrue(clone.getDependents(cloneStepThree).isEmpty());
  }

  @Test
  public void canCloneADisconnectedPipeline() throws Exception {
    RealizedPipeline realizedPipeline = newPipeline(stepOne, stepTwo);
    RealizedPipeline clone = realizedPipeline.clone();
    RealizedStep cloneStepOne = clone.getStep("foo").get();
    RealizedStep cloneStepTwo = clone.getStep("bar").get();
    assertClone(stepOne, cloneStepOne);
    assertClone(stepTwo, cloneStepTwo);

    assertTrue(cloneStepOne.getDependencies().isEmpty());
    assertTrue(clone.getDependents(cloneStepOne).isEmpty());
    assertTrue(cloneStepTwo.getDependencies().isEmpty());
    assertTrue(clone.getDependents(cloneStepTwo).isEmpty());
  }

  private void assertClone(RealizedStep originalStep, RealizedStep clonedStep) {
    assertClone((Object) originalStep, (Object) clonedStep);
    assertSame(originalStep.getResult(), clonedStep.getResult());
    assertSame(originalStep.getProduces(), clonedStep.getProduces());
    assertClone(originalStep.getBoundParameters(), clonedStep.getBoundParameters());
    assertClone(originalStep.getDependencies(), clonedStep.getDependencies());
  }

  private void assertClone(Object original, Object clone) {
    assertNotSame(original, clone);
    assertEquals(original, clone);
  }
}
