/*
 * 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 static org.mockito.Mockito.*;
import java.util.List;
import java.util.Optional;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.junit.Test;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.gt.GeometryHelper;
import nz.org.riskscape.engine.GeometryProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.data.coverage.SpatialRelationTypedCoverage;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.function.UnaryFunction;
import nz.org.riskscape.engine.GeoHelper;
import nz.org.riskscape.engine.data.BookmarkProblems;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.lang.NullOf;
import nz.org.riskscape.engine.relation.EmptyRelation;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.rl.BaseExpressionRealizerTest;
import nz.org.riskscape.engine.rl.RealizableFunction;
import nz.org.riskscape.engine.rl.RealizationContext;
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.RelationType;
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.ProblemSink;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

public class BoundsTest extends BaseExpressionRealizerTest {
  GeometryHelper nzmgGeometryHelper = GeometryHelper.nzMapGridWithOriginShift(project.getSridSet());
  Bounds subject = new Bounds();
  GeometryHelper nzGeometryHelper = GeometryHelper.nzTransverseMercatorWithOriginShift(project.getSridSet());
  public BoundsTest() {
    project.getFunctionSet().add(subject.identified("bounds"));
    project.getFunctionSet().add(new NullOf().identified("null_of"));
  }

  @Test
  public void cannotGetBoundsFromReferencedGeometry() {
    // If you could call bounds(geom) users would probably expect the bounds of the geometry argument,
    // not the bound of the geometry type.
    Type geomType = Referenced.of(Types.GEOMETRY, nzmgGeometryHelper.getCrs(), nzmgEnvelope(1, 1, 2, 2));
    Struct inputType = Struct.of("value", geomType);

    realize(inputType, parse("bounds(value)"));
    assertThat(realizationProblems, contains(
        hasAncestorProblem(is(ArgsProblems.mismatch(subject.getArguments().get(0), geomType)))
    ));
  }

  @Test
  public void canGetBoundsFromReferencedRelationType() {
    // as long as the expression is constant, we can just get the bounds from the Referenced type
    Struct itemType = Struct.of("geometry",Types.GEOMETRY, "value", Types.INTEGER);
    Type relationType = Referenced.of(
        new RelationType(itemType), nzmgGeometryHelper.getCrs(), nzmgEnvelope(1, 1, 2, 2));
    // add a numpty function to return a Referenced relation type as a constant expression
    RiskscapeFunction foo = new UnaryFunction<Object>(Types.ANYTHING, relationType, x -> new EmptyRelation(itemType));
    project.getFunctionSet().add(foo.identified("foo"));

    assertThat((Geometry) evaluate("bounds(foo(0))", Tuple.EMPTY_TUPLE),
        GeoHelper.geometryTopoMatch(nzmgGeometryHelper.box(1, 1, 2, 2)));
  }

  @Test
  public void canGetBoundsFromBookmarkIdReturningReferencedRelation() {
    // as long as the expression is constant, we can just get the bounds from the Referenced type
    Struct itemType = Struct.of("geometry",Types.GEOMETRY, "value", Types.INTEGER);
    Type relationType = Referenced.of(
        new RelationType(itemType), nzmgGeometryHelper.getCrs(), nzmgEnvelope(1, 1, 2, 2));
    // we need to add a bookmark function to return the relation
    RiskscapeFunction bookmarkFunction = new UnaryFunction<>(Types.ANYTHING, relationType, arg1 -> {
      if (! arg1.equals("foo")) {
        throw new RuntimeException("boom");
      }
      return new EmptyRelation(itemType);
    });
    project.getFunctionSet().add(bookmarkFunction.identified("bookmark"));

    assertThat((Geometry) evaluate("bounds('foo')", Tuple.EMPTY_TUPLE),
        GeoHelper.geometryTopoMatch(nzmgGeometryHelper.box(1, 1, 2, 2)));
  }

  @Test
  public void canGetBoundsFromConstantUnreferencedRelation() {
    // the expression is constant, but the Referenced type doesn't have any bounds
    Struct itemType = Struct.of("geometry",Types.GEOMETRY, "value", Types.INTEGER);
    Type relationType = Referenced.of(new RelationType(itemType), nzmgGeometryHelper.getCrs());
    // add a numpty function to return a relation as a constant expression
    ListRelation relation = new ListRelation(itemType,
        Tuple.ofValues(itemType, nzGeometryHelper.point(0, 0), 1L),
        Tuple.ofValues(itemType, nzGeometryHelper.point(150, 50), 2L))
        .inferSpatialMetadata(project);

    RiskscapeFunction foo = new UnaryFunction<Object>(Types.ANYTHING, relationType, x -> relation);
    project.getFunctionSet().add(foo.identified("foo"));

    assertThat((Geometry) evaluate("bounds(foo(0))", Tuple.EMPTY_TUPLE),
        GeoHelper.geometryTopoMatch(nzGeometryHelper.box(0, 0, 150, 50)));
  }

  @Test
  public void canGetBoundsFromCoverageType() {
    Struct pointType = Struct.of("geometry",Types.GEOMETRY, "value", Types.INTEGER);
    ListRelation relation = new ListRelation(pointType,
        Tuple.ofValues(pointType, nzGeometryHelper.point(0, 0), 1L),
        Tuple.ofValues(pointType, nzGeometryHelper.point(50, 50), 2L));
    TypedCoverage coverage = SpatialRelationTypedCoverage.of(relation, project.getSridSet(), ProblemSink.DEVNULL)
        .get();
    Tuple coverageInput = Tuple.ofValues(Struct.of("coverage", new CoverageType(Types.INTEGER)), coverage);

    assertThat((Geometry) evaluate("bounds(coverage)", coverageInput),
        GeoHelper.geometryTopoMatch(nzGeometryHelper.box(0, 0, 50, 50)));
  }

  @Test
  public void canGetBoundsFromBookmarkIdReturningCoverageType() {
    Struct pointType = Struct.of("geometry", Types.GEOMETRY, "value", Types.INTEGER);
    ListRelation relation = new ListRelation(pointType,
        Tuple.ofValues(pointType, nzGeometryHelper.point(0, 0), 1L),
        Tuple.ofValues(pointType, nzGeometryHelper.point(50, 50), 2L));
    TypedCoverage coverage = SpatialRelationTypedCoverage.of(relation, project.getSridSet(), ProblemSink.DEVNULL)
        .get();
    // we need to add a bookmark function to return the relation
    RiskscapeFunction bookmarkFunction = new UnaryFunction<>(Types.ANYTHING, new CoverageType(Types.INTEGER),
        arg1 -> {
          if (!arg1.equals("coverage1")) {
            throw new RuntimeException("boom");
          }
          return coverage;
        });
    project.getFunctionSet().add(bookmarkFunction.identified("bookmark"));

    assertThat((Geometry) evaluate("bounds('coverage1')", Tuple.EMPTY_TUPLE),
        GeoHelper.geometryTopoMatch(nzGeometryHelper.box(0, 0, 50, 50)));
  }

  @Test
  public void canGetBoundsFromRelationIfReferencedMissingBounds() {
    // Calculating bounds can be expensive so might be delayed until they are required.
    Struct itemType = Struct.of("geom", Referenced.of(Types.GEOMETRY, nzmgGeometryHelper.getCrs()),
        "value", Types.INTEGER);
    Relation relation = mock(ListRelation.class);
    ReferencedEnvelope mockEnv = nzmgEnvelope(10, 10, 20, 20);
    when(relation.calculateBounds()).thenReturn(Optional.of(mockEnv));

    Struct inputType = Struct.of("value", Referenced.of(new RelationType(itemType), nzmgGeometryHelper.getCrs()));

    Tuple input = Tuple.ofValues(inputType, relation);
    assertThat((Geometry) evaluate("bounds(value)", input),
        GeoHelper.geometryTopoMatch(nzmgGeometryHelper.box(10, 10, 20, 20)));
  }

  @Test
  public void getNullIfCoverageHasNoEnvelope() {
    TypedCoverage mockCoverage = mock(TypedCoverage.class);
    when(mockCoverage.getEnvelope()).thenReturn(Optional.empty());

    // when referenced type does not have bounds and is not a relation type there is no way to
    // calculate them from the type system
    Struct inputType = Struct.of("coverage", new CoverageType(Types.INTEGER));
    Tuple input = Tuple.ofValues(inputType, mockCoverage);
    assertNull(evaluate("bounds(coverage)", input));
  }

  @Test
  public void failsWhenInputNotReferenced() {
    Type itemType = new RelationType(Struct.EMPTY_STRUCT);
    Struct inputType = Struct.of("value", itemType);

    realize(inputType, parse("bounds(value)"));
    assertThat(realizationProblems, contains(
        hasAncestorProblem(is(GeometryProblems.get().notReferenced(itemType)))
    ));
  }

  @Test
  public void failsWhenBookmarkIdReturnsNotReferenced() {
    Type relationType = new RelationType(Struct.EMPTY_STRUCT);
    // we need to add a bookmark function to return the relation
    RiskscapeFunction bookmarkFunction = new UnaryFunction<>(Types.ANYTHING, relationType, arg1 -> {
      if (! arg1.equals("foo")) {
        throw new RuntimeException("boom");
      }
      return new EmptyRelation(Struct.of("value", relationType));
    });
    project.getFunctionSet().add(bookmarkFunction.identified("bookmark"));

    realize(Struct.EMPTY_STRUCT, parse("bounds('foo')"));
    assertThat(realizationProblems, contains(
        hasAncestorProblem(is(GeometryProblems.get().notReferenced(relationType)))
    ));
  }

  @Test
  public void failsWhenBookmarkIdNotValid() {
    // bookmark('foo') will fail to realize if foo is not a known bookmark id (or file path)
    // so we emulate that with our dummy bookmark function
    RiskscapeFunction bookmarkFunction = RealizableFunction.asFunction(
        new RealizableFunction() {
      @Override
      public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context,
          FunctionCall functionCall, List<Type> argumentTypes) {
        return ResultOrProblems.failed(BookmarkProblems.get().notBookmarkOrFile("foo"));
      }
    },
        ArgumentList.create("id", Types.TEXT), Types.ANYTHING
    );
    project.getFunctionSet().add(bookmarkFunction.identified("bookmark"));

    realize(Struct.EMPTY_STRUCT, parse("bounds('foo')"));
    assertThat(realizationProblems, contains(
        hasAncestorProblem(is(BookmarkProblems.get().notBookmarkOrFile("foo")))
    ));
  }

  @Test
  public void failsWhenBookmarkIdIsNull() {
    // bookmark requires a non-null string
    // so if null is provided the the bookmark convenience is not used and we get a type mismatch
    // we have a test if this because in previously evaluateConstant would fail with an unexpected exception
    // in this case.
    realize(Struct.EMPTY_STRUCT, parse("bounds(null_of('text'))"));
    assertThat(realizationProblems, contains(
        hasAncestorProblem(is(ArgsProblems.mismatch(subject.getArguments().get(0), Nullable.TEXT)))
    ));
  }

  private ReferencedEnvelope nzmgEnvelope(double minX, double minY, double maxX, double maxY) {
    // we use nzmgGeometryHelper to make min/max as that will apply offsets
    Point min = nzmgGeometryHelper.point(minX, minY);
    Point max = nzmgGeometryHelper.point(maxX, maxY);

    ReferencedEnvelope envelope = new ReferencedEnvelope(nzmgGeometryHelper.getCrs());

    envelope.expandToInclude(min.getCoordinate());
    envelope.expandToInclude(max.getCoordinate());

    return envelope;
  }
}
