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

import org.geotools.geometry.jts.CurvedGeometry;
import org.locationtech.jts.geom.Geometry;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.relation.InvalidTupleException;
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.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Projector that prevents {@link CurvedGeometry} from entering RiskScape.
 *
 * If a {@link CurvedGeometry} is encountered then:
 * - an {@link InvalidTupleException} will be thrown if {@link #tolerance} is empty
 * - or the geometry will be linearized by calling {@link CurvedGeometry#linearize(double) }
 */
@RequiredArgsConstructor
public class LinearGeometryProjection implements Projection {

  public interface LocalProblems extends ProblemFactory {
    /**
     * When a {@link CurvedGeometry} is encountered and the {@link #tolerance} is empty.
     */
    Problem unexpectedCurvedGeometry(Class geomType, Problem... children);

    /**
     * Hint how to enable linearization of {@link CurvedGeometry}.
     */
    Problem enableLinearizeGeometryHint();
  }

  public static final LocalProblems PROBLMES = Problems.get(LocalProblems.class);

  @RequiredArgsConstructor(access = AccessLevel.PRIVATE)
  class LinearGeometryProjector implements Projector {

    @Getter
    private final Struct sourceType;

    private final List<StructMember> geometryMembers;

    @Override
    public Struct getProducedType() {
      // although we may be re-writing curved geometries with their linear equivalent this doesn't
      // change the type as far as RiskScape is concerned. This is because all curved geometry subtypes
      // inherit from their linear equivalents (e.g, MultiSurface extends MultiPolygon)
      return sourceType;
    }

    @Override
    public Tuple apply(Tuple t) {
      Object[] newValues = t.toArray();
      Tuple projected = Tuple.ofValues(sourceType, newValues);

      for (StructMember member : geometryMembers) {
        Geometry g = projected.fetch(member);
        if (g != null && g instanceof CurvedGeometry curved) {
          if (tolerance.isEmpty()) {
            throw new InvalidTupleException(t, PROBLMES.unexpectedCurvedGeometry(
                curved.getClass(),
                PROBLMES.enableLinearizeGeometryHint()
            ));
          }
          // XXX maybe we should output warnings that geometries have been altered but this doesn't seem
          // necessary as this is opt in via the tolerance parameter

          // Note: geotools linearize looks to boil down to being done in CircularArc.java per segment
          // which has a default 10,000 node limit to the points that are added.
          projected.set(member, curved.linearize(tolerance.get()));
        }
      }
      return projected;
    }
  }

  /**
   * Tolerance to use when linearizing {@link CurvedGeometry}.
   *
   * If this value is empty then any {@link CurvedGeometry} encountered will result in an
   * {@link InvalidTupleException} being thrown.
   */
  private final Optional<Double> tolerance;

  @Override
  public ResultOrProblems<Projector> getProjectionFunction(Struct sourceType) {
    List<StructMember> members = sourceType.getMembers().stream()
        .filter(m -> m.getType().findAllowNull(Geom.class).isPresent())
        .toList();
    if (members.isEmpty()) {
      // if there are no geometry attributes some some cycles and use the identity projector
      return ResultOrProblems.of(Projector.identity(sourceType));
    }
    return ResultOrProblems.of(new LinearGeometryProjector(sourceType, members));
  }

}
