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

import static nz.org.riskscape.engine.Matchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.geotools.geometry.jts.ReferencedEnvelope;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.locationtech.jts.geom.Point;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.NoSuchMemberException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.data.coverage.IndexedTypedCoverage;
import nz.org.riskscape.engine.data.coverage.NearestNeighbourCoverage;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.rl.agg.BaseAggregationFunctionTest;
import nz.org.riskscape.engine.types.CoercionException;
import nz.org.riskscape.engine.types.CoverageType;
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.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

@SuppressWarnings("unchecked")
@RunWith(Parameterized.class)
public class ToTypedCoverageTest extends BaseAggregationFunctionTest {

  private final GeometryHelper nzGeomHelper = GeometryHelper.nzMapGridWithOriginShift(project.getSridSet());

  @Parameters
  public static List<String> getItemTypes() {
    /*
     * We run these tests twice - once where the CRS is in the type and once where it isn't (instead it's in the srid
     * of the geometry)
     */
    return List.of("referenced", "unreferenced");
  }

  private final ToTypedCoverage subject = new ToTypedCoverage();
  FunctionCall functionCall = expressionParser.parse("foo(value)")
      .isA(FunctionCall.class)
      .orElse(null);

  final Struct itemType;
  final Struct inputType;

  final Tuple tupleOne;
  final Tuple tupleTwo;

  final Tuple pointTupleOne;
  final Tuple pointTupleTwo;

  public ToTypedCoverageTest(String itemTypeParameter) {
    assertSerialAndParallelEqual = false;

    if (itemTypeParameter.equals("referenced")) {
      itemType = Struct.of(
          "geom", Nullable.of(Referenced.of(Types.GEOMETRY, nzGeomHelper.getCrs())),
          "name", Types.TEXT
        );
    } else {
      itemType = Struct.of(
        "geom", Nullable.of(Types.GEOMETRY),
        "name", Types.TEXT
      );
    }

    inputType = Struct.of("value", Nullable.of(itemType));

    tupleOne = Tuple.ofValues(itemType, nzGeomHelper.box(0, 0, 10, 10), "one");
    tupleTwo = Tuple.ofValues(itemType, nzGeomHelper.box(5, 5, 15, 15), "two");

    pointTupleOne = Tuple.ofValues(itemType, nzGeomHelper.point(100, 100), "point one");
    pointTupleTwo = Tuple.ofValues(itemType, nzGeomHelper.point(100, 200), "point two");
  }

  @Test
  public void canAggregateSpatialValuesToCoverage() throws Exception {
    tuples = Lists.newArrayList(Tuple.ofValues(inputType, tupleOne),
        Tuple.ofValues(inputType, tupleTwo)
    );

    // only in the case that the geom is referenced
    itemType.getEntry("geom").getType().find(Referenced.class).ifPresent(refType -> {
      assertThat(refType.getCrs(), equalTo(nzGeomHelper.getCrs()));
    });

    realized = subject.realize(realizationContext, inputType, functionCall).get();

    // accumulator with no values is empty
    assertTrue(realized.newAccumulator().isEmpty());

    // processors return inputType expression's return inputType, but
    assertEquals(new CoverageType(itemType), realized.getResultType());

    // result is returned from the processor verbatim
    TypedCoverage coverage = (TypedCoverage) process();
    assertNotNull(coverage);
    assertThat(coverage, instanceOf(IndexedTypedCoverage.class));
    assertThat(asCoverage(serialResult).evaluate(nzGeomHelper.point(2, 2)), is(tupleOne));
    assertThat(asCoverage(serialResult).evaluate(nzGeomHelper.point(12, 12)), is(tupleTwo));

    assertThat(asCoverage(parallelResult).evaluate(nzGeomHelper.point(2, 2)), is(tupleOne));
    assertThat(asCoverage(parallelResult).evaluate(nzGeomHelper.point(12, 12)), is(tupleTwo));

    assertThat(
        coverage.getCoordinateReferenceSystem(),
        equalTo(nzGeomHelper.getCrs())
    );

    assertThat(
        coverage.getEnvelope(),
        equalTo(Optional.of(
          new ReferencedEnvelope(nzGeomHelper.box(0, 0, 15, 15).getEnvelopeInternal(),
              coverage.getCoordinateReferenceSystem())
        ))
    );
  }

  @Test
  public void canAggregateSpatialValuesWithNullTuplesToCoverage() throws Exception {
    tuples = Lists.newArrayList(
        Tuple.ofValues(inputType, tupleOne),
        Tuple.ofValues(inputType),
        Tuple.ofValues(inputType, tupleTwo)
    );

    realized = subject.realize(realizationContext, inputType, functionCall).get();

    // accumulator with no values is empty
    assertTrue(realized.newAccumulator().isEmpty());

    // processors return inputType is expression's return inputType, but
    assertEquals(new CoverageType(itemType), realized.getResultType());

    // result is returned from the processor verbatim
    TypedCoverage coverage = (TypedCoverage) process();
    assertNotNull(coverage);
    assertThat(coverage, instanceOf(IndexedTypedCoverage.class));
    assertThat(asCoverage(serialResult).evaluate(nzGeomHelper.point(2, 2)), is(tupleOne));
    assertThat(asCoverage(serialResult).evaluate(nzGeomHelper.point(12, 12)), is(tupleTwo));

    assertThat(asCoverage(parallelResult).evaluate(nzGeomHelper.point(2, 2)), is(tupleOne));
    assertThat(asCoverage(parallelResult).evaluate(nzGeomHelper.point(12, 12)), is(tupleTwo));
  }

