/*
 * 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 java.util.List;
import java.util.Optional;
import java.util.function.Function;

import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.geo.GeometryUtils;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.query.TupleUtils;
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.Floating;
import nz.org.riskscape.engine.types.Geom;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

import lombok.Getter;

/**
 * Sample function that will return a single sample or null. Sampling if first performed at the centroid,
 * if no sample is found at the centroid then the closest (to the centroid) all intersections match is
 * chosen. Note that the centroid is only sampled if the centroid is contained by the geometry
 */
public class SampleClosest implements RiskscapeFunction, RealizableFunction {

  @Getter
  private final ArgumentList arguments = ArgumentList.fromArray(
      new FunctionArgument("geometry", Types.GEOMETRY),
      new FunctionArgument("coverage", CoverageType.WILD),
      new FunctionArgument("buffer-distance", Types.FLOATING, Optional.of(0.0F))
  );

  @Override
  public List<Type> getArgumentTypes() {
    return getArguments().getArgumentTypes();
  }

  @Override
  public Object call(List<Object> args) {
    throw new UnsupportedOperationException();
  }

  @Override
  public Type getReturnType() {
    return Types.ANYTHING;
  }

  @Override
  public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context, FunctionCall functionCall,
      List<Type> realizeTypes) {

    if (realizeTypes.size() < 2 || realizeTypes.size() > getArguments().size()) {
      return ResultOrProblems.failed(
          Problems.get(ArgsProblems.class).wrongNumber(getArguments().size(), realizeTypes.size()));
    }

    // The first argument should be a geometry type. But if the optional buffer-distance arg is missing then
    // the function resolver will not coerce a struct (with geom) to geom. So we need to do this ourselves
    // if necessary
    Function<Object, Geometry> geometryExtractor;
    Geom geomType = realizeTypes.get(0).find(Geom.class).orElse(null);
    if (geomType != null) {
      geometryExtractor = o -> (Geometry)o;
    } else {
      Optional<StructMember> geomMember = realizeTypes.get(0).find(Struct.class)
          .map(struct -> TupleUtils.findGeometryMember(struct, TupleUtils.FindOption.OPTIONAL));

      if (geomMember.isPresent()) {
        geometryExtractor = o -> ((Tuple)o).fetch(geomMember.get());
      } else {
        // not a struct or struct with no geometry. Either way thats not the expected arg
        return ResultOrProblems.failed(ArgsProblems.mismatch(getArguments().get(0), realizeTypes.get(0)));
      }
    }

    CoverageType coverageType = realizeTypes.get(1).find(CoverageType.class).orElse(null);
    if (coverageType == null) {
      return ResultOrProblems.failed(ArgsProblems.mismatch(getArguments().get(1), realizeTypes.get(1)));
    }

    if (realizeTypes.size() == 3) {
      Floating bufferDistanceType = realizeTypes.get(2).find(Floating.class).orElse(null);
      if (bufferDistanceType == null) {
        return ResultOrProblems.failed(ArgsProblems.mismatch(getArguments().get(2), realizeTypes.get(2)));
      }
    }

    return ResultOrProblems.of(new RiskscapeFunction() {

      @Getter
      private final List<Type> argumentTypes = realizeTypes;

      @Getter
      private final Type returnType = Nullable.of(coverageType.getMemberType());

      @Override
      public Object call(List<Object> args) {
        Geometry geom = geometryExtractor.apply(args.get(0));
        Point centroid = geom.getCentroid();
        TypedCoverage coverage = (TypedCoverage) args.get(1);

        Object found = GeometryUtils.getMidpoint(geom)
            .map(mid -> coverage.evaluate(mid))
            .orElse(null);
        if (found != null) {
          return found;
        }

        Function<Geometry, List<Pair<Geometry, Object>>> op = coverage.getEvaluateIntersectionOp().orElse(null);

        if (op == null) {
          throw new RiskscapeException(
              GeneralProblems.get().operationNotSupported("intersection", coverage.getClass()));
        }

        if (! (geom instanceof Point)) {
          // try to find the closest match. but we don't do this for points because that would return the
          // same answer as coverage.evaluate (and we know that's not going to give us an answer for this geom)

          // when sampling the original geom, we measure from it's centroid to the matched geoms
          found = closestMatch(op.apply(geom), g -> centroid.distance(g));
        }
        if (found == null && args.size() == 3) {
          Double bufferDistanceMetres = (Double)args.get(2);
          if (found == null && bufferDistanceMetres > 0.0F) {
            // nothing found, but an optional buffer distance is specified.
            // we buffer the geom and sample again
            double bufferDistanceCrsUnits = GeometryUtils.distanceToCrsUnits(bufferDistanceMetres, geom,
                context.getProject().getSridSet());

            // now that we are looking outside of the geom, we measure distance from it, to the matched geoms.
            found = closestMatch(op.apply(geom.buffer(bufferDistanceCrsUnits)), g -> geom.distance(g));
          }
        }
        return found;
      }
    });
  }

  private Object closestMatch(List<Pair<Geometry, Object>> found, Function<Geometry, Double> distanceFunction) {
    if (found.isEmpty()) {
      return null;
    } else if (found.size() == 1) {
      // If only one was found then it has to be the match.
      return found.get(0).getRight();
    }
    // Otherwise we need to find the closest, as determined by the distanceFunction
    Pair<Geometry, Object> bestMatch = null;
    for (Pair<Geometry, Object> f: found) {
      if (bestMatch == null) {
        bestMatch = f;
      } else if (distanceFunction.apply(f.getLeft()) < distanceFunction.apply(bestMatch.getLeft())) {
        bestMatch = f;
      }
    }
    return bestMatch.getRight();
  }

}
