/*
 * 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.List;
import java.util.Set;

import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;

import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.GeometryProblems;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.cli.ExitException;
import nz.org.riskscape.engine.data.InputDataProblems;
import nz.org.riskscape.engine.pipeline.PipelineProblems;
import nz.org.riskscape.engine.problem.ProblemMatchers;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problem.Severity;

public class ValidateGeometryTests extends BaseModelRunCommandTest {

  WKTReader reader = new WKTReader();
  Polygon invalidPolygon;
  LineString validLinestring;
  Point invalidPoint;

  @Before
  public void createGeoms() throws ParseException {
    invalidPolygon = (Polygon) reader.read("POLYGON((10 10, 20 20, 10 20, 20 10, 10 10))");
    validLinestring = (LineString) reader.read("LINESTRING(10 10, 20 20, 10 20, 20 10, 10 10)");
    invalidPoint = (Point) reader.read("POINT (10 NaN)");
  }

  public void setup(String projectName) {
    assertThat(populateProjectAndSetupCommands(stdhome().resolve(projectName)).getProblems(), empty());
    evalCommand.pipelineFile= "-";
    evalCommand.runnerOptions.format = "csv";
  }

  @Test
  public void geometryValidationCanBeTurnedOff() throws Exception {
    setup("project-off.ini");
    setCommandInput("input('unfixable') -> select(id)");

    assertNull(evalCommand.run());

    Set<List<String>> rows = openCsvUniqueData("select.csv", "id");

    assertThat(
      rows,
      containsInAnyOrder(
        hasItems("1")
      )
    );

    assertThat(collectedSinkProblems, empty());
    assertThat(new String(errBytes.toByteArray()), equalTo(""));
  }

  @Test
  public void bookmarkWillFixInvalidGeometryWhenValidationOnWarn() throws Exception {
    setup("project-warn.ini");
    doFixInvalidPipeline("input('polygon') -> select(id) as output",
        Matchers.isProblem(Severity.WARNING, GeometryProblems.class, "fixedInvalid"));
  }

  @Test
  public void bookmarkWillFixInvalidGeometryWhenValidationOnError() throws Exception {
    setup("project-error.ini");
    doFixInvalidPipeline("input('polygon') -> select(id) as output",
        Matchers.isProblem(Severity.WARNING, GeometryProblems.class, "fixedInvalid"));
  }

  @Test
  public void bookmarkWillFixInvalidGeometryWithDefaultSettings() throws Exception {
    setup("project.ini");
    doFixInvalidPipeline("input('polygon') -> select(id) as output",
        Matchers.isProblem(Severity.WARNING, GeometryProblems.class, "fixedInvalid"));
  }

  @Test
  public void reprojectionWillFixInvalidGeometryWhenValidationOnWarn() throws Exception {
    setup("project-warn.ini");
    // polygon-validate-off has validate-geometry turned off. this makes it easy to give the reproject
    // a fixable geometry
    doFixInvalidPipeline("input('polygon-validate-off') -> select({id, reproject(the_geom, 'EPSG:4326')}) as output",
        Matchers.isProblem(Severity.WARNING, GeometryProblems.class, "fixedInvalidPostReprojection"));
  }

  @Test
  public void reprojectionWillFixInvalidGeometryWhenValidationOnError() throws Exception {
    setup("project-error.ini");
    // polygon-validate-off has validate-geometry turned off. this makes it easy to give the reproject
    // a fixable geometry
    doFixInvalidPipeline("input('polygon-validate-off') -> select({id, reproject(the_geom, 'EPSG:4326')}) as output",
        Matchers.isProblem(Severity.WARNING, GeometryProblems.class, "fixedInvalidPostReprojection"));
  }

  @Test
  public void reprojectionWillFixInvalidGeometryWithDefaultSettings() throws Exception {
    setup("project.ini");
    // polygon-validate-off has validate-geometry turned off. this makes it easy to give the reproject
    // a fixable geometry
    doFixInvalidPipeline("input('polygon-validate-off') -> select({id, reproject(the_geom, 'EPSG:4326')}) as output",
        Matchers.isProblem(Severity.WARNING, GeometryProblems.class, "fixedInvalidPostReprojection"));
  }

  private void doFixInvalidPipeline(String pipeline, Matcher<Problem> expectedProblemMatcher) throws Exception {
    setCommandInput(pipeline);

    assertNull(evalCommand.run());

    List<List<String>> rows = readCsvColumns("output.csv", "id");

    // data is still there in the output
    assertThat(
      rows,
      containsInAnyOrder(
        hasItems(equalTo("1"))
      )
    );

    // fix warning is output
    assertThat(collectedSinkProblems, contains(
        Matchers.hasAncestorProblem(expectedProblemMatcher)
    ));
  }

  @Test
  public void invalidGeometryAtSourceCanCauseWarningsGlobally() throws Exception {
    setup("project-warn.ini");
    setCommandInput("input('unfixable') -> select(id)");

    assertNull(evalCommand.run());

    Set<List<String>> rows = openCsvUniqueData("select.csv", "id");

    assertThat(
      rows,
      containsInAnyOrder(
        hasItems(equalTo("1"))
      )
    );

    assertThat(collectedSinkProblems, hasSize(1));

    Problem actualProblem = collectedSinkProblems.get(0).getChildren().get(0);
    Problem expectedProblem = GeometryProblems.get().invalid(invalidPoint, null, "");
    // can't use matcher - top error doesn't have an equality method (d'oh)
    assertEquals(expectedProblem.getCode(), actualProblem.getCode());
    // testing geometry equality doesn't work with the invalid point because that works by
    // calculating the distance between the two points. But that distance calc won't work with a NaN
    // in the coordinate
    Point problemPoint = (Point)actualProblem.getArguments()[0];
    assertThat(problemPoint.getX(), is(invalidPoint.getX()));
    assertThat(problemPoint.getY(), is(invalidPoint.getY()));
  }

  @Test
  public void invalidGeometryAtSourceCanCauseErrorsGlobally() throws Exception {
    setup("project-error.ini");
    setCommandInput("input('unfixable') -> select(id)");

    ExitException thrown = Assert.assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(
      thrown.getProblem(),
      allOf(
        ProblemMatchers.problemsInTree(
          equalTo(PipelineProblems.get().executionFailed()),
          equalTo(InputDataProblems.get().invalidTupleError())
        )
      )
    );
  }

  @Test
  public void invalidGeometryPostReprojectCanCauseWarningsGlobally() throws Exception {
    setup("project-warn.ini");
    setCommandInput(
        "input('unfixable-flag-on-a-pole') -> select({id, reproject(the_geom, 'EPSG:2193')}) -> select(id) as output");

    assertNull(evalCommand.run());

    Set<List<String>> rows = openCsvUniqueData("output.csv", "id");

    // data is still there in the output
    assertThat(
      rows,
      containsInAnyOrder(
        hasItems(equalTo("1"))
      )
    );

    // check the error came out - NB using code matcher as CRS matching is a PITA on problems
    assertThat(
      collectedSinkProblems,
      contains(
        Matchers.isProblem(Severity.WARNING, GeometryProblems.class, "invalidPostReprojection")
      )
    );
  }

  @Test
  public void invalidGeometryPostReprojectCanCauseErrorsGlobally() throws Exception {
    setup("project-error.ini");
    setCommandInput(
        "input('unfixable-flag-on-a-pole') -> select({id, reproject(the_geom, 'EPSG:2193')}) -> select(id) as output");

    ExitException thrown = Assert.assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(
      thrown.getProblem(),
      allOf(
        ProblemMatchers.problemsInTree(
          equalTo(PipelineProblems.get().executionFailed()),
          ProblemMatchers.isProblem(GeometryProblems.class, (t, f) -> f.invalidPostReprojection(t.any(), t.any()))
        )
      )
    );
  }

  @Test
  public void invalidGeometryCanBeDetectedPerBookmark() throws Exception {
    setup("project.ini");
    setCommandInput("input(bookmark('unfixable', options: {validate-geometry: 'warn'})) -> select(id)");

    assertNull(evalCommand.run());

    Set<List<String>> rows = openCsvUniqueData("select.csv", "id");

    assertThat(
      rows,
      containsInAnyOrder(
        hasItems(equalTo("1"))
      )
    );

    assertThat(collectedSinkProblems, hasSize(1));

    Problem actualProblem = collectedSinkProblems.get(0).getChildren().get(0);
    Problem expectedProblem = GeometryProblems.get().invalid(invalidPoint, null, "");
    // can't use matcher - top error doesn't have an equality method (d'oh)
    assertEquals(expectedProblem.getCode(), actualProblem.getCode());
    // testing geometry equality doesn't work with the invalid point because that works by
    // calculating the distance between the two points. But that distance calc won't work with a NaN
    // in the coordinate
    Point problemPoint = (Point)actualProblem.getArguments()[0];
    assertThat(problemPoint.getX(), is(invalidPoint.getX()));
    assertThat(problemPoint.getY(), is(invalidPoint.getY()));
  }

  @Test
  public void invalidGeometryCanCauseErrorsGlobally() throws Exception {
    setup("project-error.ini");
    setCommandInput("input('unfixable') -> select(id)");

    ExitException thrown = Assert.assertThrows(ExitException.class, () -> evalCommand.run());
    assertThat(
      thrown.getProblem(),
      allOf(
        ProblemMatchers.problemsInTree(
          equalTo(PipelineProblems.get().executionFailed()),
          equalTo(InputDataProblems.get().invalidTupleError())
        )
      )
    );
  }

  @Test
  public void invalidGeometryCanCauseErrorsButBeSkipped() throws Exception {
    setup("project-error.ini");
    setCommandInput("input(bookmark('unfixable', options: {skip-invalid: 'true'})) -> select(id)");

    // no errors
    assertNull(evalCommand.run());
    // file gets written (but will be empty)
    assertThat(new String(outBytes.toByteArray()), endsWith("select.csv\n"));

    assertThat(
      collectedSinkProblems,
      contains(
        Matchers.hasAncestorProblem(
          // it's an error, but parent is (should be) a warning
          Matchers.isProblem(Severity.ERROR, GeometryProblems.class, "invalid")
        )
      )
    );
  }

}
