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

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.Test;

import nz.org.riskscape.engine.cli.model.RunCommand;

/**
 * Tests for the correct handling of relative paths to ensure that,
 *
 * 1) command line arguments have relative paths resolved from current working directory 2) project
 * and bookmark files that contain relative paths have them resolved relative to the file containing
 * them
 */
public class GL164_Relative_Paths extends BaseModelRunCommandTest {

  @Test
  public void projectFileDefinedBookmarksAreRelativeToProjectFile() throws Exception {
    doTest("pipeline", Arrays.asList("relation=car"), "car");
  }

  @Test
  public void bookmarksAreRelativeToFileDefiningThem() throws Exception {
    // car is defined in parent directory
    doTest("pipeline", Arrays.asList("relation=car"), "car");
    reset();

    // paths are relative to the bookmark, so it works the same if we use a quoted
    // bookmark ID expression, or use the binder to resolve unquoted bookmark IDs
    doTest("pipeline-expression", Arrays.asList("relation='car'"), "car");
    reset();

    // car-bookmark is defined in dir1/bookmarks.ini
    doTest("pipeline", Arrays.asList("relation=car-bookmark"), "car1");
    reset();

    doTest("pipeline-expression", Arrays.asList("relation='car-bookmark'"), "car1");

    reset();
    useDir1Project();
    doTest("pipeline-expression", Arrays.asList("relation='car-bookmark'"), "car1");
  }

  @Test
  public void commandLineArgsAreRelativeToCurrentWorkDir() throws Exception {
    doTest("pipeline", Arrays.asList("relation=car.csv"), "car");

    reset();
    doTest("pipeline", Arrays.asList("relation=dir1/car.csv"), "car1");

    reset();
    // path starting with ./ is relative to the working directory
    doTest("pipeline", Arrays.asList("relation=./src/test/homes/GL164_Relative_Paths/dir1/car.csv"), "car1");

    reset();
    useDir1Project();

    doTest("pipeline", Arrays.asList("relation=../car.csv"), "car");

    reset();
    doTest("pipeline", Arrays.asList("relation=car.csv"), "car1");
  }

  @Test
  public void modelLocationsAreRelativeToModelFile() throws Exception {
    useDir1Project();

    doTest("car", Arrays.asList(), "car1");

    reset();
    doTest("car", Arrays.asList("relation=../car.csv"), "car");

    reset();
    // path starting with ./ is relative to the working directory
    doTest("car", Arrays.asList("relation=./src/test/homes/GL164_Relative_Paths/car.csv"), "car");

    reset();
    doTest("car", Arrays.asList("relation=truck"), "truck1");
  }

  @Test
  public void pathIsRelativeToParameterFileContainingIt() throws Exception {
    doTest("pipeline", Collections.emptyList(), "dir1/parameters1.ini", "car");

    reset();
    doTest("pipeline", Collections.emptyList(), "dir1/parameters2.ini", "car1");
  }

  @Test
  public void parameterFilePathsAreRelativeToTheParameterFileForWizardModel() throws Exception {
    assertThat(runWizardTest(Collections.emptyList(), "dir1/parameters-wizard.ini"),
        containsInAnyOrder(
            contains("1", "3"),
            contains("0", "1")
        ));

    reset();
    useDir1Project();
    assertThat(runWizardTest(Collections.emptyList(), "dir1/parameters-wizard.ini"),
        containsInAnyOrder(
            contains("1", "3"),
            contains("0", "1")
        ));
  }

  @Test
  public void commandLineParametersForWizardModelAreRelativeTo() throws Exception {
    // parameter values are relative to the project location
    assertThat(
        runWizardTest(Arrays.asList("input-hazards.layer=../GL472_CombineCoverages/magma2.shp"), null),
        containsInAnyOrder(
            contains("1", "3"),
            contains("0", "1")
        ));

    reset();
    // unless they start with ./
    assertThat(
        runWizardTest(Arrays.asList("input-hazards.layer=./src/test/homes/GL472_CombineCoverages/pumice2.shp"), null),
        containsInAnyOrder(
            contains("0", "4")
        ));

    reset();
    useDir1Project();
    assertThat(
        runWizardTest(Arrays.asList("input-hazards.layer=./src/test/homes/GL472_CombineCoverages/magma2.shp"), null),
        containsInAnyOrder(
            contains("1", "3"),
            contains("0", "1")
        ));

    reset();
    assertThat(
        runWizardTest(Arrays.asList("input-hazards.layer=../../GL472_CombineCoverages/pumice2.shp"), null),
        containsInAnyOrder(
            contains("0", "4")
        ));
  }

  @Test
  public void pipelineExpressionsAreAlwaysRelativeToProjectFile() throws Exception {
    // by default, all pipeline model parameters are expressions, so the relation parameters
    // are typically passed through as string expressions. This bypasses the relative-path
    // handling because of the wrapping quotes.
    doTest("pipeline-expression", Arrays.asList("relation='./car.csv'"), "car");

    reset();
    doTest("pipeline-expression", Arrays.asList("relation='./dir1/car.csv'"), "car1");

    // the parameter here is './car.csv', which is relative to the project file
    reset();
    doTest("pipeline-expression", Arrays.asList(), "dir1/parameters3.ini", "car");

    // car-expression model is defined in dir1, but expression is still relative to project.ini
    reset();
    doTest("car-expression", Arrays.asList(), "car");

    reset();
    useDir1Project();

    doTest("pipeline-expression", Arrays.asList("relation='./car.csv'"), "car1");

    reset();
    doTest("pipeline-expression", Arrays.asList("relation='./../car.csv'"), "car");

    reset();
    doTest("pipeline-expression", Arrays.asList(), "dir1/parameters3.ini", "car1");

    reset();
    doTest("car-expression", Arrays.asList(), "car1");
  }

  private void useDir1Project() {
    populateProject(stdhome().resolve("dir1/"));
  }

  private void doTest(String modelId, List<String> parameters, String expected) throws Exception {
    doTest(modelId, parameters, null, expected);
  }

  private void doTest(String modelId, List<String> parameters, String parametersFile, String expected)
      throws Exception {
    runTest(modelId, parameters, parametersFile);

    List<List<String>> losses = openCsv("output.csv", "loss");

    assertThat(
      losses,
      contains(
        contains(expected)
      )
    );
  }

  private List<List<String>> runWizardTest(List<String> parameters, String parametersFile) throws Exception {
    runTest("wizard", parameters, parametersFile);

    return openCsv("event-impact.csv", "affected", "count");
  }

  private void runTest(String modelId, List<String> parameters, String parametersFile)
      throws Exception {
    // we set up a new run command every time. this is to accomodate the project switching going on.
    runCommand = this.setupCommand(new RunCommand());
    runCommand.runnerOptions.output = getTempDirectory().toString();
    runCommand.runnerOptions.replace = true;

    runCommand.modelId = modelId;
    runCommand.parameters = parameters;
    if (parametersFile != null) {
      runCommand.parametersFile = stdhome().resolve(parametersFile);
    }

    runCommand.run();
  }
}
