/*
 * 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.geo;

import static nz.org.riskscape.engine.Assert.*;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import static nz.org.riskscape.engine.Matchers.*;

import java.util.Optional;

import org.geotools.geometry.jts.ReferencedEnvelope;
import org.junit.Test;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.expr.StructMemberAccessExpression;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Referenced;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.StandardCodes;

public class IntersectionIndexTest extends ProjectTest {

  private IntersectionIndex.Options options = new IntersectionIndex.Options();

  GeometryHelper nzGeometryHelper = GeometryHelper.nzTransverseMercatorWithOriginShift(project.getSridSet());
  GeometryHelper latLongGeometryHelper = GeometryHelper.latLong(project.getSridSet());

  Point aucklandLatLong = latLongGeometryHelper.point(-36, 175.5);
  Point wellingtonLatLong = latLongGeometryHelper.point(-41, 175);
  Point sydneyLatLong = latLongGeometryHelper.point(-33, 151);

  @Test
  public void canIndexGeometriesInNestedTuples() throws Exception {
    Struct itemType = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT);
    Struct indexedType = Struct.of("value", itemType);

    StructMemberAccessExpression geomAccessor = StructMemberAccessExpression.build(indexedType,
        Lists.newArrayList("value", "geom")).getOrThrow();

    Tuple auckland = Tuple.ofValues(indexedType, Tuple.ofValues(itemType, aucklandLatLong, "auckland"));
    Tuple wellington = Tuple.ofValues(indexedType, Tuple.ofValues(itemType, wellingtonLatLong, "wellington"));

    IntersectionIndex index = new IntersectionIndex(geomAccessor, project.getSridSet(), options);
    index.insert(wellington);
    index.insert(auckland);

    assertThat(index.findPointIntersections(wellingtonLatLong), contains(wellington));

    assertThat(index.findPointIntersections(sydneyLatLong), hasSize(0));

    assertThat(index.size(), is(2));
  }

  @Test
  public void canIndexPointWithCutBeforeAddingEmpty() throws Exception {
    Struct itemType = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT);
    Struct indexedType = Struct.of("value", itemType);

    StructMemberAccessExpression geomAccessor = StructMemberAccessExpression.build(indexedType,
        Lists.newArrayList("value", "geom")).getOrThrow();

    Tuple auckland = Tuple.ofValues(indexedType, Tuple.ofValues(itemType, aucklandLatLong, "auckland"));
    Tuple wellington = Tuple.ofValues(indexedType, Tuple.ofValues(itemType, wellingtonLatLong, "wellington"));

    // empty lets the index choose to cut of not based on geom type
    options.setCutBeforeAdding(Optional.empty());

    IntersectionIndex index = new IntersectionIndex(geomAccessor, project.getSridSet(), options);
    index.insert(wellington);
    index.insert(auckland);

    assertThat(index.findPointIntersections(wellingtonLatLong), contains(wellington));

    assertThat(index.findPointIntersections(sydneyLatLong), hasSize(0));

    assertThat(index.size(), is(2));
  }

  @Test
  public void cuttingFailsOnMixedGeometryTypes() throws Exception {
    Struct itemType = Struct.of("geom", Types.GEOMETRY, "value", Types.TEXT);
    Struct indexedType = Struct.of("value", itemType);

    StructMemberAccessExpression geomAccessor = StructMemberAccessExpression.build(indexedType,
        Lists.newArrayList("value", "geom")).getOrThrow();

    Polygon aucklandPolygon = latLongGeometryHelper.box(-36, 175.5, -36.5, 175.6);
    Tuple aucklandWithPolygon = Tuple.ofValues(indexedType, Tuple.ofValues(itemType, aucklandPolygon, "auckland"));
    Tuple wellingtonWithPoint = Tuple.ofValues(indexedType, Tuple.ofValues(itemType, wellingtonLatLong, "wellington"));

    // empty lets the index choose to cut or not based on first seen geom type
    options.setCutBeforeAdding(Optional.empty());

    IntersectionIndex index = new IntersectionIndex(geomAccessor, project.getSridSet(), options);
    // auckland contains a polygon, which will set the index up to cut geometries
    index.insert(aucklandWithPolygon);
    // now if we insert a non-polygon the cut will blow up.
    assertThat(
        assertThrows(RiskscapeException.class, () -> index.insert(wellingtonWithPoint)).getProblem(),
        hasAncestorProblem(is(IntersectionIndex.PROBLEMS.intersectionCutNotSupportedHint(GeometryFamily.PUNTAL)))
    );
  }

  @Test
  public void canIndexGeometriesSkippingNulls() throws Exception {
    Struct itemType = Struct.of("geom", Nullable.GEOMETRY, "value", Types.TEXT);
    Struct indexedType = Struct.of("value", itemType);

    StructMemberAccessExpression geomAccessor = StructMemberAccessExpression.build(indexedType,
        Lists.newArrayList("value", "geom")).getOrThrow();

    Tuple auckland = Tuple.ofValues(indexedType, Tuple.ofValues(itemType, aucklandLatLong, "auckland"));
    Tuple wellington = Tuple.ofValues(indexedType, Tuple.ofValues(itemType, wellingtonLatLong, "wellington"));

    IntersectionIndex index = new IntersectionIndex(geomAccessor, project.getSridSet(), options);
    index.insert(wellington);
    index.insert(auckland);

    // sanity check that index is working
    assertThat(index.findPointIntersections(wellingtonLatLong), contains(wellington));
    assertThat(index.findPointIntersections(sydneyLatLong), hasSize(0));

    // now insert some tuples with null geometry.
    index.insert(Tuple.ofValues(indexedType, Tuple.ofValues(itemType, null, "nowhere")));
    index.insert(Tuple.ofValues(indexedType, Tuple.ofValues(itemType, null, "nowhere at all")));

    // and make sure index is still working okay
    assertThat(index.findPointIntersections(wellingtonLatLong), contains(wellington));
    assertThat(index.findPointIntersections(sydneyLatLong), hasSize(0));
  }

  @Test
  public void canBuildFromRelationAndReprojectIfSafe() throws ProblemException {
    Type lhsGeomType = Referenced.of(Types.POINT, nzGeometryHelper.getCrs());
    Struct rhsType = Struct.of(
        "geom", Referenced.of(Types.POINT, latLongGeometryHelper.getCrs(),
            new ReferencedEnvelope(-41, -36, 175, 175.5, latLongGeometryHelper.getCrs())),
        "value", Types.TEXT);
    ListRelation relation = new ListRelation(rhsType,
        Tuple.ofValues(rhsType, wellingtonLatLong, "wellington"),
        Tuple.ofValues(rhsType, aucklandLatLong, "auckland")
    );

    IntersectionIndex index = IntersectionIndex.populateFromRelation(relation, lhsGeomType, project.getSridSet(),
        options);
    assertThat(index.findPointIntersections((Point)nzGeometryHelper.reproject(wellingtonLatLong)), contains(
        Tuple.ofValues(rhsType, nzGeometryHelper.reproject(wellingtonLatLong), "wellington")
    ));
    assertThat(index.findPointIntersections((Point)nzGeometryHelper.reproject(aucklandLatLong)), contains(
        Tuple.ofValues(rhsType, nzGeometryHelper.reproject(aucklandLatLong), "auckland")
    ));
  }

  @Test
  public void canBuildFromRelationNoReprojectionIfNotSafe() throws ProblemException{
    Type lhsGeomType = Referenced.of(Types.POINT, nzGeometryHelper.getCrs());
    Struct rhsType = Struct.of(
        "geom", Referenced.of(Types.POINT, latLongGeometryHelper.getCrs(),
            new ReferencedEnvelope(-41, -33, 151, 175.5, latLongGeometryHelper.getCrs())),
        "value", Types.TEXT);
    ListRelation relation = new ListRelation(rhsType,
        Tuple.ofValues(rhsType, wellingtonLatLong, "wellington"),
        Tuple.ofValues(rhsType, aucklandLatLong, "auckland"),
        Tuple.ofValues(rhsType, sydneyLatLong, "sydney")
    );

    IntersectionIndex index = IntersectionIndex.populateFromRelation(relation, lhsGeomType, project.getSridSet(),
        options);
    assertThat(index.findPointIntersections(wellingtonLatLong), contains(
        Tuple.ofValues(rhsType,wellingtonLatLong, "wellington")
    ));
    assertThat(index.findPointIntersections(aucklandLatLong), contains(
        Tuple.ofValues(rhsType, aucklandLatLong, "auckland")
    ));
    assertThat(index.findPointIntersections(sydneyLatLong), contains(
        Tuple.ofValues(rhsType, sydneyLatLong, "sydney")
    ));
  }

  @Test
  public void emptyIndexReturnsNoResults() throws ProblemException{
    Type lhsGeomType = Referenced.of(Types.POINT, nzGeometryHelper.getCrs());
    Struct rhsType = Struct.of(
        "geom", Referenced.of(Types.POINT, latLongGeometryHelper.getCrs(),
            new ReferencedEnvelope(-41, -33, 151, 175.5, latLongGeometryHelper.getCrs())),
        "value", Types.TEXT);
    ListRelation relation = new ListRelation(rhsType);

    IntersectionIndex index = IntersectionIndex.populateFromRelation(relation, lhsGeomType, project.getSridSet(),
        options);

    assertThat(index.findPointIntersections(wellingtonLatLong), hasSize(0));
    assertThat(index.findIntersections(wellingtonLatLong), hasSize(0));
    assertThat(index.findDifferenceAndIntersections(wellingtonLatLong).getRight(), hasSize(0));
    assertThat(index.findIntersectingValues(wellingtonLatLong), hasSize(0));
  }

  @Test
  public void cannotBuildFromRelationWithNoGeometry() {
    Type lhsGeomType = Referenced.of(Types.POINT, nzGeometryHelper.getCrs());
    Struct rhsType = Struct.of(
        "value", Types.TEXT);
    ListRelation relation = new ListRelation(rhsType,
        Tuple.ofValues(rhsType, "wellington"),
        Tuple.ofValues(rhsType, "auckland"),
        Tuple.ofValues(rhsType, "sydney")
    );

    ProblemException ex = assertThrows(ProblemException.class,
        () -> IntersectionIndex.populateFromRelation(relation, lhsGeomType, project.getSridSet(),
            options));
    assertThat(ex.getProblems(), contains(
        Problem.error(StandardCodes.GEOMETRY_REQUIRED, relation.getType())
    ));
  }

}
