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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import org.locationtech.jts.geom.Point;

import com.google.common.collect.Range;

import nz.org.riskscape.defaults.function.MultiCoverage.RawValueSetter;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.coverage.TypedCoverage;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.BaseRealizableFunction;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.geo.ProjectGeometryOp;
import nz.org.riskscape.engine.geo.RecursiveQuadGridOp;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.types.CoverageType;
import nz.org.riskscape.engine.types.Geom;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
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.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

public class CombineCoverages extends BaseRealizableFunction {

  private static final Range<Double> GRID_RANGE = Range.greaterThan(0.0D);

  public CombineCoverages() {
    super(
      ArgumentList.create("coverages", Types.ANYTHING, "grid-resolution", Types.FLOATING),
      new CoverageType(Struct.EMPTY_STRUCT)
    );
  }

  @Override
  public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context, FunctionCall functionCall,
      List<Type> argumentTypes) {

    SRIDSet sridSet = context.getProject().getSridSet();

    return ProblemException.catching(() -> {

      arguments.getRequiredArgument(functionCall, "coverages").getOrThrow();
      Struct components = argumentTypes.get(0).findAllowNull(Struct.class).get();

      if (components.size() == 0) {
        throw new ProblemException(TypeProblems.get().structMustBeNonEmpty("coverages"));
      }

      final Struct builtType = buildCoverageStruct(components);
      CoverageType newReturnType = new CoverageType(builtType);

      // now build the value setters that will be required for to set the raw values (in the sampled tuple)
      // for each child coverage
      final RawValueSetter[] valueSetters = buildCoverageValueSetters(components);

      // check grid resolution - trigger an exception if missing or wrong type
      arguments.getRequiredArgument(functionCall, "grid-resolution").getOrThrow();
      Type gridResType = argumentTypes.get(1);
      if (!Number.class.isAssignableFrom(gridResType.internalType())) {
        throw new ProblemException(
            TypeProblems.get().requiresOneOf(getArgument("grid-resolution"),
                Arrays.asList(Types.INTEGER, Types.FLOATING),
                gridResType)
        );
      }

      RecursiveQuadGridOp cutOp = new RecursiveQuadGridOp();
      ProjectGeometryOp projOp = new ProjectGeometryOp(sridSet);

      return RiskscapeFunction.create(this, argumentTypes, newReturnType, args -> {
        Tuple tuple = (Tuple) args.get(0);
        double gridResolution = ((Number) args.get(1)).doubleValue();

        if (!GRID_RANGE.contains(gridResolution)) {
          throw new RiskscapeException(
              GeneralProblems.get().valueOutOfRange(getArgument("grid-resolution"), gridResolution, GRID_RANGE)
          );
        }

        TypedCoverage[] coverages = Arrays.asList(tuple.toArray()).toArray(new TypedCoverage[0]);
        return MultiCoverage.create(builtType, coverages, valueSetters, sridSet, (geom, origin) -> {
          // when sampling the MultiCoverage we want to cut the input geom by a grid.
          // Project it to a metric CRS first, so we can cut it by the gridResolution (in metres)
          return projOp.apply(geom).stream().flatMap(projected ->
            cutOp
                .apply(projected.getProjected(), gridResolution, (Point) projected.projectAlso(origin))
                .stream()
                .map(cutGeom -> projected.toSourceCrs(cutGeom))
          ).collect(Collectors.toList());
        });
      });
    });
  }

  private Struct buildCoverageStruct(Struct components) throws ProblemException {
    Struct building = Struct.EMPTY_STRUCT;
    for (StructMember member : components.getMembers()) {
      CoverageType coverageType = member.getType().findAllowNull(CoverageType.class).orElse(null);
      if (coverageType == null) {
        throw new ProblemException(Problems.foundWith(getArgument("coverages"),
            TypeProblems.get().mismatch(
            member,
            CoverageType.WILD,
            member.getType()
        )));
      } else {
        String coverageName = member.getKey();
        Optional<Struct> structOr = coverageType.getMemberType().findAllowNull(Struct.class);
        if (! structOr.isPresent()) {
          building = building.add(member.getKey(), Nullable.of(coverageType.getMemberType()));
        } else {
          Struct child = structOr.get();
          for (StructMember childMember: child.getMembers()) {
            Type childType = childMember.getType();
            if (childType.findAllowNull(Geom.class).isPresent()) {
              // we don't include geometry members in combine coverage results
              continue;
            }
            building = building.add(
                String.format("%s_%s", coverageName, childMember.getKey()),
                Nullable.of(childType));
          }
        }
      }
    }

    return building;
  }

  private RawValueSetter[] buildCoverageValueSetters(Struct components) throws ProblemException {
    List<RawValueSetter> evaluators = new ArrayList<>();
    AtomicInteger idx = new AtomicInteger();

    for (StructMember member : components.getMembers()) {
      CoverageType coverageType = member.getType().findAllowNull(CoverageType.class).orElse(null);
      if (coverageType == null) {
        throw new ProblemException(Problems.foundWith(getArgument("coverages"),
            TypeProblems.get().mismatch(
            member,
            CoverageType.WILD,
            member.getType()
        )));
      }
      Optional<Struct> structOr = coverageType.getMemberType().findAllowNull(Struct.class);
      int indexAt = idx.get();
      if (!structOr.isPresent()) {
        evaluators.add((value, rawValues) -> rawValues.set(indexAt, value));
        idx.getAndIncrement();
      } else {
        Struct child = structOr.get();
        List<StructMember> childMembersToInclude = new ArrayList<>();
        for (StructMember childMember : child.getMembers()) {
          Type childType = childMember.getType();
          if (childType.findAllowNull(Geom.class).isPresent()) {
            // we don't include geometry members in combine coverage results
            continue;
          }
          idx.getAndIncrement();
          childMembersToInclude.add(childMember);
        }
        evaluators.add((value, rawValues) -> {
          Tuple tuple = (Tuple) value;
          for (int j = 0; j < childMembersToInclude.size(); j++) {
            StructMember childMember = childMembersToInclude.get(j);
            rawValues.set(indexAt + j, tuple.fetch(childMember));
          }
        });
      }
    }
    return evaluators.toArray(new RawValueSetter[0]);
  }

  /**
   * @return a named {@link FunctionArgument}, for errors.
   */
  private FunctionArgument getArgument(String name) {
    return getArguments().get(name);
  }
}
