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

import static nz.org.riskscape.engine.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.net.URI;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;

import org.junit.Before;
import org.junit.Test;

import com.codahale.metrics.MetricRegistry;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.OutputProblems;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.cli.ApplicationCommandTest;
import nz.org.riskscape.engine.cli.ExitException;
import nz.org.riskscape.engine.output.CsvFormat;
import nz.org.riskscape.engine.output.PipelineOutputContainer;
import nz.org.riskscape.engine.output.PipelineOutputOptions;
import nz.org.riskscape.engine.output.PipelineOutputStore;
import nz.org.riskscape.engine.output.SinkParameters;
import nz.org.riskscape.engine.pipeline.ExecutionContext;
import nz.org.riskscape.engine.pipeline.RealizedPipeline;
import nz.org.riskscape.engine.pipeline.Sink;
import nz.org.riskscape.pipeline.PipelineMetadata;
import nz.org.riskscape.rl.ast.PipelineDeclaration;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

public class CliPipelineRunnerTest extends ApplicationCommandTest {

  @RequiredArgsConstructor
  static class TestPipelineOutputContainer implements PipelineOutputContainer {

    public final TestPipelineOutputStore parent;
    public final URI outputLocation;
    public final RealizedPipeline pipeline;
    public final PipelineOutputOptions options;