  @Test
  public void canAggregateLargeVolumesOfSpatialValuesToCoverage() throws Exception {
    tuples = IntStream.rangeClosed(0, 10000)
        .mapToObj(i -> Tuple.ofValues(inputType, Tuple.ofValues(itemType,
        nzGeomHelper.box(i, 0, i + 1, 1), String.valueOf(i)
    ))).collect(Collectors.toList());

    // let's be explicit in asking for an intersection coverage
    functionCall = expressionParser.parse("foo(value, options: {index: 'intersection'})")
      .isA(FunctionCall.class)
      .orElse(null);
    realized = subject.realize(realizationContext, inputType, functionCall).get();

    // accumulator with no values is empty
    assertTrue(realized.newAccumulator().isEmpty());

    // processors return inputType is expression's return inputType, but
    assertEquals(new CoverageType(itemType), realized.getResultType());

    // result is returned from the processor verbatim
    TypedCoverage coverage = (TypedCoverage) process();
    assertNotNull(coverage);
    assertThat(coverage, instanceOf(IndexedTypedCoverage.class));

    assertThat(evaluate(coverage, nzGeomHelper.point(0.5, 0.5)).toMap(), hasEntry("name", "0"));
    assertThat(evaluate(coverage, nzGeomHelper.point(5000.5, 0.5)).toMap(), hasEntry("name", "5000"));
    assertThat(evaluate(coverage, nzGeomHelper.point(10000.5, 0.5)).toMap(), hasEntry("name", "10000"));
  }

  @Test
  public void canAggregateToNearestNeighbourCoverage() {
    tuples = Lists.newArrayList(
        Tuple.ofValues(inputType, pointTupleOne),
        Tuple.ofValues(inputType, pointTupleTwo)
    );

    // let's ask for a nearest neighbour coverage
    functionCall = expressionParser
        .parse("foo(value, options: {index: 'nearest_neighbour', nearest_neighbour_max_distance: 50})")
      .isA(FunctionCall.class)
      .orElse(null);
    realized = subject.realize(realizationContext, inputType, functionCall).get();

    // accumulator with no values is empty
    assertTrue(realized.newAccumulator().isEmpty());

    // processors return inputType is expression's return inputType, but
    assertEquals(new CoverageType(itemType), realized.getResultType());

    // result is returned from the processor verbatim
    TypedCoverage coverage = (TypedCoverage) process();
    assertNotNull(coverage);
    assertThat(coverage, instanceOf(NearestNeighbourCoverage.class));

    assertThat(asCoverage(serialResult).evaluate(nzGeomHelper.point(100, 100)), is(pointTupleOne));
    assertThat(asCoverage(serialResult).evaluate(nzGeomHelper.point(51, 100)), is(pointTupleOne));
    assertThat(asCoverage(serialResult).evaluate(nzGeomHelper.point(100, 149)), is(pointTupleOne));

    assertThat(asCoverage(serialResult).evaluate(nzGeomHelper.point(100, 150)), oneOf(pointTupleOne, pointTupleTwo));

    assertThat(asCoverage(serialResult).evaluate(nzGeomHelper.point(100, 151)), is(pointTupleTwo));
  }

  @Test
  public void failsIfNoGeometry() {
    Struct myItemType = Struct.of("name", Types.TEXT, "value", Types.INTEGER);
    Struct myInputType = Struct.of("value", myItemType);

    assertThat(subject.realize(realizationContext, myInputType, functionCall), failedResult(
        hasAncestorProblem(is(TypeProblems.get().structMustHaveMemberType(Types.GEOMETRY, myItemType)))
    ));
  }

  @Test
  public void failsIfValueExpressionNoGood() {
    FunctionCall myFunctionCall = expressionParser.parse("foo(bad_value)").isA(FunctionCall.class).orElse(null);

    assertThat(subject.realize(realizationContext, itemType, myFunctionCall), failedResult(
        hasAncestorProblem(is(ExpressionProblems.get().noSuchStructMember("bad_value", itemType.getMemberKeys())))
    ));
  }

  @Test
  public void failsIfOptionsNotRecognised() {
    // there is no index called 'fast'
    FunctionCall myFunctionCall = expressionParser.parse("foo(value, options: {index: 'fast'})")
        .isA(FunctionCall.class)
        .orElse(null);

    assertThat(subject.realize(realizationContext, inputType, myFunctionCall), failedResult(
        hasAncestorProblem(isProblem(CoercionException.class))
    ));

    // missing distance
    myFunctionCall = expressionParser.parse("foo(value, options: {index: 'nearest_neighbour'})")
        .isA(FunctionCall.class)
        .orElse(null);

    assertThat(subject.realize(realizationContext, inputType, myFunctionCall), failedResult(
        hasAncestorProblem(is(GeneralProblems.get().required("nearest_neighbour_max_distance")))
    ));

    // max distance should be a number
    myFunctionCall = expressionParser
        .parse("foo(value, options: {index: 'nearest_neighbour', nearest_neighbour_max_distance: 'medium'})")
        .isA(FunctionCall.class)
        .orElse(null);

    assertThat(subject.realize(realizationContext, inputType, myFunctionCall), failedResult(
        hasAncestorProblem(isProblem(CoercionException.class))
    ));

    // unknown parameter
    myFunctionCall = expressionParser
        .parse("foo(value, options: {index: 'intersection', bogus: 'medium'})")
        .isA(FunctionCall.class)
        .orElse(null);

    assertThat(subject.realize(realizationContext, inputType, myFunctionCall), failedResult(
        hasAncestorProblem(isProblem(NoSuchMemberException.class))
    ));
  }

  Tuple evaluate(Object coverage, Point geom) {
    return (Tuple)asCoverage(coverage).evaluate(geom);
  }

  TypedCoverage asCoverage(Object value) {
    return (TypedCoverage) value;
  }
}
