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

import java.util.Arrays;
import java.util.List;

import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.Point;
import org.geotools.api.referencing.FactoryException;
import org.geotools.api.referencing.NoSuchAuthorityCodeException;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.api.referencing.crs.ProjectedCRS;
import org.geotools.api.referencing.operation.MathTransform;
import org.geotools.api.referencing.operation.TransformException;

import lombok.Data;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.GeometryProblems;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.problem.Problems;

/**
 * Geometry operation to return geometries in a {@link ProjectedCRS} which makes measuring and other
 * geometry operations easier.
 *
 * Large geometries or {@link GeometryCollection}s may be split into pieces.
 */
@RequiredArgsConstructor
public class ProjectGeometryOp {

  /**
   * Contains a source {@link Geometry} and the same geometry re-projected to a gridded CRS.
   *
   * Useful when geometries need to be measured or segmented.
   */
  @Data
  public class Projected {

    /**
     * The original {@link Geometry}
     */
    private final Geometry source;

    /**
     * The {@link CoordinateReferenceSystem} of {@link #getSource()}
     */
    private final CoordinateReferenceSystem sourceCrs;

    /**
     * A projected form of {@link #getSource()}.
     *
     * If the {@link #getSourceCrs()} is a projected CRS then this will be the same object as
     * see {@link #getSource()}.
     */
    private final Geometry projected;

    /**
     * The {@link CoordinateReferenceSystem} of {@link #getProjected()}.
     */
    private final CoordinateReferenceSystem projectedCrs;

    /**
     * A {@link MathTransform} that is able to return projected geometries back to
     * {@link #getSourceCrs()}.
     */
    private final MathTransform projectedToSource;

    /**
     * Re-projects the {@link Geometry} (which is expected to be in the projected CRS) back to
     * {@link #getSourceCrs()}.
     *
     * @param geom
     * @return Geometry
     */
    public Geometry toSourceCrs(Geometry geom) {
      if (projectedToSource == null) {
        return geom;
      }
      try {
        Geometry reprojected = sridSet.reproject(geom, projectedToSource, projectedCrs, sourceCrs);
        // We need to ensure that the geom has the correct srid before we give it back.
        reprojected.setSRID(source.getSRID());
        return reprojected;
      } catch (TransformException e) {
        throw new RiskscapeException(GeometryProblems.get().cannotReproject(geom, projectedCrs, sourceCrs));
      }
    }

    /**
     * Helper to bring another geometry into the same projected CRS as {@link #getProjected()}.
     * This is useful when there are two or more geometries required for a given operation,
     * such as union or difference.
     * @return the `geom` transformed into the same CRS as {@link #getProjected()}.
     */
    public Geometry projectAlso(Geometry geom) {
      // first we need to reproject into the source CRS we started with. This is important
      // because a metric CRS doesn't need to be projected, so if *either* source or geom
      // are already in a metric CRS, then apply() will do nothing
      Geometry reprojected = ProjectGeometryOp.this.sridSet.reproject(geom, source.getSRID());

      // now we can apply the autoCRS projection to the input geometry
      List<Projected> projectedGeom = apply(reprojected);
      if (projectedGeom.size() != 1) {
        // Single input should only ever result in a single projected geometry result...
        throw new RiskscapeException("Internal error reprojecting single geometry");
      }
      return projectedGeom.get(0).getProjected();
    }
  }

  private final SRIDSet sridSet;

  /**
   * Returns a {@link List} of {@link Projected} containing the source geometry and it's
   * {@link CoordinateReferenceSystem} along with a re-projected version (or part) of it. Useful when
   * geometries need to be measured or segmented.
   *
   * Projected relates to the geometry's {@link CoordinateReferenceSystem} been a {@link ProjectedCRS}
   * in which case the geometry's units are meaningful to measure. That is a square metre is a meaningful
   * measurement, whereas the size of a square degree depends on the latitude of that square degree.
   *
   * @param geom
   * @return List<Projected>
   */
  public List<Projected> apply(Geometry geom) {
    CoordinateReferenceSystem crs = sridSet.get(geom);
    if (crs instanceof ProjectedCRS) {
      return Arrays.asList(new Projected(geom, crs, geom, crs, null));
    }
    // TODO the following implementation should be made smarter to detect and segment features that
    // span too many degrees. GeometryCollections could also be split into components but we may only
    // want to do that if they are spanning large areas. Splitting them up will add to re-projection
    // overhead so we don't want to split them up just because we can.

    // We reproject the geometry's centroid to EPSG:4326 lat/lon as that has the required longitude
    // range of -180 < longitude <= 180. This is necessary as other CRSs may have a longitude range
    // of 0 < longitude <= 360. EPSG:4167 (NZGD) is an example of one of these CRSs.
    Point centroid = sridSet.reproject(geom.getCentroid(), sridSet.get(SRIDSet.EPSG4326_LATLON)).getCentroid();
    CoordinateReferenceSystem autoCrs = null;

    double latitude = centroid.getX();
    double longitude = centroid.getY();
    try {
      // format of the auto projection is "AUTO2:auto_crs_id,scale_factor,lon0,lat0"
      autoCrs = CRS.decode(String.format("AUTO2:42001,0.9996,%f,%f", longitude, latitude));

      MathTransform transform = sridSet.getReprojectionTransform(geom.getSRID(), sridSet.get(autoCrs));

      return Arrays.asList(
          new Projected(geom, crs, sridSet.reproject(geom, transform, crs, autoCrs), autoCrs, transform.inverse())
      );
    } catch (TransformException e) {
      throw new RiskscapeException(GeometryProblems.get().cannotReproject(geom, crs, autoCrs));
    } catch (NoSuchAuthorityCodeException e) {
      throw new RiskscapeException(GeometryProblems.get().autoProjectionNotFound(latitude, longitude));
    } catch (FactoryException e) {
      throw new RiskscapeException(Problems.caught(e));
    }
  }
}
