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

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.NoSuchObjectException;
import nz.org.riskscape.engine.function.IdentifiedFunction;
import nz.org.riskscape.engine.rl.DefaultExpressionRealizer;
import nz.org.riskscape.engine.rl.ExpressionRealizer;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.rl.UnresolvedExpressionParameterException;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.BinaryOperation;
import nz.org.riskscape.rl.ast.BracketedExpression;
import nz.org.riskscape.rl.ast.Constant;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.ExpressionVisitor;
import nz.org.riskscape.rl.ast.FunctionCall;
import nz.org.riskscape.rl.ast.FunctionCall.Argument;
import nz.org.riskscape.rl.ast.Lambda;
import nz.org.riskscape.rl.ast.ListDeclaration;
import nz.org.riskscape.rl.ast.ParameterToken;
import nz.org.riskscape.rl.ast.PropertyAccess;
import nz.org.riskscape.rl.ast.SelectAllExpression;
import nz.org.riskscape.rl.ast.StructDeclaration;

/**
 * Does all the work for {@link DefaultExpressionRealizer#realizeAggregate(Type, Expression)}
 */
@RequiredArgsConstructor
public class AggregateExpressionRealizer implements ExpressionVisitor<List<Problem>, Expression> {

  /**
   * Returns an identifier for use in an aggregate struct expression for the given aggregation function call, where the
   * user hasn't specified one.
   *
   * Note this is a simpler routine than that adopted for scalar expressions
   * {@link ExpressionRealizer#getImplicitName(RealizationContext, RealizedExpression, Collection)} as a
   * {@link RealizedAggregateExpression} does not expose as much 'structure' via its API (compared to a
   * {@link RealizedExpression}.  Given how realization for aggregate expressions is currently implemented, it doesn't
   * really matter in practice and decent names are given in most situations that agree with the names that scalar
   * struct expressions would be given.
   */
  public static String getImplicitName(FunctionCall aggregateFunctionCall, Collection<String> used) {
    String ident = aggregateFunctionCall.getIdentifier().getValue();

    // for unary functions, append the first arg's property name, or nothing if nothing
    if (aggregateFunctionCall.getArguments().size() == 1) {
      ident = ident + aggregateFunctionCall.getArguments().get(0).getExpression().isA(PropertyAccess.class)
        .map(pa -> "_" + pa.getLastIdentifier().rawValue())
        .orElse("");
    }

    return ExpressionRealizer.makeUnique(ident, used);
  }

  private final RealizationContext context;
  private final Type inputType;
  private final Expression root;
  private Map<FunctionCall, Pair<RealizedAggregateExpression, String>> realizedFunctions = new HashMap<>();
  private List<Problem> allProblems = new ArrayList<>();

  public ResultOrProblems<RealizedAggregateExpression> realize() {
    // find all the aggregate functions, realize them, and rebuild the expression with all the agg function calls
    // replaced as property access expressions
    Expression rewritten = root.accept(this, allProblems);
    // our input type is now just the results of the functions
    Struct.StructBuilder builder = Struct.builder();

    for (Pair<RealizedAggregateExpression, String> entry : realizedFunctions.values()) {
      builder.add(entry.getRight(), entry.getLeft().getResultType());
    }

    if (allProblems.size() > 0) {
      return ResultOrProblems.failed(allProblems);
    }

    Struct processingInputType = builder.build();
    RealizedExpression processingExpression = collect(
        context.getExpressionRealizer().realize(processingInputType, rewritten));

    if (processingExpression == null) {
      return ResultOrProblems.failed(allProblems);
    }

    return ResultOrProblems.of(
        RealizedAggregateExpression.create(
            inputType,
            processingExpression.getResultType(),
            root,
            () -> new ExpressionAccumulator(
                realizedFunctions.values().stream().map(r -> r.getLeft().newAccumulator()).collect(Collectors.toList()),
                processingExpression
            ))
    );

  }

