/*
 * 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 org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.junit.Test;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;

import it.geosolutions.jaiext.jts.CoordinateSequence2D;
import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.GeometryMatchers;
import nz.org.riskscape.engine.cli.ExitException;
import nz.org.riskscape.engine.resource.ByteArrayCreateHandle;

public class GL483_DynamicVectorLayerBookmarks extends BaseModelRunCommandTest {

  @Test
  public void canSampleAListOfVectorLayers() throws Exception {
    runCommand.modelId = "test";
    runCommand.runnerOptions.format = "csv";

    runCommand.run();

    // layer 1 has hamilton region, layer 2 has wellington region
    List<List<String>> rows = readCsvColumns("results.csv", "filename", "point_name", "sampled");
    assertThat(
        rows,
        containsInAnyOrder(
            contains("layer-1.gpkg", "Hawke's Bay", ""),
            contains("layer-1.gpkg", "Hamilton", "Hamilton"),
            contains("layer-1.gpkg", "Wellington", ""),
            contains("layer-2.gpkg", "Hawke's Bay", ""),
            contains("layer-2.gpkg", "Hamilton", ""),
            contains("layer-2.gpkg", "Wellington", "Wellington")
        )
    );
  }

  @Test
  public void executionFailsIfWrongCrsEncountered() throws Exception {
    String layersCsvData = """
        filename
        layer-1.gpkg
        layer-2-epsg-2193.gpkg
        """;
    runCommand.modelId = "test";
    runCommand.runnerOptions.format = "csv";
    runCommand.parameters.add("layers=" + encodeCsv(layersCsvData));

    ExitException e = Assert.assertThrows(ExitException.class, () -> runCommand.run());
    assertThat(
        render(e.getProblem()),
        containsString("Expected 'Relation[{geometry=>Polygon[crs=EPSG:4326], value=>Text}][crs=EPSG:4326]' "
            + "but found 'Relation[{geometry=>Polygon[crs=EPSG:2193], value=>Text}][crs=EPSG:2193]'")
    );
  }

  @Test
  public void canComputeBoundsFromEachLayer() throws Exception {
    // this test confirms that the bounds function isn't relying on information in the type system
    runCommand.modelId = "report-bounds";
    runCommand.runnerOptions.format = "csv";

    runCommand.run();

    List<List<String>> rows = readCsvColumns("results.csv", "filename", "bounds_bookmark");

    assertThat(
        rows,
        containsInAnyOrder(
            // bounds as reported by ogrinfo
            contains(equalTo("layer-1.gpkg"), bounds(174.819918, -37.999478, 176.336687, -36.640187)),
            contains(equalTo("layer-2.gpkg"), bounds(174.587843, -41.944737, 176.577050, -40.469409))
        )
    );
  }

  private Matcher<String> bounds(double x1, double y1, double x2, double y2) {
    GeometryFactory gf = new GeometryFactory();
    Polygon rectangle = gf.createPolygon(new CoordinateSequence2D(
        x1, y1,
        x2, y1,
        x2, y2,
        x1, y2,
        x1, y1
    ));

    Matcher<Geometry> matcher = GeometryMatchers.geometryTopoMatch(rectangle, 100000);

    return new TypeSafeDiagnosingMatcher<String>(String.class) {

      @Override
      public void describeTo(Description description) {
        matcher.describeTo(description);
      }

      @Override
      protected boolean matchesSafely(String item, Description mismatchDescription) {
        Geometry geometry;
        try {
          geometry = new WKTReader().read(item);
          mismatchDescription.appendText("Not valid WKT: ").appendValue(item);
        } catch (ParseException e) {
          return false;
        }

        matcher.describeMismatch(geometry, mismatchDescription);

        return matcher.matches(geometry);
      }
    };
  }

  private String encodeCsv(String layersCsvData) {
    return ByteArrayCreateHandle.encodeData(layersCsvData, "text/csv").toString();
  }
}
