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

import lombok.Getter;
import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.data.InputDataProblems;
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.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.eqrule.PartialStructRule;
import nz.org.riskscape.engine.typeset.TypeSet;
import nz.org.riskscape.problem.Problem;

/**
 * Represents a function defined by the user in a script file (e.g. Jython,
 * CPython, etc). User-defined functions are realizable, so we can provide the
 * user with an in-depth error message if the types don't line up. Users are
 * much more likely to hit type errors defining their own functions, so we can
 * be more specific about pointing them in the right direction.
 */
public abstract class UserDefinedFunction implements RealizableFunction {

  @Getter
  private final FunctionMetadata metadata;

  @Getter
  private final Resource script;

  // memoized result from identified to avoid proliferating these in objects in various situations.  Thread safety not
  // a concern here - if we end up with two or three of these objects, it doesn't matter.
  private IdentifiedFunction identified;

  public UserDefinedFunction(FunctionMetadata details, Resource script) {
    this.metadata = details;
    this.script = script;
  }

  public List<Type> getDeclaredArgumentTypes() {
    return metadata.getArguments().getArgumentTypes();
  }

  /**
   * @return true if the given arguments are compatible with this function, false if not
   */
  public boolean areArgumentsCompatible(RealizationContext context, List<Type> givenArgs) {
    return metadata.getArguments().isCompatible(context, givenArgs);
  }

  /**
   * @return A list of problems associated with the given arguments, or an empty list if there are no problems
   */
  public List<Problem> getArgumentProblems(RealizationContext context, List<Type> givenArgs) {
    return metadata.getArguments().getProblems(context, givenArgs,
        (expected, given) -> describeMismatch(context, expected, given));
  }

  private List<Problem> describeMismatch(RealizationContext context, FunctionArgument expectedArg, Type given) {
    TypeSet typeset = context.getProject().getTypeSet();
    Problem mismatch = ArgsProblems.mismatch(expectedArg, given);

    // structs can be particularly confusing for users to decipher, so try to hone in
    // on the struct member that's resulting in the mismatch
    Optional<Struct> expectedStructOr = expectedArg.getType().find(Struct.class);
    Optional<Struct> givenStructOr = given.find(Struct.class);
    if (expectedStructOr.isPresent() && givenStructOr.isPresent()) {
      mismatch = mismatch.withChildren(
          describeMismatch(typeset, givenStructOr.get(), expectedStructOr.get()));
    }
    return Arrays.asList(mismatch);
  }

  private List<Problem> describeMismatch(TypeSet typeset, Struct given, Struct expected) {
    // generally it's going to be the PartialStructRule that failed to match,
    // so drill down into what struct members specifically didn't match
    List<Problem> problems = PartialStructRule.describeMismatch(typeset, given, expected);

    if (!problems.isEmpty()) {
      // it's probably a problem with the input data, so point the user in that direction
      problems.add(InputDataProblems.get().doesNotMatchType());
    }
    return problems;
  }

  public IdentifiedFunction identified() {
    if (identified == null) {
      identified = RealizableFunction.identified(this, metadata);
    }
    return identified;
  }
}