    @Override
    public URI getStoredAt() {
      throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ResultOrProblems<Sink> createSinkForStep(SinkParameters parameters) {
      throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void close() {
      throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Map<String, URI> getPipelineOutputs() {
      throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public PipelineOutputStore getStore() {
      return parent;
    }

    @Override
    public ExecutionContext getExecutionContext() {
      return pipeline.getContext();
    }
  }

  @RequiredArgsConstructor
  public class TestPipelineOutputStore implements PipelineOutputStore {

    @Getter
    private final String id;

    private final Function<URI, Integer> applicabilityFunction;

    @Override
    public PipelineOutputOptions newOutputOptions(String reference) {
      return new PipelineOutputOptions(reference);
    }

    @Override
    public int isApplicable(URI outputLocation) {
      return applicabilityFunction.apply(outputLocation);
    }

    @Override
    public ResultOrProblems<PipelineOutputContainer> create(URI outputLocation, RealizedPipeline usePipeline,
        PipelineOutputOptions argOptions) {
      List<Problem> problems = new ArrayList<>();
      if (outputLocation != null) {
        if (outputLocation.toString().endsWith("/warning")) {
          problems.add(Problem.warning("fake warning"));
        }
        if (outputLocation.toString().endsWith("/multipleWarnings")) {
          problems.add(Problem.warning("fake warning1"));
          problems.add(Problem.warning("fake warning2"));
        }
        if (outputLocation.toString().endsWith("/error")) {
          return ResultOrProblems.failed(Problem.error("fake error"));
        }
      }
      return ResultOrProblems.of(
          new TestPipelineOutputContainer(this, outputLocation, usePipeline, argOptions), problems);
    }

  }

  Supplier<LocalDateTime> currentTime = () -> LocalDateTime.of(2000, 1, 1, 12, 00, 00);
  ExecutionContext executionContext;
  CliPipelineRunner runner;
  RealizedPipeline pipeline;

  PipelineDeclaration pipelineDeclaration = PipelineDeclaration.EMPTY;
  MetricRegistry progressStats = new MetricRegistry();

  TestPipelineOutputContainer outputContainer;

  CliPipelineRunnerOptions options = new CliPipelineRunnerOptions();

  // the catch all store
  PipelineOutputStore catchAllStore = new TestPipelineOutputStore("filesystem",
      uri -> PipelineOutputStore.PRIORITY_DEFAULT);
  PipelineOutputStore testSchemeStore = new TestPipelineOutputStore("test-scheme", uri -> {
    if (uri == null || !"test".equals(uri.getScheme())) {
      return PipelineOutputStore.PRIORITY_NA;
    }
    return PipelineOutputStore.PRIORITY_HIGH;
  });
  PipelineOutputStore geoPackageStore = new TestPipelineOutputStore("geopackage", uri -> {
    if (uri == null || !"file".equals(uri.getScheme()) || ! uri.getPath().endsWith(".gpkg")) {
      return PipelineOutputStore.PRIORITY_NA;
    }
    return PipelineOutputStore.PRIORITY_HIGH;
  });

  @Override
  public void populateProject() {
    super.populateProject();

    project.setRelativeTo(Paths.get(".").toUri());
  }

  @Before
  public void setup() {
    engine.getPipelineOutputStores().add(catchAllStore);
    engine.getPipelineOutputStores().add(testSchemeStore);
    engine.getPipelineOutputStores().add(geoPackageStore);

    executionContext = project.newExecutionContext();
    runner = new CliPipelineRunner(executionContext, messages, terminal, currentTime);

    pipeline = RealizedPipeline
        .empty(executionContext, PipelineDeclaration.EMPTY)
        .withMetadata(PipelineMetadata.ANONYMOUS.withName("foo"));
  }

  @Test
  public void nullOutputBaseUsesProjectDefaultFileLocation() {
    options.output = null; // set null for good measure / explicitness
    project.setOutputBaseLocation(URI.create("file:/tmp/bar"));

    outputContainer = createContainer();
    assertThat(outputContainer.parent, is(catchAllStore));
    assertThat(outputContainer.outputLocation, is(URI.create("file:///tmp/bar/foo/2000-01-01T12_00_00")));
  }

  @Test
  public void nullOutputBaseUsesProjectDefaultNonFileLocationWithoutFolderTimestamping() {
    options.output = null; // set null for good measure / explicitness
    project.setOutputBaseLocation(URI.create("magic:url:foo"));

    outputContainer = createContainer();
    assertThat(outputContainer.parent, is(catchAllStore));
    assertThat(outputContainer.outputLocation, is(project.getOutputBaseLocation()));
  }

  @Test
  public void ifNoBackendSupportsLocationExitExceptionThrown() throws Exception {
    URI outputBase = URI.create("foo-backend:bar");
    options.output = outputBase.toString();
    engine.getPipelineOutputStores().remove(catchAllStore.getId());

    ExitException ex = Assert.assertThrows(ExitException.class, () -> createContainer());

    assertThat(ex.getProblem(), equalTo(Problems.foundWith("--output",
        OutputProblems.get().outputLocationNotSupported(outputBase))));
  }

  @Test
  public void randomOutputBaseReturnsCatchAllContainer() {
    URI outputBase = URI.create("file:///my-test-uri");
    options.output = outputBase.toString();

    outputContainer = createContainer();
    assertThat(outputContainer.parent, is(catchAllStore));
    assertThat(outputContainer.outputLocation, is(outputBase));
  }

  @Test
  public void testSchemeOutputBaseReturnsCatchAllContainer() {
    URI outputBase = URI.create("test://my-test-uri");
    options.output = outputBase.toString();

    outputContainer = createContainer();
    assertThat(outputContainer.parent, is(testSchemeStore));
    assertThat(outputContainer.outputLocation, is(outputBase));
  }

  @Test
  public void geoPackageOutputBaseReturnsGeoPackageContainer() {
    URI outputBase = URI.create("file:/path/to/geopackage.gpkg");
    options.output = outputBase.toString();

    outputContainer = createContainer();
    assertThat(outputContainer.parent, is(geoPackageStore));
    // the output base hasn't been munged with the standard output directory paths <model>/<timestamp>
    assertThat(outputContainer.outputLocation, is(outputBase));
  }

  @Test
  public void passesReplaceOptionToOutputContainer() {
    options.replace = false;

    outputContainer = createContainer();
    assertFalse(outputContainer.options.isReplace());

    options.replace = true;
    outputContainer = createContainer();
    assertTrue(outputContainer.options.isReplace());
  }

  @Test
  public void passesChecksumOptionToOutputContainer() {
    options.checksum = false;

    outputContainer = createContainer();
    assertFalse(outputContainer.options.isChecksum());

    options.checksum = true;
    outputContainer = createContainer();
    assertTrue(outputContainer.options.isChecksum());
  }

  @Test
  public void passesPipelineIdToOutputContainer() {
    outputContainer = createContainer();
    assertThat(outputContainer.options.getReference(), is("foo"));
  }

  @Test
  public void passesPipelineDeclarationToOutputContainer() {
    outputContainer = createContainer();
    assertThat(outputContainer.options.getPipelineDeclaration(), Matchers.isPresent(pipelineDeclaration));
  }

  @Test
  public void passesFormatOptionToOutputContainer() {
    options.format = null;
    CsvFormat csvFormat = new CsvFormat();
    engine.getFormats().add(csvFormat);
    outputContainer = createContainer();
    assertThat(outputContainer.options.getFormat(), Matchers.isEmptyOptional());

    options.format = "csv";
    outputContainer = createContainer();
    assertThat(outputContainer.options.getFormat(), is(Optional.of(csvFormat)));
  }

  @Test
  public void warningsFromOutputStoreAreDrained() {
    URI outputBase = URI.create("warning");
    options.output = outputBase.toString();

    outputContainer = createContainer();
    assertThat(outputContainer.parent, is(catchAllStore));
    assertThat(terminal.getCollectedProblems(), contains(
        Problems.foundWith("--output", Problem.warning("fake warning"))
    ));
  }

  @Test
  public void allWarningsFromOutputStoreAreDrained() {
    URI outputBase = URI.create("multipleWarnings");
    options.output = outputBase.toString();

    outputContainer = createContainer();
    assertThat(outputContainer.parent, is(catchAllStore));
    assertThat(terminal.getCollectedProblems(), contains(
        // we are checking that all the warning are nested under the same --output parent
        Problems.foundWith("--output",
            Problem.warning("fake warning1"),
            Problem.warning("fake warning2"))
    ));
  }

  @Test
  public void errorsFromOutputStoreAreThrown() {
    List<Problem> sunkProblems = new ArrayList<>();
    engine.setProblemSink(p -> sunkProblems.add(p));

    options.output = "error";

    RiskscapeException ex = assertThrows(RiskscapeException.class, () -> createContainer());
    assertThat(ex.getProblem(), is(
        Problems.foundWith("--output", Problem.error("fake error"))
    ));
  }

  private TestPipelineOutputContainer createContainer() {
    return (TestPipelineOutputContainer) runner.createContainer(options, pipeline);
  }

}
