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

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.referencing.CRS;
import org.hamcrest.Matcher;
import org.junit.Test;

import nz.org.riskscape.engine.GeoHelper;
import nz.org.riskscape.engine.OsUtils;
import nz.org.riskscape.engine.SRIDSet;

public class AxisOrderBehaviourIntegrationTest extends BaseModelRunCommandTest {

  private String saveAs = "shapefile";
  private String model = "read";
  private String input = null;
  private String targetCrs = null;

  private static final CoordinateReferenceSystem EPSG2193XY = SRIDSet.epsgToCrsWithForceXY("EPSG:2193");

  private static final List<String> EXPECTED_POINT_DATA_LON_LAT = Arrays.asList("POINT (175 -41)", "1");

  private static final Matcher<String> EXPECTED_POINT_DATA_LON_LAT_FROM_EPSG2193 =
      GeoHelper.wktGeometryMatch("POINT (175.00000000000497 -41.000000040637026)", DEGREE_TOLERANCE_NEAREST_MM);

  /**
   * The expected point data once reprojected from EPSG:4326 to EPGS:2193 and saved to a shapefile (XY axis order)
   */
  private static final Matcher<String> EXPECTED_POINT_DATA_EPSG2193_XY =
      GeoHelper.wktGeometryMatch("POINT (1768207.8850896547 5459316.46622252)", METER_TOLERANCE_NEAREST_MM);

  /**
   * The expected point data once reprojected from CRS:84 to EPGS:2193 and saved to a shapefile (XY axis order)
   * This was expected to be the same as for ESPG:4326 as the .prj files look quite similar, but possibly the
   * DATUM is slightly different thus moving the point a few millimetres.
   */
  private static final Matcher<String> EXPECTED_POINT_DATA_EPSG2193_XY_FROM_CRS84 =
      GeoHelper.wktGeometryMatch("POINT (1768207.8851930252 5459316.470734514)", METER_TOLERANCE_NEAREST_MM);

  @Override
  public void reset() {
    super.reset();
    saveAs = "shapefile";
    model = "read";
    input = null;
    targetCrs = null;
  }

  @Test
  public void canReadWriteDataInCRS84() {
    useInput("point-crs84-no-prj-axis-order");
    saveAs("shapefile");

    run();
    assertCrs(SRIDSet.EPSG4326_LONLAT, readOutputPrj());

    assertOutputWKT("output.shp", EXPECTED_POINT_DATA_LON_LAT);
  }

  @Test
  public void canReadWriteDataInCRS84NoAxisInPrj() {
    useInput("point-crs84-no-prj-axis-order");
    saveAs("shapefile");

    run();
    assertCrs(SRIDSet.EPSG4326_LONLAT, readOutputPrj());

    assertOutputWKT("output.shp", EXPECTED_POINT_DATA_LON_LAT);
  }

  @Test
  public void canReadWriteDataInEPSG4326() {
    useInput("point-epsg4326-with-prj-axis-order");
    saveAs("shapefile");

    run();
    assertCrs(SRIDSet.EPSG4326_LONLAT, readOutputPrj());

    assertOutputWKT("output.shp", EXPECTED_POINT_DATA_LON_LAT);
  }

  @Test
  public void canReadWriteDataInEPSG4326NoAxisInPrj() {
    useInput("point-epsg4326-no-prj-axis-order");
    saveAs("shapefile");

    run();
    assertCrs(SRIDSet.EPSG4326_LONLAT, readOutputPrj());

    assertOutputWKT("output.shp", EXPECTED_POINT_DATA_LON_LAT);
  }

  @Test
  public void canReadWriteDataInEPSG4326YX() {
    // input is shapefile in 4326 by with a non standard YX axis order. The axis order is in the .prj
    // file so should be respected by RiskScape
    useInput("point-epsg4326-yx-with-prj-axis-order");
    saveAs("shapefile");

    run();
    assertCrs(SRIDSet.EPSG4326_LONLAT, readOutputPrj());

    assertOutputWKT("output.shp", EXPECTED_POINT_DATA_LON_LAT);
  }

  @Test
  public void canReadWriteDataInEPSG4326YXNoAxisInPrj() {
    // input is shapefile in 4326 by with a non standard YX axis order. The axis order is not in the .prj
    // file. But the bookmark has crs-name = 'EPSG:4326' which should force the CRS the right way.
    useInput("point-epsg4326-yx-no-prj-axis-order");
    saveAs("shapefile");

    run();
    assertCrs(SRIDSet.EPSG4326_LONLAT, readOutputPrj());

    assertOutputWKT("output.shp", EXPECTED_POINT_DATA_LON_LAT);
  }

  @Test
  public void canReadInCRS84WriteTo2193() {
    useInput("point-crs84-no-prj-axis-order");
    saveAs("shapefile");
    useModel("reproject");

    run();
    // sanity check EPSG2193XY is actually xy axis order
    assertEquals(CRS.AxisOrder.EAST_NORTH, CRS.getAxisOrder(EPSG2193XY));
    assertCrs(EPSG2193XY, readOutputPrj());

    assertThat(readResultsAsCsv("output.shp"), contains(
        GeoHelper.wktGeometryMatch("POINT (1768207.8851930252 5459316.470734514)", METER_TOLERANCE_NEAREST_MM),
        is("1")
    ));
  }

  @Test
  public void canReadInCRS84NoAxisInPrjWriteTo2193() {
    useInput("point-crs84-no-prj-axis-order");
    saveAs("shapefile");
    useModel("reproject");

    run();
    assertCrs(EPSG2193XY, readOutputPrj());

    assertThat(readResultsAsCsv("output.shp"), contains(
        EXPECTED_POINT_DATA_EPSG2193_XY_FROM_CRS84, is("1")
    ));
  }

