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

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

import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.factory.epsg.CartesianAuthorityFactory;
import org.geotools.api.coverage.Coverage;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;

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

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.data.SelfDescribingScalarData;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.types.CoverageType;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.util.Pair;


/**
 * A provider of {@link Type} values backed by a {@link Coverage}.
 */
public interface TypedCoverage extends SelfDescribingScalarData {

  /**
   * A default {@link CoordinateReferenceSystem} to return from {@link #getCoordinateReferenceSystem()} when none
   * is provided with the data.  Matches the default from AbstractGridFormat.
   */
  CoordinateReferenceSystem DEFAULT_CRS = CartesianAuthorityFactory.GENERIC_2D;

  /**
   * An empty coverage, useful for testing, stubs, or proxy implementations
   */
  @RequiredArgsConstructor
  class Empty implements TypedCoverage {

    @Getter
    private final Type type;

    @Override
    public Object evaluate(Point point) {
      return null;
    }

    @Override
    public CoordinateReferenceSystem getCoordinateReferenceSystem() {
      return DEFAULT_CRS;
    }
  }

  /**
   * @return an empty {@link TypedCoverage} with the given type
   */
  static TypedCoverage empty(Type type) {
    return new Empty(type);
  }

  /**
   * @return type of values returned by {@link #evaluate(org.locationtech.jts.geom.Point) }
   */
  Type getType();

  /**
   * Get values from coverage at point. Values will be in the type returned by
   * {@link #getType() }
   *
   * @param point to sample coverages at
   * @return result as expected type
   */
  Object evaluate(Point point);

  /**
   * @return a function that can be used for calculating all the parts of the a geometry that intersect with this
   * grid.   The function is 'curried' so that it always applies to this {@link TypedCoverage}.
   *
   * How the intersection is done is up to each implementation of {@link TypedCoverage}, but in general, this method
   * should return a new list of geometries paired up with the value of the coverage at each intersection.
   *
   * This method should return Optional.empty if this operation is not supported.
   */
  default Optional<Function<Geometry, List<Pair<Geometry, Object>>>> getEvaluateIntersectionOp() {
    return Optional.empty();
  }

  /**
   * Similar to {@link #getEvaluateIntersectionOp() } except that the returned function only returns
   * the values of intersecting grid cells. E.g geometry intersections are not included.
   */
  default Optional<Function<Geometry, List<? extends Object>>> getEvaluateIntersectingValuesOp() {
    return Optional.empty();
  }

  /**
   * @return the CRS that the underlying data is represented in
   */
  CoordinateReferenceSystem getCoordinateReferenceSystem();

  /**
   * @return the geographic bounds of the underlying data, if available.
   */
  default Optional<ReferencedEnvelope> getEnvelope() {
    return Optional.empty();
  }

  @Override
  default CoverageType getScalarDataType() {
    /*
     * NB: We used to return a Referenced wrapped type here, but in hindsight it was a mistake.  The CRS of a coverage
     * is irrelevant to its co/variance - as long as the result types are the same, they are interchangeable.  This is
     * because they (should) always mirror the CRS of the sampled geometry in sampling operations, so the CRS of the
     * underlying data does not affect its use.
     *
     * This is different to the relation case,
     * where the CRS of the geometry does influence its variance, as the type system does make demands on you about
     * having geometry attributes be in the right projection.
     *
     * Note that it looks like the referenced type was only added for 'completeness', looks like it was added when
     * #getScalarDataType was added, possibly without really thinking through the why.
     */
    return new CoverageType(getType());
  }

  /**
   * Returns a tabular view of this data, or empty if it isn't possible.  This method is here to support efficient and
   * streaming through raster data - at the moment there's no perceived need to implement this for non-grid/pixel
   * formats, such as hdf5/netcdf, but who knows what the future holds or what use cases this might allow...
   * <mysterious-science-noises>
   *
   * The relation's type is expected to at least contain the values that the coverage yields, plus the geometry at each
   * location in the coverage.
   */
  default Optional<Relation> asRelation() {
    return Optional.empty();
  }

}
