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

import java.util.EnumSet;
import java.util.Map;
import java.util.Optional;

import org.geotools.api.coverage.grid.GridCoverage;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.geometry.jts.ReferencedEnvelope;

import com.google.common.collect.ImmutableMap;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.data.BaseBookmarkResolver;
import nz.org.riskscape.engine.data.BookmarkProblems;
import nz.org.riskscape.engine.data.coverage.GridTypedCoverage;
import nz.org.riskscape.engine.function.ExpensiveResource;
import nz.org.riskscape.engine.geo.GeometryUtils;
import nz.org.riskscape.engine.geo.GeometryValidation;
import nz.org.riskscape.engine.projection.ForceSridProjection;
import nz.org.riskscape.engine.projection.SetAttributeProjection;
import nz.org.riskscape.engine.projection.TypeProjection;
import nz.org.riskscape.engine.projection.ValidateGeometryProjection;
import nz.org.riskscape.engine.query.TupleUtils;
import nz.org.riskscape.engine.raster.VectorToRaster;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.relation.SpatialMetadata;
import nz.org.riskscape.engine.relation.TypeCheckingOptions;
import nz.org.riskscape.engine.restriction.ExpressionRestriction;
import nz.org.riskscape.engine.rl.ExpressionRealizer;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.Expression;


/**
 * Base class for a thing that returns relations from a bookmark.  Shares the logic of applying various
 * relation-specific features and validations to any relation return from some format-specific source.
 *
 * TODO i18n all the various error messages in here
 */
