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

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.BaseRealizableFunction;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.function.agg.AggregationFunctionAdapter;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.rl.agg.AggregationFunction;
import nz.org.riskscape.engine.rl.agg.RealizedAggregateExpression;
import nz.org.riskscape.engine.types.LambdaType;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.ScopedLambdaType;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ExpressionParser;
import nz.org.riskscape.rl.TokenTypes;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.ExpressionConverter;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.FunctionCall;
import nz.org.riskscape.rl.ast.Lambda;
import nz.org.riskscape.rl.ast.PropertyAccess;

public class MapStruct extends BaseRealizableFunction implements AggregationFunction {

  public interface LocalProblems extends ProblemFactory {
    Problem lambdaNotCompatibleAllAttributesHint(Struct given);
  }

  public static final LocalProblems PROBLEMS = Problems.get(LocalProblems.class);

  private record AttributeMapper(String attribute, BiFunction<Object, ScopedLambdaExpression, Object> mapper) {};

  public static final ArgumentList ARGUMENTS = ArgumentList.create(
      "struct", Types.ANYTHING,
      "mapper", new LambdaType("item")
  );

  public MapStruct() {
    super(ARGUMENTS, Types.ANYTHING);
  }

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

    return ProblemException.catching(() -> {
      getArguments().validateArity(givenTypes);

      if (givenTypes.get(0).find(RSList.class).isPresent()) {
        // if the we've been given a list then realize via the AggregationFunctionAdaptor
        return new AggregationFunctionAdapter(this)
            .realize(context, functionCall, givenTypes)
            .getOrThrow();
      }
      boolean nullable = givenTypes.get(0).isNullable();
      Struct itemType = givenTypes.get(0)
          .findAllowNull(Struct.class)
          .orElse(null);

      ScopedLambdaType lambdaType = givenTypes.get(1).find(ScopedLambdaType.class)
          .orElseThrow(() -> new ProblemException(ArgsProblems.mismatch(ARGUMENTS.get("mapper"), givenTypes.get(1))));

      Lambda lambda = functionCall.getArguments().get(1).getExpression().isA(Lambda.class).get();
      if (lambdaType.getArity() != 1) {
        throw new ProblemException(ExpressionProblems.get().lambdaArityError(lambda, lambdaType.getArity(), 1));
      }

      if (itemType == null) {
        // item is not a struct, oh well let's just apply the mapper to whatever it is.
        // Strip and reapply nullable, so that if the item is null, then the lambda result will also be null
        // (i.e. typical null-safe wrapper behaviour)
        Struct lambdaScopeType = lambdaType.buildCallingScopeType(Nullable.strip(givenTypes.get(0)));
        RealizedExpression realizedLambda = context.getExpressionRealizer()
            .realize(lambdaScopeType, lambda.getExpression())
            .getOrThrow();

        return RiskscapeFunction.create(this, givenTypes, Nullable.ifTrue(nullable, realizedLambda.getResultType()),
            args -> {
          Object input = args.get(0);
          if (input == null) {
            return null;
          }
          ScopedLambdaExpression givenLambda = (ScopedLambdaExpression) args.get(1);

          Tuple lambdaScope = givenLambda.buildCallingScope(lambdaScopeType);
          StructMember listElementDestMember = lambdaScopeType.getEntry(lambdaType.getArgs().get(0));
          lambdaScope.set(listElementDestMember, input);

          return realizedLambda.evaluate(lambdaScope);
        });
      }

      List<AttributeMapper> attributeMappers = new ArrayList<>();
      Struct sb = Struct.EMPTY_STRUCT;
      for (StructMember member : itemType.getMembers()) {
        Struct lambdaScopeType = lambdaType.buildCallingScopeType(member.getType());
        RealizedExpression realizedLambda = context.getExpressionRealizer()
            .realize(lambdaScopeType, lambda.getExpression())
            .getOrThrow((probs) ->  Problems.foundWith(StructMember.class, member.getKey())
            .withChildren(probs, PROBLEMS.lambdaNotCompatibleAllAttributesHint(itemType))
            );

        BiFunction<Object, ScopedLambdaExpression, Object> mapper = (value, givenLambda) -> {
          Tuple lambdaScope = givenLambda.buildCallingScope(lambdaScopeType);
          StructMember listElementDestMember = lambdaScopeType.getEntry(lambdaType.getArgs().get(0));
          lambdaScope.set(listElementDestMember, value);

          return realizedLambda.evaluate(lambdaScope);
        };

        attributeMappers.add(new AttributeMapper(member.getKey(), mapper));
        sb = sb.add(member.getKey(), realizedLambda.getResultType());
      }
      Struct mappedType = context.normalizeStruct(sb);

      return RiskscapeFunction.create(this, givenTypes, Nullable.ifTrue(nullable, mappedType), args -> {
        Tuple input = (Tuple) args.get(0);
        if (input == null) {
          return null;
        }

        ScopedLambdaExpression givenLambda = (ScopedLambdaExpression) args.get(1);

        Tuple result = Tuple.of(mappedType);
        for (AttributeMapper attributeMapper: attributeMappers) {
          result.set(
              attributeMapper.attribute,
              attributeMapper.mapper.apply(input.fetch(attributeMapper.attribute), givenLambda)
          );
        }
        return result;
      });
    });
  }

  @Override
  public RiskscapeFunction asFunction() {
    return AggregationFunction.addAggregationTo(this, super.asFunction());
  }

  @Override
  public ResultOrProblems<RealizedAggregateExpression> realize(RealizationContext context, Type inputType,
      FunctionCall fc) {
    return ProblemException.catching(() -> {
      if (fc.getArguments().size() != 2) {
        // need value expression and a lambda
        throw new ProblemException(ArgsProblems.get().wrongNumber(2, fc.getArguments().size()));
      }

      // get and validate type to aggregate. this is always expected to be in arg: 0
      RealizedExpression itemExpression = context.getExpressionRealizer()
          .realize(inputType, fc.getArguments().get(0).getExpression())
          .getOrThrow(probs -> Problems.foundWith(fc.getArguments().get(0), probs));

      Struct itemType = itemExpression.getResultType()
          .findAllowNull(Struct.class)
          .orElseThrow(() -> new ProblemException(
              ArgsProblems.mismatch(ARGUMENTS.get("struct"), itemExpression.getResultType()))
          );

      // base case - make sure we don't try and process an empty struct, we can just return an empty struct as
      // the result
      if (itemType.size() == 0) {
        return context.getExpressionRealizer().realizeAggregate(inputType, ExpressionParser.parseString("{}"))
            .getOrThrow();
      }

      // we get the lambda only to validate that it is correct and that it can be realized for each attribute
      // in the struct. but we don't ever evaluate lambdas here, we will defer to aggregate_struct for that
      Lambda lambda = fc.getArguments().get(1).getExpression()
          .isA(Lambda.class)
          .orElseThrow(() -> new ProblemException(
              ExpressionProblems.get().mismatch(fc.getArguments().get(1).getExpression(), Lambda.class, "v -> sum(v)"))
          );

      LambdaType lambdaType = LambdaType.create(lambda);
      if (lambdaType.getArgs().size() != 1) {
        // error, only one expected
        throw new ProblemException(ExpressionProblems.get().lambdaArityError(
            lambda,
            lambdaType.getArgs().size(),
            1
        ));
      }

      // an expression converter that will amend property access expressions for the lambda arg,
      // e.g `v -> mean(v)` will become `v -> mean(v.attr)`
      ExpressionConverter<String> lambdaConverter = new ExpressionConverter<>() {
        @Override
        public Expression visit(PropertyAccess expression, String memberKey) {
          if (expression.toSource().equals(lambdaType.getArgs().get(0))) {
            return ExpressionParser.parseString(
                String.format("%s.%s", expression.toSource(),
                    TokenTypes.quoteIdent(memberKey)
                 ))
                .isA(PropertyAccess.class)
                .orElseThrow();
          }
          return expression;
        }
      };

      List<String> memberLambdas = new ArrayList<>();
      for (StructMember member : itemType.getMembers()) {
        // we realize the lambda against the member type to so we know it will work when passed to aggregate_struct
        // we do this here to have better errors for the user.
        Struct testType = Struct.of(lambdaType.getArgs().get(0), member.getType());
        context.getExpressionRealizer().realizeAggregate(testType, lambda)
            .orElseThrow((problems) ->
                new ProblemException(Problems.foundWith(StructMember.class, member.getKey(), problems)
                  .withChildren(PROBLEMS.lambdaNotCompatibleAllAttributesHint(itemType))
            ));

        memberLambdas.add(String.format(
            "%s: %s",
            TokenTypes.quoteIdent(member.getKey()), lambdaConverter.visit(lambda, member.getKey()).toSource()
        ));
      }

      // we don't want to reinvent the aggregation wheel here so we can rewrite the expression and defer
      // it to aggregate_struct. Our deferred expression should realize fine since we have already validated
      // that the lambda is fine for each arg in the struct.
      FunctionCall compositeExpression = ExpressionParser.parseString(
          memberLambdas.stream()
              .collect(Collectors.joining(
                  ", ",
                  String.format("aggregate_struct(%s, {", itemExpression.getExpression().toSource()),
                  "})"
              ))
      ).isA(FunctionCall.class)
          .orElseThrow();

      return context.getExpressionRealizer().realizeAggregate(inputType, compositeExpression).getOrThrow();
    });
  }

}
