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

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.FileProblems;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.bind.BoundParameters;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.bind.ParameterSet;
import nz.org.riskscape.engine.cli.ExitException;
import nz.org.riskscape.engine.cli.model.RunCommand;
import nz.org.riskscape.engine.model.Model;
import nz.org.riskscape.engine.model.ModelFramework;
import nz.org.riskscape.engine.problem.ProblemMatchers;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problem.Severity;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

// not testing contents, this is about files and options
public class ModelRunCommandOutputOptionsTest extends BaseModelRunCommandTest {

  @Test
  public void canWriteToDirectoryWithSpaces() throws Exception {
    runCommand.modelId = "unnamed-last-step";
    runCommand.runnerOptions.output = getTempDirectory().resolve("my results/").toUri().toString();
    runCommand.run();

    openCsv("my results/sort.csv", "name");
  }

  @Test
  public void byDefaultANonSpatialOutputIsWrittenAsCsv() throws Exception {
    runCommand.modelId = "unnamed-last-step";
    runCommand.run();

    openCsv("sort.csv", "name");
  }

  @Test
  public void byDefaultASpatialOutputIsWrittenAsAShapefile() throws Exception {
    runCommand.modelId = "unnamed-last-step";
    runCommand.parameters.add("inputRelation='geo-animals'");
    runCommand.run();

    // not testing contents, this is about files and options
    assertTrue(getTempDirectory().resolve("sort.shp").toFile().exists());
  }

  @Test
  public void aFormatOptionCanBeSuppliedOnTheCliWhichOverridesTheImplicitDefault() throws Exception {
    runCommand.modelId = "unnamed-last-step";
    runCommand.parameters.add("inputRelation='geo-animals'");
    runCommand.runnerOptions.format = "csv";

    runCommand.run();

    assertFalse(getTempDirectory().resolve("sort.shp").toFile().exists());
    openCsv("sort.csv", "name", "point");
  }

  @Test
  public void explicitNameOnLastStepIsUsedAsOutputName() throws Exception {
    runCommand.modelId = "named-last-step";
    runCommand.run();

    openCsv("sorted_animals.csv", "name");
  }


  @Test
  public void aModelWithAnExplicitOutputProducesShapefileIfSpatialOutput() throws Exception {
    runCommand.modelId = "explicit-output-with-name-param";
    runCommand.parameters.add("inputRelation='geo-animals'");
    runCommand.run();

    assertTrue(getTempDirectory().resolve("the best animals.shp").toFile().exists());
  }

  @Test
  public void aModelWithAnExplicitOutputProducesCsvIfSpatialOutputButPipelineOptionGiven() throws Exception {
    runCommand.modelId = "explicit-output-with-name-param";
    runCommand.parameters.add("inputRelation='geo-animals'");
    runCommand.parameters.add("fave_animals.format=csv");
    runCommand.runnerOptions.format = "csv";
    runCommand.run();

    openCsv("the best animals.csv", "name", "point");
  }

  @Test
  public void newCsvFilesAreRolledToAvoidOverwriting() throws Exception {
    runCommand.modelId = "unnamed-last-step";
    runCommand.run();

    openCsv("sort.csv", "name");

    reset();
    runCommand.parameters.add("inputRelation='geo-animals'");
    runCommand.runnerOptions.format = "csv";
    runCommand.run();

    openCsv("sort-1.csv", "name", "point");
    // double check it wasn't messed with
    openCsv("sort.csv", "name");

    assertThat(Arrays.asList(getTempDirectory().toFile().list()), hasItem("manifest-1.txt"));
  }

  @Test
  public void newShapefilesAreRolledToAvoidOverwriting() throws Exception {
    runCommand.modelId = "unnamed-last-step";
    runCommand.parameters.add("inputRelation='geo-animals'");
    runCommand.run();

    assertTrue(getTempDirectory().resolve("sort.shp").toFile().exists());

    reset();
    runCommand.run();

    assertTrue(getTempDirectory().resolve("sort-1.shp").toFile().exists());
    assertThat(Arrays.asList(getTempDirectory().toFile().list()), hasItem("manifest-1.txt"));
  }

  @Test
  public void existingFilesCanBeReplacedWithDashDashForce() throws Exception {
    runCommand.modelId = "unnamed-last-step";
    runCommand.run();

    openCsv("sort.csv", "name");

    reset();
    runCommand.parameters.add("inputRelation='geo-animals'");
    runCommand.runnerOptions.format = "csv";
    runCommand.runnerOptions.replace = true;
    runCommand.run();

    // no new file should be created
    assertThat(Arrays.asList(getTempDirectory().toFile().list()), not(hasItem("sort-1.csv")));
    assertThat(Arrays.asList(getTempDirectory().toFile().list()), not(hasItem("manifest-1.txt")));
    // original file has been placed
    openCsv("sort.csv", "name", "point");
  }

  @Test
  public void aModelWithAnExplicitOutputProducesCsvIfSpatialOutputButCliOptionGiven() throws Exception {
    runCommand.modelId = "explicit-output-with-name-param";
    runCommand.parameters.add("inputRelation='geo-animals'");
    runCommand.runnerOptions.format = "csv";
    runCommand.run();

    openCsv("the best animals.csv", "name", "point");
  }