@Slf4j
public abstract class RelationBookmarkResolver<T extends RelationBookmarkParams>
  extends BaseBookmarkResolver<T> {

  private static final String RASTERIZE_KEY = "rasterize";
  private static final String RASTERIZE_EXPRESSION_KEY = "rasterize-expression";
  private static final String RASTERIZE_SCALE_KEY = "rasterize-scale-factor";
  private static final String RASTERIZE_GRID_SIZE_KEY = "rasterize-grid-size";

  @Getter @Setter
  protected VectorToRaster v2r = new VectorToRaster();

  public RelationBookmarkResolver(Engine engine) {
    super(engine);
  }

  @Override
  protected Map<String, String> getAliasMapping() {
    return ImmutableMap.of("crs-force-xy", "crs-longitude-first");
  }

  @SuppressWarnings({ "unchecked", "rawtypes" })
  @Override
  protected ResultOrProblems build(T params) {
    // building the relation might be slow so wrap it in an ExpensiveResource, so we
    // at least get some logs as to why the engine has become unresponsive
    ResultOrProblems<Relation> relation = new ExpensiveResource<>(
        params.getExecutionContext().getProblemSink(),
        getClass().getSimpleName(),
        () -> createRawRelationFromBookmark(params)
    ).get();

    if (relation.hasErrors()) {
      return relation;
    }

    if (params.skipInvalid) {
      relation = relation.map(r -> r.skipInvalid(params.getExecutionContext().getProblemSink()));
    }

    Type type  = params.type.orElse(null);

    if (params.setAttribute.isPresent()) {
      Map<String, Expression> setAttributeMap = params.setAttribute.get();
      SetAttributeProjection projection = new SetAttributeProjection(setAttributeMap, params.getExpressionRealizer());
      relation = relation
          .flatMap(r -> r.project(projection))
          .composeProblems(Problem.error("Could not apply all `set-attribute` parameters"));
    } else if (type != null) {
      Map<String, Expression> attributeMap = params.mapAttribute.orElse(new AttributeMap());
      EnumSet<TypeCheckingOptions> options =
          EnumSet.of(TypeCheckingOptions.SKIP_INVALID_TUPLES, TypeCheckingOptions.COERCE);

      TypeProjection projection = new TypeProjection(type.asStruct(), attributeMap, options,
          params.getRealizationContext());
      relation = relation.flatMap(r -> r.project(projection));
    }

    if (params.crs.isPresent()) {
      // if relation already has spatial metadata, we forcibly set the crs to this value, and convert all tuples to
      // contain geometries with this crs
      relation = relation.flatMap(r -> r.project(new ForceSridProjection(params.crs.get(),
          params.getProject().getSridSet())));
    }

    if (params.filter.isPresent()) {
      relation = relation.flatMap(r -> applyFilter(params.filter.get(), r, params));
    }

    boolean hasGeometry = relation.map(r -> TupleUtils.hasGeometryMember(r.getType())).orElse(false);

    GeometryValidation geometryValidation = params.validateGeometry
        .orElse(params.getProject().getGeometryValidation());

    if (hasGeometry && geometryValidation != GeometryValidation.OFF) {
      relation = relation.flatMap(r -> r.project(new ValidateGeometryProjection(geometryValidation,
          params.bookmark,
          params.getExecutionContext().getProblemSink())));
    }

    if (params.rasterize) {
      return relation.flatMap((r, p) -> rasterize(params, r).withMoreProblems(p));
    }

    return relation.flatMap(rel -> postBuild(rel, params));
  }

  /**
   * Called on completion of {@link #build(nz.org.riskscape.engine.data.relation.RelationBookmarkParams) } with
   * the built relation.
   *
   * Override this method to make any final changes to the relation.
   *
   * @param built the build relation
   * @param params the bookmark parameters
   */
  protected ResultOrProblems<Relation> postBuild(Relation built, T params) {
    return ResultOrProblems.of(built);
  }

  protected ResultOrProblems<Relation> applyFilter(Expression filter, Relation relation, T params) {
    ExpressionRealizer  expressionRealizer = params.getExpressionRealizer();
    return expressionRealizer.realize(relation.getType(), filter).flatMap(fe -> {
      if (! Nullable.strip(fe.getResultType()).equals(Types.BOOLEAN)) {
        return ResultOrProblems.failed(
            Problems.get(TypeProblems.class).mismatch(params.bookmark, Types.BOOLEAN, fe.getResultType()));
      }
      return relation.restrict(new ExpressionRestriction(filter, expressionRealizer));
    }).composeProblems("Could not apply bookmark supplied filter `%s` to relation", filter.toSource());
  }

  /**
   * Converts the given {@link Relation} in to a {@link GridCoverage} using the options in the bookmark.
   */
  protected ResultOrProblems<TypedCoverage> rasterize(T params, Relation relation) {
    Expression coverageValueExpression = params.rasterizeExpression.get();

    return ProblemException.catching(() -> {
      RealizedExpression realizedCoverageExpr = params.getExpressionRealizer()
        .realize(relation.getType(), coverageValueExpression).getOrThrow();

      if (!realizedCoverageExpr.getResultType().isNumeric()) {
        throw new ProblemException(Problem.error(
          "Expression '%s' does not result in a numeric type, was '%s'",
          coverageValueExpression.toSource(),
          realizedCoverageExpr));
      }

      Optional<CoordinateReferenceSystem> crs = relation.getSpatialMetadata().map(SpatialMetadata::getCrs);
      if (!crs.isPresent()) {
        throw new ProblemException(Problem.error(
            "Relation '%s' has no spatial metadata - can not convert to a raster",
            relation));
      }

      log.info("Calculating bounds from {} ...", relation);
      Optional<ReferencedEnvelope> bounds = relation.calculateBounds();

      if (!bounds.isPresent()) {
        throw new ProblemException(Problem.error(
            "Relation '%s' is either empty or has no spatial metadata - can not convert to a raster",
            relation));
      }

      // if scale factor is not set, then it is calculated from grid size. validate() will ensure that
      // one them them is set when rasterizing.
      double scaleFactor = params.rasterizeScaleFactor
          .orElseGet(() -> 1 / GeometryUtils.toCrsUnits(params.rasterizeGridSize.get(),  crs.get()));

      GridCoverage2D coverage = v2r.convert(
          relation,
          realizedCoverageExpr,
          scaleFactor,
          bounds.get(),
          params.coverageTitle
      );
      return new GridTypedCoverage(coverage, params.getProject().getSridSet());
    });
  }

  @Override
  protected void validateParameters(T params, BindingContext context) {

    if (!params.type.isPresent() && params.mapAttribute.isPresent()) {
      params.problems.add(Problem.warning(
          "Attribute mappings were given, but no type specified.  These will be ignored"));
    }

    if (params.type.isPresent() && params.setAttribute.isPresent()) {
      params.add(Problems.get(BookmarkProblems.class).setAttributesNotAllowedWithType());
    }


    params.crsName.ifPresent(name -> {
      BaseBookmarkResolver.setCrs(params, name, params.crsLongitudeFirst, getParameterSet().get("crs-name"),
          crs -> params.crs = Optional.of(crs));
    });

    boolean rasterizeErrors = params.problems.stream()
      .anyMatch(problem ->
        problem.getAffected(Parameter.class).map(param -> param.getName().startsWith("rasterize")).orElse(false)
      );

    if (params.rasterize && !rasterizeErrors) {
      // one of scaleFactor or grid size are supported, ultimately it needs to be converted in to a scale factor
      boolean gridSizeGiven = params.rasterizeGridSize.isPresent();
      boolean scaleFactorGiven = params.rasterizeScaleFactor.isPresent();

      if (gridSizeGiven == scaleFactorGiven) {
        if (gridSizeGiven) {
          params.add(Problem.error("Only one of '%s' and '%s' can be specified", RASTERIZE_GRID_SIZE_KEY,
              RASTERIZE_SCALE_KEY, RASTERIZE_KEY));
        } else {
          params.add(Problem.error("'%s' or '%s' is required when '%s' is set to true", RASTERIZE_SCALE_KEY,
              RASTERIZE_GRID_SIZE_KEY, RASTERIZE_KEY));
        }
      } else {

        if (gridSizeGiven) {
          double gridSizeValue = params.rasterizeGridSize.get().doubleValue();
          if (gridSizeValue <= 0.0) {
            params.add(Problem.error("Value of '%s' must be a non-zero positive number, was '%s'",
                RASTERIZE_GRID_SIZE_KEY, gridSizeValue));
          }
        } else {
          double scaleFactorValue = params.rasterizeScaleFactor.get().doubleValue();
          if (scaleFactorValue <= 0.0) {
            params.add(Problem.error("Value of '%s' must be a non-zero positive number, was '%s'",
                RASTERIZE_SCALE_KEY, scaleFactorValue));
          }
        }
      }

      if (!params.rasterizeExpression.isPresent()) {
        params.add(Problem.error("'%s' is required when '%s' is set to true", RASTERIZE_EXPRESSION_KEY,
            RASTERIZE_KEY));
      }
    }

    params.coverageTitle = params.bookmark.getId();
  }

  /**
   * Construct the raw, unadulterated relation from the bookmark.  Won't be called if validation includes errors.
   * @return the {@link Relation} that returns data from some specific format and location
   */
  protected abstract ResultOrProblems<Relation> createRawRelationFromBookmark(T params);

}
