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

import java.util.List;

import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.data.coverage.GridCoverageRelation;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.BaseRealizableFunction;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.projection.CoercerProjection;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.types.CoverageType;
import nz.org.riskscape.engine.types.RelationType;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.rl.ast.FunctionCall;
import nz.org.riskscape.rl.ast.FunctionCall.Argument;

/**
 * RiskScape function for tapping in to {@link TypedCoverage#asRelation()} to allow the data within a coverage to be
 * processed as tuples.
 */
public class ToRelation extends BaseRealizableFunction {

  public ToRelation() {
    super(ArgumentList.create("coverage", CoverageType.WILD), RelationType.WILD);
  }

  @Override
  protected RiskscapeFunction build(RealizationContext context, FunctionCall functionCall, List<Type> givenTypes)
      throws ProblemException {

    CoverageType coverageType = getArguments().getRequiredAs(givenTypes, 0, CoverageType.class).getOrThrow();
    Argument argument = arguments.getArgument(functionCall, "coverage").get();

    TypedCoverage constantValue = argument.evaluateConstant(context, TypedCoverage.class, coverageType).orElse(null);

    if (constantValue != null) {
      return buildConstant(givenTypes, constantValue);
    } else {
      return buildDynamic(context, givenTypes, coverageType);
    }
  }

  private RiskscapeFunction buildConstant(List<Type> givenTypes, TypedCoverage constantValue) throws ProblemException {
    Relation relation = constantValue.asRelation().orElse(null);
    if (relation == null) {
      throw new ProblemException(GeneralProblems.get().operationNotSupported("to_relation", CoverageType.class));
    }

    return RiskscapeFunction.create(
        this,
        givenTypes,
        relation.getScalarDataType(),
        args -> relation,
        relation::close);
  }

  private RiskscapeFunction buildDynamic(RealizationContext context, List<Type> givenTypes, CoverageType coverageType) {
    // NB this is not really defined anywhere that this is how a converted coverage should work.  We might
    // need to put some more thought in to this?  If it's implementation specific, that'll be difficult.
    Struct valueType = GridCoverageRelation.createStructType(coverageType);

    return RiskscapeFunction.create(this, givenTypes, new RelationType(valueType), args -> {
        TypedCoverage coverage = (TypedCoverage) args.get(0);

        Relation relation = coverage.asRelation().orElse(null);
        if (relation == null) {
          throw new RiskscapeException(GeneralProblems.get().operationNotSupported("to_relation", CoverageType.class));
        }

        if (relation.getProducedType().equals(valueType)) {
          return relation;
        } else {
          // we need to return tuples of the exact same type
          Relation mapped = CoercerProjection.mapping(relation.getProducedType(), valueType, context)
              .flatMap(projection -> relation.project(projection))
              .orElseThrow(probs -> new RiskscapeException(Problems.from(probs)));

          return mapped;
        }
    });
  }

}
