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

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

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.function.FunctionResolver;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.function.OperatorResolver;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.pipeline.ExecutionContext;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.BinaryOperation;
import nz.org.riskscape.rl.ast.FunctionCall;

/**
 * Minimal interface for a set of {@link IdentifiedFunction}s that can be looked up by an id.
 * <p>
 * NB seems like overkill, but didn't want to pass around maps, where type signatures get big and unwieldy
 */

public class DefaultFunctionSet
extends IdentifiedCollection.Base<IdentifiedFunction>
implements OperatorResolver, FunctionSet {

  private final List<OperatorResolver> operatorResolvers = Lists.newArrayList();

  @Override
  public void validate(ExecutionContext context, Consumer<Problem> problemConsumer) {
    // TODO Make validation a part of all identifiedCollections?
    this.results.values().forEach(handle -> {
      ResultOrProblems<IdentifiedFunction> function = handle.getResult();

      if (function.hasProblems()) {
        problemConsumer.accept(
          GeneralProblems.get().failedToValidate(IdentifiedFunction.class, handle.getId(), handle.getResource())
              .withSeverity(Problem.max(function.getProblems()))
              .withChildren(function.getProblems())
        );
      } else {
        ResultOrProblems<Boolean> validationProblems = function.get().validate(context.getRealizationContext());
        if (validationProblems.hasProblems()) {
          problemConsumer.accept(
            GeneralProblems.get().failedToValidate(IdentifiedFunction.class, handle.getId(), handle.getResource())
                .withSeverity(Problem.max(validationProblems.getProblems()))
                .withChildren(validationProblems.getProblems())
          );
        }
      }
    });
  }

  /**
   * Resolve a function call by using all of the registered {@link FunctionResolver}s in order until one is found
   */

  @Override
  public ResultOrProblems<RiskscapeFunction> resolve(
      RealizationContext context,
      FunctionCall functionCall,
      Type inputType,
      List<Type> argumentTypes,
      FunctionResolver resolver
    ) {

    String functionId = functionCall.getIdentifier().value;

    try {
      return resolver.resolve(context, functionCall, inputType, argumentTypes, get(functionId));
    } catch (IdentifiedException e) {
      return ResultOrProblems.failed(e.getProblem());
    }
  }

  /**
   * Resolve a binary operation by using all of the registered {@link FunctionResolver}s in order until one is found
   */
  @Override
  public Optional<RiskscapeFunction> resolve(RealizationContext context, BinaryOperation operation, Type inputType,
      Type lhs, Type rhs) {
    return operatorResolvers.stream()
        .map(r -> r.resolve(context, operation, inputType, lhs, rhs))
        .filter(p -> p.isPresent())
        .map(Optional::get)
        .findFirst();
  }

  /**
   * Add a new {@link OperatorResolver} with highest precedence.
   */
  @Override
  public void insertFirst(OperatorResolver operatorResolver) {
    operatorResolvers.add(0, operatorResolver);
  }

  /**
   * Add a new {@link OperatorResolver} with lowest precedence.
   */
  @Override
  public void insertLast(OperatorResolver operatorResolver) {
    operatorResolvers.add(operatorResolver);
  }

}
