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

import java.util.List;

import nz.org.riskscape.dsl.Token;
import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.FunctionMetadata;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.function.UntypedFunction;
import nz.org.riskscape.engine.function.UserDefinedFunction;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.typeset.TypeSet;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.FunctionCall;
import nz.org.riskscape.rl.ast.Lambda;

public class RealizableExpressionFunction extends UserDefinedFunction {

  private Lambda lambda;

  public RealizableExpressionFunction(FunctionMetadata details, Resource functionSource, Lambda ast) {
    super(details, functionSource);
    this.lambda = ast;
  }

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

    if (!areArgumentsCompatible(context, givenTypes)) {
      return ResultOrProblems.failed(getArgumentProblems(context, givenTypes));
    }

    if (lambda.getArguments().size() != givenTypes.size()) {
      return ResultOrProblems.failed(ArgsProblems.get().wrongNumber(lambda.getArguments().size(), givenTypes.size()));
    }

    int index = 0;
    Struct lambdaScope = Struct.EMPTY_STRUCT;
    // build up the lambda scope based on the defined args for the function
    for (Type type : givenTypes) {
      Token argToken = lambda.getArguments().get(index++);
      lambdaScope = lambdaScope.add(argToken.value, type);
    }

    ResultOrProblems<RealizedExpression> realizedOr = context.getExpressionRealizer().realize(lambdaScope,
        lambda.getExpression());

    if (realizedOr.hasErrors()) {
      return ResultOrProblems.failed(
          ExpressionProblems.get().failedToRealize(lambda, lambdaScope)
            .withChildren(realizedOr.getProblems())
      );
    }
    RealizedExpression realizedLambda = realizedOr.get();
    Struct finalScope = lambdaScope;


    Type declaredReturnType = getMetadata().getReturnType();
    Type inferredReturnType = realizedLambda.getResultType();
    TypeSet typeSet = context.getProject().getTypeSet();

    // assign these based on whether or not we are doing result type coercion.
    UntypedFunction function;
    Type returnType;

    if (typeSet.isAssignable(inferredReturnType, declaredReturnType)) {
      returnType = inferredReturnType;
      function = args -> {
        return realizedLambda.evaluate(Tuple.ofValues(finalScope, args.toArray()));
      };
    } else {
      returnType = declaredReturnType;
      function = args -> {

        Object result = realizedLambda.evaluate(Tuple.ofValues(finalScope, args.toArray()));
        // this is actually casting rather than coercing - but we don't have a type-set aware casting method in
        // riskscape at all, so the function is falling back to the early/primitive Type#coerce method
        try {
          return declaredReturnType.coerce(result);
        } catch (Exception e) {
          throw new RiskscapeException(
            ExpressionFunctionFramework.PROBLEMS.returnTypeCoercionFailed(
                result,
                realizedLambda.getResultType(),
                declaredReturnType
            ).withChildren(Problems.caught(e))
          );
        }
      };
    }

    return ResultOrProblems.of(RiskscapeFunction.create(this, givenTypes, returnType, function, realizedLambda));
  }

}