  @Override
  public Expression visit(BinaryOperation expression, List<Problem> data) {
    return new BinaryOperation(
        expression.getLhs().accept(this, data),
        expression.getOperator(),
        expression.getRhs().accept(this, data)
    );
  }

  @Override
  public Expression visit(BracketedExpression expression, List<Problem> data) {
    return new BracketedExpression(expression.accept(this, data), Optional.empty());
  }

  @Override
  public Expression visit(Constant expression, List<Problem> data) {
    return expression;
  }

  @Override
  public Expression visit(FunctionCall expression, List<Problem> data) {
    String id = expression.getIdentifier().getValue();

    String ident =
        getImplicitName(expression, realizedFunctions.values().stream()
          .map(Pair::getRight)
          .collect(Collectors.toSet())
        );

    PropertyAccess substitute = PropertyAccess.of(ident);
    // repeat of something we've already done, just return the reference to the previous one
    if (realizedFunctions.containsKey(expression)) {
      return substitute;
    }

    IdentifiedFunction function;
    try {
      function = context.getProject().getFunctionSet().get(id);
    } catch (NoSuchObjectException ex) {
      data.add(Problems.caught(ex));
      return expression;
    }

    AggregationFunction aggFunction = function.getAggregationFunction().orElse(null);

    if (aggFunction == null) {
      // not an aggregate function, attempt to rewrite
      return rewrite(expression, data);
    } else {
      ResultOrProblems<RealizedAggregateExpression> realizedFunction =
          aggFunction.realize(context, inputType, expression);

      // XXX is there a case where we want to support an aggregate function being used in a non-aggregated way?
      // It adds a bunch of complexity and I'm not sure it's worth the hassle without a decent use case
      if (realizedFunction.hasErrors()) {
        data.add(ExpressionProblems.get().failedToRealize(expression, inputType)
            .withChildren(realizedFunction.getProblems()));

        return expression;
      } else {
        // ok, it worked, we remember the function's realized expression and substitute it with a pickled property
        // access expression of our own creation
        realizedFunctions.put(expression, Pair.of(realizedFunction.get(), ident));
        return substitute;
      }
    }
  }

  private Expression rewrite(FunctionCall expression, List<Problem> data) {
    List<Argument> rewrittenArguments =
        expression.getArguments().stream().map(arg -> new Argument(arg.getExpression().accept(this, data),
            arg.getNameToken())).collect(Collectors.toList());

    return new FunctionCall(expression.getIdentifier(), rewrittenArguments);
  }

  private <T> T collect(ResultOrProblems<T> realize) {
    if (realize.hasErrors()) {
      allProblems.addAll(realize.getProblems());
      return null;
    } else {
      return realize.get();
    }
  }

  @Override
  public Expression visit(ListDeclaration expression, List<Problem> data) {
    return new ListDeclaration(
      expression.getElements().stream().map(expr -> expr.accept(this, data)).collect(Collectors.toList()),
      Optional.empty()
    );
  }

  @Override
  public Expression visit(PropertyAccess expression, List<Problem> data) {
    data.add(ExpressionProblems.get().propertyOutsideOfAggregationFunction(expression));
    return expression;
  }

  @Override
  public Expression visit(StructDeclaration expression, List<Problem> data) {
    return new StructDeclaration(
        expression.getMembers().stream()
          .map(member -> member.cloneWithExpression(member.getExpression().accept(this, data)))
          .collect(Collectors.toList()),
        Optional.empty()
    );
  }

  @Override
  public Expression visit(SelectAllExpression expression, List<Problem> data) {
    return expression;
  }

  @Override
  public Expression visit(Lambda expression, List<Problem> data) {
    return new Lambda(expression.getLeft(), expression.getArguments(), expression.getExpression().accept(this, data));
  }

  @Override
  public Expression visit(ParameterToken parameterToken, List<Problem> data) {
    throw new UnresolvedExpressionParameterException(Collections.singletonList(parameterToken));
  }
}
