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

import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import nz.org.riskscape.engine.Identified;
import nz.org.riskscape.engine.function.IdentifiedFunction.Category;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.rl.RealizableFunction;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.rl.agg.AggregationFunction;
import nz.org.riskscape.engine.rl.agg.RealizedAggregateExpression;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * General interface for any kind of function that accepts and returns riskscape types values.
 */
public interface RiskscapeFunction extends UntypedFunction, AutoCloseable {

  Logger LOG = LoggerFactory.getLogger(RiskscapeFunction.class);

  /**
   * Create a {@link RiskscapeFunction} from the given types and untyped function.  Note that this won't add any type
   * checking or coercion around the function call, it simply serves as a way to add the type metadata to an
   * {@link UntypedFunction} to make it fulfill the {@link RiskscapeFunction} interface.
   *
   * Also accepts an optional list of {@link AutoCloseable} objects to clean up when the function gets closed.  It's
   * worthy of note that there is no standard mechanism for cleaning up resources allocated to functions that realize
   * lambda expressions - the closing of any {@link RealizedExpression}s or related objects must be done by the function
   * when it's closed.  If a lambda scope or function is passed around as data in a tuple, then there is no standard
   * way to clean up resources attached to it (see https://gitlab.catalyst.net.nz/riskscape/riskscape/-/issues/1441
   * as an example of this.
   *
   * @param source an object to use in the toString of this function to track where it came from, or null to just
   * use the function as the source
   * @param function a function we are extending with type metadata.
   * @param closeThese any {@link AutoCloseable} resources to clean up when this function is closed.  Can pass nulls,
   * they will be skipped/ignored
   * @return a RiskscapeFunction that can be used as part of a RiskScape expression
   */
  static RiskscapeFunction create(
      Object source,
      List<Type> argumentTypes,
      Type returnType,
      UntypedFunction function,
      AutoCloseable... closeThese
  ) {

    // add any non-null elements of closeThese - The if function in particular is simpler if we can throw possibly null
    // values in to the constructor
    List<AutoCloseable> closeables = Stream.of(closeThese).filter(el -> el != null).toList();

    return new RiskscapeFunction() {

      @Override
      public Object call(List<Object> args) {
        return function.call(args);
      }

      @Override
      public Type getReturnType() {
        return returnType;
      }

      @Override
      public List<Type> getArgumentTypes() {
        return argumentTypes;
      }

      @Override
      public String toString() {
        String sourceString;

        if (source == null) {
          sourceString = function.toString();
        } else {
          if (source instanceof Class<?>) {
            sourceString = ((Class<?>) source).getSimpleName();
          } else if (source instanceof RealizableFunction) {
            sourceString = source.getClass().getSimpleName();
          } else if (source instanceof Identified) {
            sourceString = ((Identified) source).getId();
          } else {
            sourceString = source.toString();
          }
        }

        return String.format(
            "Function(argTypes=%s returnType=%s source=%s)", argumentTypes, returnType, sourceString);
      }

      @Override
      public void close() {
        for (AutoCloseable closeable : closeables) {
          try {
            closeable.close();
          } catch (Exception e) {
            LOG.error("Exception closing {}", closeable, e);
          }
        }
      }
    };
  }

  // denotes a built-in function that's provided by RiskScape,
  // i.e. standard maths functions like log(), norm_cdf()
  URI BUILT_IN = URI.create("internal:internal");

  /**
   * @return the types that this function expects
   */
  List<Type> getArgumentTypes();

  /**
   * @return the type that this function should return
   */
  Type getReturnType();

  /**
   * Validate that the function can be run.
   *
   * To be considered valid there should be no {@link Problem}s found that are at error or fatal. Finding problems
   * of lower severity should not make a function invalid.
   *
   * @return ResultOrProblems indicating if function is valid
   */
  default ResultOrProblems<Boolean> validate(RealizationContext context) {
    return ResultOrProblems.of(true);
  }

  /**
   * @return a {@link RealizableFunction} that can realize this {@link RiskscapeFunction} against a type, or empty if
   * this function does not support realization.
   */
  default Optional<RealizableFunction> getRealizable() {
    if (this instanceof RealizableFunction) {
      return Optional.of((RealizableFunction) this);
    } else {
      return Optional.empty();
    }
  }

  /**
   * @return an {@link OverloadedFunction} that offers alternative input types for use within an expression, or empty if
   * this function does not support overloading
   */
  default Optional<OverloadedFunction> getOverloaded() {
    if (this instanceof OverloadedFunction) {
      return Optional.of((OverloadedFunction) this);
    } else {
      return Optional.empty();
    }
  }

  /**
   * @return An {@link AggregationFunction} that is functionally the same operation as this, but works with a
   * {@link RealizedAggregateExpression}, rather than against a {@link RealizedExpression} with an {@link RSList}.
   */
  default Optional<AggregationFunction> getAggregationFunction() {
    if (this instanceof AggregationFunction) {
      return Optional.of((AggregationFunction) this);
    } else {
      return Optional.empty();
    }
  }

  default ArgumentList getArguments() {
    return ArgumentList.anonymous(getArgumentTypes());
  }

  default List<Type> getTypesFromArguments() {
    return getArguments().getArgumentTypes();
  }

  /**
   * Set a problem report that this function may use to issue {@link Problem}s to if any are encountered
   * whilst the function is being called.
   *
   * Any {@link Problem}s sent to the problemReporter should clearly state what function they came from.
   *
   * @param problemReporter
   */
  default void setProblemReporter(Consumer<Problem> problemReporter) {}

  /**
   * @return an {@link IdentifiedFunction} that wraps this function with the given metadata.
   * Note that for built-in functions, {@link #builtin(String, IdentifiedFunction.Category)} is probably
   * a better choice to use (i.e. is simpler and encourages i18n description).
   */
  default IdentifiedFunction identified(String id, String description, URI source, Category category) {
    return new IdentifiedFunction.Wrapping(this, id, description, source, category);
  }

  /**
   * @return an {@link IdentifiedFunction} that wraps this function with the given metadata
   */
  default IdentifiedFunction builtin(String id, Category category) {
    // note that function description should go in i18n help.properties file
    // instead of hard-coding it in the code
    return identified(id, "", BUILT_IN, category);
  }

  /**
   * @return alternative to {@link #identified(String, String, String, IdentifiedFunction.Category)}
   *         that is suitable for test cases
   */
  default IdentifiedFunction identified(String id) {
    return identified(id, "none given", Resource.UNKNOWN_URI, Category.UNASSIGNED);
  }

  default <T extends RiskscapeFunction> Optional<T> isA(Class<T> type) {
    if (type.isInstance(this)) {
      return Optional.of(type.cast(this));
    } else {
      return Optional.empty();
    }
  }

  @Override
  default void close() {
    // do nothing by default
  }
}
