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

import static org.geotools.measure.Units.METRE;
import static tech.units.indriya.unit.Units.*;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.function.Function;

import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.IntersectionMatrix;
import org.locationtech.jts.geom.Lineal;
import org.locationtech.jts.geom.Polygonal;
import org.locationtech.jts.geom.Puntal;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;

import lombok.Getter;
import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.GeometryProblems;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.filter.FilterFactory;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.GeometryPredicateFunction;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.function.IdentifiedFunction.Category;
import nz.org.riskscape.engine.function.JavaFunction;
import nz.org.riskscape.engine.function.geometry.Bounds;
import nz.org.riskscape.engine.function.geometry.Buffer;
import nz.org.riskscape.engine.function.geometry.CentroidFunction;
import nz.org.riskscape.engine.function.geometry.CreatePoint;
import nz.org.riskscape.engine.function.geometry.GeomFromWKT;
import nz.org.riskscape.engine.function.geometry.Reproject;
import nz.org.riskscape.engine.function.geometry.ToTypedCoverage;
import nz.org.riskscape.engine.geo.GeometryAreaOp;
import nz.org.riskscape.engine.geo.GeometryLengthOp;
import nz.org.riskscape.engine.geo.GeometryUtils;
import nz.org.riskscape.engine.geo.OverlayOperations;
import nz.org.riskscape.engine.types.Floating;
import nz.org.riskscape.engine.types.Text;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.rl.ast.FunctionCall;

public class GeometryFunctions {

  public static final GeometryFactory GEOMETRY_FACTORY = new GeometryFactory();
  public static final FilterFactory FILTER_FACTORY = new FilterFactory();
  public static final OverlayOperations OVERLAY_OPERATIONS = OverlayOperations.get();

  @Getter
  public final List<IdentifiedFunction> functions;

  @Getter
  private final  List<IdentifiedFunction> predicates;

  public GeometryFunctions(Engine engine) {

    this.functions = Arrays.asList(CENTROID,
        INTERSECTION,
        new Bounds().builtin("bounds", Category.GEOMETRY_PROCESSING),
        buffer,
        new CreatePoint(),
        new GeomFromWKT().builtin("geom_from_wkt", Category.GEOMETRY_PROCESSING),
        new Reproject().asFunction().builtin("reproject", Category.GEOMETRY_PROCESSING),
        area,
        length,
        measure,
        toCoverage
    );

    this.predicates = Arrays.asList(
        newOne("intersects", (lhs, rhs) -> lhs.intersects(rhs)),
        newOne("disjoint", (lhs, rhs) -> lhs.disjoint(rhs)),
        newOne("contains", (lhs, rhs) -> lhs.contains(rhs)),
        newOne("within", (lhs, rhs) -> lhs.within(rhs)),
        newOne("touches", (lhs, rhs) -> lhs.touches(rhs)),
        newOne("crosses", (lhs, rhs) -> lhs.crosses(rhs)),
        newOne("overlaps", (lhs, rhs) -> lhs.overlaps(rhs)),
        newOne("equals", (lhs, rhs) -> lhs.equalsTopo(rhs)),
        RELATE,
        dwithin,
        beyond,
        BBOX
    );
  }

  public static final IdentifiedFunction RELATE = new GeometryPredicateFunction(
      new FunctionArgument("pattern", Types.TEXT)) {
    @Override
    protected Function<List<Object>, BiPredicate<Geometry, Geometry>> realizePredicateSupplier(
        RealizationContext context, FunctionCall functionCall, List<Type> argTypes) throws ProblemException {

      if (!argTypes.get(2).findAllowNull(Text.class).isPresent()) {
        throw new ProblemException(ArgsProblems.mismatch(arguments.get(2), argTypes.get(2)));
      }

      return (args) -> {
        String pattern = args.get(2).toString();
        return (lhs, rhs) -> {
          IntersectionMatrix matrix = lhs.relate(rhs);

          return matrix.matches(pattern);
        };
      };
    }
  }.builtin("relate", Category.GEOMETRY_LOGICAL);

  public final IdentifiedFunction dwithin = withinPredicateFunction(within -> within)
      .builtin("dwithin", Category.GEOMETRY_LOGICAL);

  public final IdentifiedFunction beyond = withinPredicateFunction(within -> ! within)
      .builtin("beyond", Category.GEOMETRY_LOGICAL);