  @Test
  public void canReadInEPSG4326WriteTo2193() {
    useInput("point-epsg4326-with-prj-axis-order");
    saveAs("shapefile");
    useModel("reproject");

    run();
    assertCrs(EPSG2193XY, readOutputPrj());

    assertThat(readResultsAsCsv("output.shp"), contains(
        EXPECTED_POINT_DATA_EPSG2193_XY, is("1")
    ));
  }

  @Test
  public void canReadInEPSG4326NoAxisInPrjWriteTo2193() {
    useInput("point-epsg4326-no-prj-axis-order");
    saveAs("shapefile");
    useModel("reproject");

    run();
    assertCrs(EPSG2193XY, readOutputPrj());

    assertThat(readResultsAsCsv("output.shp"), contains(
        EXPECTED_POINT_DATA_EPSG2193_XY, is("1")
    ));
  }

  @Test
  public void canReadInEPSG4326YXWriteTo2193() {
    // input is shapefile in 4326 by with a non standard YX axis order. The axis order is in the .prj
    // file so should be respected by RiskScape
    useInput("point-epsg4326-yx-with-prj-axis-order");
    saveAs("shapefile");
    useModel("reproject");

    run();
    assertCrs(EPSG2193XY, readOutputPrj());

    assertThat(readResultsAsCsv("output.shp"), contains(
        EXPECTED_POINT_DATA_EPSG2193_XY, is("1")
    ));
  }

  @Test
  public void canReadInEPSG4326YXNoAxisInPrjWriteTo2193() {
    // input is shapefile in 4326 by with a non standard YX axis order. The axis order is not in the .prj
    // file. But the bookmark has crs-name = 'EPSG:4326' which should force the CRS the right way.
    useInput("point-epsg4326-yx-no-prj-axis-order");
    saveAs("shapefile");
    useModel("reproject");

    run();
    assertCrs(EPSG2193XY, readOutputPrj());

    assertThat(readResultsAsCsv("output.shp"), contains(
        EXPECTED_POINT_DATA_EPSG2193_XY, is("1")
    ));
  }

  @Test
  public void canReadInEPSG2193YXWriteTo4326() {
    // input is shapefile in 4326 by with a non standard YX axis order. The axis order is in the .prj
    // file so should be respected by RiskScape
    useInput("point-epsg2193-with-prj-axis-order");
    saveAs("shapefile");
    useModel("reproject");
    targetCrs("EPSG:4326");

    run();
    assertCrs(SRIDSet.EPSG4326_LONLAT, readOutputPrj());

    assertThat(readResultsAsCsv("output.shp"), contains(
        EXPECTED_POINT_DATA_LON_LAT_FROM_EPSG2193, is("1")
    ));
  }

  @Test
  public void canReadInEPSG2193YXNoAxisInPrjWriteTo4326() {
    // input is shapefile in 4326 by with a non standard YX axis order. The axis order is not in the .prj
    // file. But the bookmark has crs-name = 'EPSG:4326' which should force the CRS the right way.
    useInput("point-epsg2193-no-prj-axis-order");
    saveAs("shapefile");
    useModel("reproject");
    targetCrs("EPSG:4326");

    run();
    assertCrs(SRIDSet.EPSG4326_LONLAT, readOutputPrj());

    assertThat(readResultsAsCsv("output.shp"), contains(
        EXPECTED_POINT_DATA_LON_LAT_FROM_EPSG2193, is("1")
    ));
  }

  private void run() {
    runCommand.modelId = model;
    runCommand.runnerOptions.format = saveAs;
    runCommand.parameters = new ArrayList<>();
    runCommand.parameters.add(String.format("input='%s'", input));
    if (targetCrs != null) {
      runCommand.parameters.add(String.format("target_crs='%s'", targetCrs));
    }

    runCommand.run();
  }

  private CoordinateReferenceSystem readOutputPrj() {
    try {
      Path prjPath = getTempDirectory().resolve("output.prj");
      String prj = Files.readAllLines(prjPath).stream()
          .collect(Collectors.joining(OsUtils.LINE_SEPARATOR));
      return CRS.parseWKT(prj);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  private void assertOutputWKT(String outputFile, List<String> expected) {
    // we check the results by using the outputFile as input to the `read` model and saving
    // the results as CSV. This makes it a little bit easier to verify the results as text.
    reset();

    useModel("read");
    useInput(getTempDirectory().resolve(outputFile).toString());
    saveAs("csv");
    run();

    assertThat(readOutputCsv(), is(expected));
  }

  private List<String> readResultsAsCsv(String outputFile) {
    reset();

    useModel("read");
    useInput(getTempDirectory().resolve(outputFile).toString());
    saveAs("csv");
    run();

    return readOutputCsv();
  }

  private void assertCrs(CoordinateReferenceSystem expected, CoordinateReferenceSystem found) {
    assertTrue(CRS.equalsIgnoreMetadata(expected, found));
    assertEquals(CRS.AxisOrder.EAST_NORTH, CRS.getAxisOrder(found));
  }

  private List<String> readOutputCsv() {
    try {
      return openCsv("output.csv", "the_geom", "id").get(0);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  private void useInput(String newInput) {
    this.input = newInput;
  }

  private void useModel(String newModel) {
    this.model = newModel;
  }

  private void saveAs(String newFormat) {
    this.saveAs = newFormat;
  }

  private void targetCrs(String crs) {
    this.targetCrs = crs;
  }

}