  @Test
  public void getWarningIfCliCannotOverrideExplicitOutputFormatInModel() throws Exception {
    // --format only overrides the *default* save format, so it shouldn't override a model with
    // a save format already explicitly specified
    runCommand.modelId = "explicit-output-no-name";
    runCommand.parameters.add("inputRelation='geo-animals'");
    runCommand.runnerOptions.format = "shapefile";
    runCommand.run();

    // output is still csv (because it's baked into the model) even though we used --format=shapefile
    openCsv("sorted_animals.csv", "name", "point");

    assertThat(collectedSinkProblems, contains(
        Problems.get(RunCommand.LocalProblems.class).cannotOverrideSaveFormat("shapefile")
            .withSeverity(Severity.WARNING)
        ));
  }

  Model dummyModel = Mockito.mock(Model.class);
  ModelFramework dummyFramework = Mockito.mock(ModelFramework.class);


  @Before
  public void addMockFramework() {
    BoundParameters params = ParameterSet.from(Parameter.optional("foo", String.class))
        .bind(project.newBindingContext(), Collections.emptyMap());
    Mockito.when(dummyModel.getBoundParameters()).thenReturn(params);
    Mockito.when(dummyModel.getFramework()).thenReturn(dummyFramework);
    Mockito.when(dummyModel.getFrameworkParameters()).thenReturn(params);

    Mockito.when(dummyModel.realize(Mockito.any())).thenReturn(ResultOrProblems.failed(Problems.foundWith("carrots")));
    Mockito.when(dummyFramework.getId()).thenReturn("mock");
    Mockito.when(dummyFramework.getBuildParameterSet()).thenReturn(ParameterSet.EMPTY);


    engine.getModelFrameworks().add(dummyFramework);

    // by default, the model comes back a-ok
    Mockito
    .when(dummyFramework.build(Mockito.any(), Mockito.any()))
     .thenReturn(ResultOrProblems.of(dummyModel));

  }

  @After
  public void removeMockFramework() {
    // engine is reused across tests, clean up after ourselves
    engine.getModelFrameworks().remove("mock");
  }

  // NB there used to be a bug where the warning would come out twice because we built the model twice
  // when parameters were given.
  @Test
  public void problemsOnlyReportedOnceWithParameterUpdates() throws Exception {
    Problem warning = Problems.foundWith("my chakras").withSeverity(Severity.WARNING);

    Mockito
    .when(dummyFramework.build(Mockito.any(), Mockito.any()))
    .thenReturn(ResultOrProblems.of(dummyModel, warning));

    runCommand.modelId = "warnings";
    runCommand.parameters = Arrays.asList("foo=bar");
    Assert.assertThrows(RuntimeException.class, () -> runCommand.run());

    // should see a single warning
    assertThat(
      terminal.getCollectedProblems(),
      contains(Matchers.hasAncestorProblem(equalTo(warning)))
    );
  }

  @Test
  public void errorIfOutputUnusable() {
    runCommand.modelId = "unnamed-last-step";
    runCommand.runnerOptions.output = String.format("%s/foo<bar", getTempDirectory().toUri().toString());
    ExitException ex = assertThrows(ExitException.class, () -> runCommand.run());
    assertThat(ex.getProblem(), hasAncestorProblem(ProblemMatchers.isProblem(
        FileProblems.class,
        (r, p) -> p.badUri(r.eq(runCommand.runnerOptions.output), r.any()))
    ));
  }

  Path stats = getTempDirectory().resolve("stats.txt");

  @Test
  public void canWriteOutProgressMetricsToATextFile() throws Exception {
    runCommand.modelId = "named-last-step";
    runCommand.runnerOptions.progressIndicator = stats.toString();

    runCommand.run();

    assertThat(
        Files.readAllLines(stats),
        // unfortunately, the scheduler removes everything from the registry as the tasks wind down, so all we
        // can do is assert the final, empty state.
        hasItem(equalToCompressingWhiteSpace("Complete!"))
    );
  }

  @Test
  public void canWriteOutProgressAndEngineMetricsToATextFile() throws Exception {
    // need to hit a raster for the tile cache to appear
    populateProjectAndSetupCommands(homes().resolve("CoverageSamplingTest"));

    runCommand.modelId = "sample-raster2-with-map";
    runCommand.runnerOptions.progressIndicator = stats.toString();
    runCommand.runnerOptions.engineStats = true;

    runCommand.run();

    assertThat(
        Files.readAllLines(stats),
        allOf(
            hasItem("Complete!"),
//            // heap pressure
            hasItem(containsString("engine.current-heap-pressure")),
            // tile metrics
            hasItem(containsString("engine.tile-cache.hits"))
        )
    );
  }

  // pending #321
//  @Test
//  public void aModelWithAnExplicitOutputIsNamedAfterTheSaveStep() throws Exception {
//    runCommand.modelId = "explicit-output-no-name";
//    runCommand.run();
//
//    openCsv("save.csv", "name");
//  }

  // TODO only works with scheduler?
//  @Test
//  public void aModelCanDefineManyOutputs() throws Exception {
//    runCommand.modelId = "many-outputs";
//    runCommand.run();
//  }

}
