/*
 * 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.ArrayList;
import java.util.List;
import java.util.Optional;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.eqrule.Coercer;

import lombok.AccessLevel;

@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class CoercingFunctionWrapper implements RiskscapeFunction {

  /**
   * Return a {@link RiskscapeFunction} that wraps another function to apply any {@link Coercer}s to the
   * input arguments before passing them to the wrapped function.  This function advertises argument types
   * based on the coercer's source type, falling back to the wrapped function's original advertised type if no coercer
   * was present for that argument.
   */
  public static RiskscapeFunction wrap(
      RiskscapeFunction wrapped,
      List<Optional<Coercer>> coercers
  ) {

    if (wrapped.getArgumentTypes().size() > coercers.size()) {
      // There must be coercer entry for every argument type, but it is okay for there to be extras.
      // You get extra coercers when:
      // - function is realizable and has optional arguments
      // - this function is called without the optional arguments and other arguments have
      //   null safe handling added.
      //   In this case a null suppling coercer is added to pass null to the null safe function
      //   Following this the function is realized with the actual args(coerced as necessary) and re-wrapped
      //   at which point the optional arg is not present.
      // See SampleOneRealizationTest#findsSampleWhenCalledWithComplexFunctionAdapting for an
      // example of this
      throw new IllegalArgumentException("There must be a coercer for every argument type");
    }

    List<Type> argumentTypes = new ArrayList<>(coercers.size());
    for (int i = 0; i < wrapped.getArgumentTypes().size(); i++) {
      argumentTypes.add(coercers.get(i)
          .map(Coercer::getSourceType)
          .orElse(wrapped.getArgumentTypes().get(i)));
    }
    // NB should we check that the resulting target argument type list is covariant with what the function
    // says it expects? There's a chance, because of programmer confusion (likely given this code), that
    // we end up with a function that says it accepts a type, but actually the wrapped function doesn't
    return new CoercingFunctionWrapper(coercers, wrapped, argumentTypes);
  }

  @Getter
  private final List<Optional<Coercer>> coercers;
  @Getter
  private final RiskscapeFunction wrapped;

  // TODO clone argument list
  @Getter
  private final List<Type> argumentTypes;

  @Override
  public Object call(List<Object> args) {
    List<Object> coerced = new ArrayList<>(args.size());

    for (int i = 0; i < args.size(); i++) {
      Object argValue = args.get(i);
      coerced.add(coercers.get(i).map(c -> c.apply(argValue)).orElse(argValue));
    }

    return wrapped.call(coerced);
  }

  @Override
  public Type getReturnType() {
    return wrapped.getReturnType();
  }

  @Override
  public void close() {
    wrapped.close();
  }

  @Override
  public String toString() {
    return String.format("Coercing(%s)", wrapped);
  }

}