  /**
   * @param adaptor function to change the result of calling `isWithinDistance` to the required result
   * @return a geometry predicate function that will apply a isWithinDistance predicate with the distance from
   *         the given distance argument
   */
  private GeometryPredicateFunction withinPredicateFunction(Function<Boolean, Boolean> adaptor) {
    return new GeometryPredicateFunction(new FunctionArgument("distance", Types.FLOATING)) {
      @Override
      protected Function<List<Object>, BiPredicate<Geometry, Geometry>> realizePredicateSupplier(
          RealizationContext context, FunctionCall functionCall, List<Type> argTypes) throws ProblemException {
        // the distance arg must be a float
        if (!argTypes.get(2).find(Floating.class).isPresent()) {
          throw new ProblemException(ArgsProblems.mismatch(arguments.get(2), argTypes.get(2)));
        }

        return (args) -> {
          Double distanceInput = (Double) args.get(2);
          return (lhs, rhs) -> {
            Double distance = distanceToCrsUnits(distanceInput, rhs, context.getProject().getSridSet());
            return adaptor.apply(lhs.isWithinDistance(rhs, distance));
          };
        };
      }
    };
  }
  /**
   * Converts a distance that is expected to be in metres, to the units of the geom's
   * {@link CoordinateReferenceSystem}.
   *
   * @param distance to convert
   * @param geom geometry to get the CRS from
   * @param sridSet to use when converting distance
   * @return distance converted to the correct units for the geom's CRS
   */
  private double distanceToCrsUnits(double distance, Geometry geom, SRIDSet sridSet) {
    return GeometryUtils.distanceToCrsUnits(distance, geom, sridSet);
  }

  public static final IdentifiedFunction BBOX = JavaFunction
      .asBuiltin("bbox", Category.GEOMETRY_LOGICAL)
      .withArgumentTypes(Arrays.asList(
          Types.GEOMETRY, Types.FLOATING, Types.FLOATING, Types.FLOATING, Types.FLOATING))
      .withReturnType(Types.BOOLEAN).calling((args) -> {
        Geometry lhs = (Geometry) args.get(0);
        Double minx = (Double) args.get(1);
        Double miny = (Double) args.get(2);
        Double maxx = (Double) args.get(3);
        Double maxy = (Double) args.get(4);

        Envelope env = new Envelope(minx, maxx, miny, maxy);

        return env.intersects(lhs.getEnvelopeInternal());
  });

  public static final IdentifiedFunction CENTROID = new CentroidFunction()
      .builtin("centroid", Category.GEOMETRY_PROCESSING);

  public static final IdentifiedFunction INTERSECTION = JavaFunction
      .asBuiltin("intersection", Category.GEOMETRY_PROCESSING)
      .withArgumentTypes(Arrays.asList(Types.GEOMETRY, Types.GEOMETRY))
      .withReturnType(Types.GEOMETRY).calling((args) -> {
        Geometry lhs = (Geometry) args.get(0);
        Geometry rhs = (Geometry) args.get(1);

        return OVERLAY_OPERATIONS.intersection(lhs, rhs);
  });

  public final IdentifiedFunction toCoverage =
      new ToTypedCoverage().builtin("to_coverage", IdentifiedFunction.Category.GEOMETRY_PROCESSING);


  public final IdentifiedFunction buffer = new Buffer()
      .builtin("buffer", Category.GEOMETRY_PROCESSING);

  public final IdentifiedFunction length = RealizableFunction.contextOnly(
      ArgumentList.create("geom", Types.GEOMETRY), Types.FLOATING,
      context -> {
        GeometryLengthOp op = new GeometryLengthOp(context.getProject().getSridSet());
        return args -> {
          Geometry geom = (Geometry) args.get(0);
          return op.apply(geom, METRE);
        };
      })
      .builtin("measure_length", Category.GEOMETRY_PROCESSING);

  public final IdentifiedFunction area = RealizableFunction.contextOnly(
      ArgumentList.create("geom", Types.GEOMETRY), Types.FLOATING,
      context -> {
        GeometryAreaOp op = new GeometryAreaOp(context.getProject().getSridSet());
        return args -> {
        Geometry geom = (Geometry) args.get(0);
        return op.apply(geom, SQUARE_METRE);
        };
      })
      .builtin("measure_area", Category.GEOMETRY_PROCESSING);

  public final IdentifiedFunction measure = RealizableFunction.contextOnly(
      ArgumentList.create("geom", Types.GEOMETRY), Types.FLOATING,
      context -> {
        GeometryLengthOp lengthOp = new GeometryLengthOp(context.getProject().getSridSet());
        GeometryAreaOp areaOp = new GeometryAreaOp(context.getProject().getSridSet());
        return args -> {
          Geometry geom = (Geometry) args.get(0);
          if (geom instanceof Polygonal) {
            return areaOp.apply(geom, SQUARE_METRE);
          } else if (geom instanceof Lineal) {
            return lengthOp.apply(geom, METRE);
          } else if (geom instanceof Puntal) {
            return 0D;
          } else {
            // presumably we got a GeometryCollection with a mixture of types. Throw an error
            Set<String> geomTypes = new HashSet<>();
            GeometryUtils.processPerPart(geom, part -> geomTypes.add(part.getClass().getSimpleName()));
            throw new RiskscapeException(GeometryProblems.get().mixedGeometryTypes(geomTypes));
          }
        };
      })
      .builtin("measure", Category.GEOMETRY_PROCESSING);

  private static IdentifiedFunction newOne(String identifier, BiPredicate<Geometry, Geometry> function) {
    return new GeometryPredicateFunction(function).builtin(identifier, Category.GEOMETRY_LOGICAL);
  }

}
