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

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

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

import com.google.common.collect.Lists;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.Lambda;

/**
 * Wrapper around a coverage that applies a mapping expression to every value sampled, e.g.
 * - users could manipulate the sampled value in their bookmark, such as converting units
 * from centimetres to metres without having to touch pipeline code.
 * - consolidate the value returned from a {@link MultiCoverage}, e.g.
 * `val -> val.depth * val.veolcity`
 */
@RequiredArgsConstructor @Getter @EqualsAndHashCode
public class MappedCoverage implements TypedCoverage {

  public static ResultOrProblems<TypedCoverage> build(
      RealizationContext context,
      TypedCoverage wrapping,
      String valueName,
      Expression expression
  ) {
    Struct scope = Struct.of(valueName, wrapping.getType());

    return ProblemException.catching(() -> {
      return new MappedCoverage(wrapping,
          context.getExpressionRealizer().realize(scope, expression).getOrThrow(),
          valueName);
    });
  }

  public static ResultOrProblems<TypedCoverage> build(
      RealizationContext context,
      TypedCoverage wrapping,
      Lambda lambda
  ) {
    return build(context, wrapping, lambda.getArguments().get(0).getValue(), lambda.getExpression());
  }

  /**
   * @return scope that *only* contains the lambda argument and nothing else
   */
  private static Tuple lambdaOnlyScope(RealizedExpression expression) {
    Object placeholder = null;
    return Tuple.ofValues((Struct) expression.getInputType(), placeholder);
  }

  private final TypedCoverage mapped;
  private final RealizedExpression mappingExpression;
  private final String valueName;
  private final Tuple originalScope;

  public MappedCoverage(TypedCoverage coverage, RealizedExpression expression, String valueName) {
    this(coverage, expression, valueName, lambdaOnlyScope(expression));
  }

  @Override
  public Type getType() {
    return mappingExpression.getResultType();
  }

  @Override
  public Object evaluate(Point point) {
    return map(mapped.evaluate(point));
  }

  @Override
  public Optional<ReferencedEnvelope> getEnvelope() {
    return mapped.getEnvelope();
  }

  @Override
  public Optional<Function<Geometry, List<Pair<Geometry, Object>>>> getEvaluateIntersectionOp() {
    return mapped.getEvaluateIntersectionOp().map(op ->
      op.andThen(list ->
        Lists.transform(list, pair ->
          Pair.of(pair.getLeft(), map(pair.getRight()))
        )
      )
    );
  }

  @Override
  public Optional<Function<Geometry, List<? extends Object>>> getEvaluateIntersectingValuesOp() {
    return mapped.getEvaluateIntersectingValuesOp().map(op ->
      op.andThen(list ->
        Lists.transform(list, item -> map(item))
      )
    );
  }

  @Override
  public CoordinateReferenceSystem getCoordinateReferenceSystem() {
    return mapped.getCoordinateReferenceSystem();
  }

  private Object map(Object rawResult) {
    // null (probably NO-DATA) doesn't get mapped unless the wrapped coverage can return null
    // worth reiterating here that the type of a coverage can be not-null, but the sampling operation will
    // always be nullable (cos of no-data)
    if (rawResult == null && !mapped.getType().isNullable()) {
      return null;
    }

    Tuple scope = originalScope.clone();
    scope.set(valueName, rawResult);
    return mappingExpression.evaluate(scope);
  }

  @Override
  public String toString() {
    return String.format("Mapped(%s, %s)", mapped, mappingExpression.getExpression().toSource());
  }

}
