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

import static nz.org.riskscape.engine.function.RiskscapeFunction.*;

import java.util.List;
import java.util.function.BiPredicate;
import java.util.function.Function;

import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.locationtech.jts.geom.Geometry;

import lombok.Getter;
import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.GeometryProblems;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.types.Geom;
import nz.org.riskscape.engine.types.Referenced;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

public class GeometryPredicateFunction extends BaseRealizableFunction {

  protected static final ArgumentList BASE_ARGUMENTS =
      ArgumentList.create("lhs", Types.GEOMETRY, "rhs", Types.GEOMETRY);

  @Getter
  private final BiPredicate<Geometry, Geometry> predicate;

  public GeometryPredicateFunction(BiPredicate<Geometry, Geometry> predicate) {
    super(BASE_ARGUMENTS, Types.BOOLEAN);
    this.predicate = predicate;
  }

  /**
   * For use by subclasses that wish to supply a custom predicate at runtime. These subclasses must
   * override {@link #realizePredicateSupplier(RealizationContext, FunctionCall, List) } to allow the
   * predicate to obtained when required
   * @param extraArgs the in addition to {@link #BASE_ARGUMENTS} that the function requires
   */
  protected GeometryPredicateFunction(FunctionArgument... extraArgs) {
    super(BASE_ARGUMENTS.withExtraArgument(extraArgs), Types.BOOLEAN);
    this.predicate = null;
  }

  @Override
  public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context, FunctionCall functionCall,
      List<Type> argTypes) {
    return ProblemException.catching(() -> {

      arguments.validateArity(argTypes);

      // We setup the predicate supplier before the geometry args are validated. This allows subclasses that
      // have additional arguments to fail first if they are not correct. This is necessary because if the
      // types cannot be coerced to the required types by the function resolver it will fall back to realizing
      // the function with whatever it got. That could be either a struct or a nullable geom which will cause
      // errors that could obstruct the real problem which could be the extra argument being the wrong type.
      Function<List<Object>, BiPredicate<Geometry, Geometry>> predicateSupplier =
          realizePredicateSupplier(context, functionCall, argTypes);

      if (!argTypes.get(0).find(Geom.class).isPresent()) {
        throw new ProblemException(ArgsProblems.mismatch(arguments.get(0), argTypes.get(0)));
      }
      if (!argTypes.get(1).find(Geom.class).isPresent()) {
        throw new ProblemException(ArgsProblems.mismatch(arguments.get(1), argTypes.get(1)));
      }

      // lets see if we can find the CRS of each side
      Referenced lhsReferenced = argTypes.get(0).find(Referenced.class).orElse(null);
      Referenced rhsReferenced = argTypes.get(1).find(Referenced.class).orElse(null);
      SRIDSet sridSet = context.getProject().getSridSet();
      if (lhsReferenced != null && rhsReferenced != null
          && sridSet.requiresReprojection(lhsReferenced.getCrs(), rhsReferenced.getCrs())) {
        // the referenced types for both sides is known but the CRS's are not the same. This is not allowed.
        throw new ProblemException(
            GeometryProblems.get().mismatchedCrs(lhsReferenced.getCrs(), rhsReferenced.getCrs())
        );
      }

      UntypedFunction function = args -> {
        if (args.get(0) == null || args.get(1) == null) {
          return null;
        }
        Geometry lhs = (Geometry)args.get(0);
        Geometry rhs = (Geometry)args.get(1);

        if (lhs.getSRID() != rhs.getSRID()) {
          // the geometries do not have the same SRID. predicate functions are unlikely to return the right result
          // if the CRSs are not the same.
          // we need to be a little bit careful getting the CRS for the geometry. because currently it's possible
          // to create a geom with srid == 0 which is the unknown CRS. You cannot get a CRS from SRIDSet for this
          // as it will throw an exception. so check for this and map it to null just in case.
          CoordinateReferenceSystem lhsCrs = lhs.getSRID() == 0 ? null : sridSet.get(lhs.getSRID());
          CoordinateReferenceSystem rhsCrs = rhs.getSRID() == 0 ? null : sridSet.get(rhs.getSRID());
          throw new RiskscapeException(
              GeometryProblems.get().mismatchedCrs(lhsCrs, rhsCrs)
          );
        }

        BiPredicate<Geometry, Geometry> predicateToUse = predicateSupplier.apply(args);
        return predicateToUse.test(lhs, rhs);
      };

      return RiskscapeFunction.create(BUILT_IN, argTypes, returnType, function);
    });
  }

  /**
   * Realize the predicate supplier.
   *
   * May be used by sub classes to customise how a predicate function is supplied.
   *
   * @param context       the realization context
   * @param functionCall  the function call AST being realized
   * @param argTypes      the types of the arguments that have been supplied to the function
   * @return  a function that given the functions arguments will return a geometry bi predicate function
   * @throws ProblemException should argTypes or functionCall contain problems
   */
  protected Function<List<Object>, BiPredicate<Geometry, Geometry>> realizePredicateSupplier(
      RealizationContext context, FunctionCall functionCall, List<Type> argTypes) throws ProblemException {
    return (args) -> predicate;
  }


}
