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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.operation.valid.IsValidOp;

import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.GeometryProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.geo.GeometryFixer;
import nz.org.riskscape.engine.geo.GeometryValidation;
import nz.org.riskscape.engine.query.TupleUtils;
import nz.org.riskscape.engine.relation.InvalidTupleException;
import nz.org.riskscape.engine.relation.SpatialMetadata;
import nz.org.riskscape.engine.types.Geom;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemSink;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * A projection that detects any invalid {@link Geometry} and throws {@link InvalidTupleException} should
 * an invalid geometry be found.
 *
 * Note that this projector only checks geometries that are in the top level of the sourceType (nested
 * geometry members are not checked). If there are no geometries in the top level of sourceType of if
 * mode is {@link GeometryValidation#OFF} then the affect is an identity projection.
 *
 * Invalid Geometry can cause TopologyExceptions later if we try to manipulate the Geometry
 * at all (i.e. take an intersection). It's simpler to alert the user at this point
 * rather than trying to catch a TopologyException later.
 */
@RequiredArgsConstructor
public class ValidateGeometryProjection implements Projection {

  @RequiredArgsConstructor
  protected class ValidateGeometryProjector implements Projector {

    private final List<StructMember> geometryMembers;
    private final Struct struct;
    private final GeometryFixer geometryFixer = GeometryFixer.DEFAULT;

    @Override
    public Tuple apply(Tuple t) {
      if (mode != GeometryValidation.OFF) {
        for (StructMember geometryMember : geometryMembers) {
          Geometry geom = t.fetch(geometryMember);
          if (geom != null) {
            IsValidOp isValidOp = new IsValidOp(geom);
            if (!isValidOp.isValid()) {
              // we can try to fix the geometry automagically. if that works out then we can continue
              // as normal
              Geometry fixed = geometryFixer.fix(geom);
              if (fixed != null) {
                problemSink.log(Problems.foundWith(context,
                    GeometryProblems.get().fixedInvalid(geom, fixed, TupleUtils.getContentSummary(t))
                ));
                t.set(geometryMember, fixed);
                continue;
              }
              Problem invalidProblem = GeometryProblems.get()
                  .invalid(geom, isValidOp.getValidationError(), TupleUtils.getContentSummary(t));
              if (mode == GeometryValidation.ERROR) {
                throw new InvalidTupleException(t, invalidProblem);
              } else {
                problemSink.log(Problems.foundWith(context, invalidProblem.withSeverity(Problem.Severity.WARNING)));
              }
            }
          }
        }
      }
      return t;
    }

    @Override
    public Struct getProducedType() {
      return struct;
    }

    @Override
    public Struct getSourceType() {
      return struct;
    }

    @Override
    public Map<List<StructMember>, List<StructMember>> getDirectMapping() {
      return Projector.identityMapping(struct);
    }

    @Override
    public Optional<Function<SpatialMetadata, SpatialMetadata>> getSpatialMetadataMapper() {
      return Optional.empty();
    }
  }

  private final GeometryValidation mode;

  /**
   * Used with mode is {@link GeometryValidation#WARN} to add some context to warning,
   * eg Problem.foundWith(context, invalid-geom-problem)
   */
  private final Object context;

  /**
   * A problem sink to send warning to.
   */
  private final ProblemSink problemSink;

  @Override
  public ResultOrProblems<Struct> projectType(Struct source) {
    return ResultOrProblems.of(source);
  }

  @Override
  public ResultOrProblems<Projector> getProjectionFunction(Struct sourceType) {
    List<StructMember> geometryMembers = new ArrayList<>();
    for (StructMember member: sourceType.getMembers()) {
      if (member.getType().findAllowNull(Geom.class).isPresent()) {
        geometryMembers.add(member);
      }
    }
    return ResultOrProblems.of(new ValidateGeometryProjector(geometryMembers, sourceType));
  }

}
