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

import lombok.Getter;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.rl.agg.Accumulator;
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.Struct;
import nz.org.riskscape.engine.types.Struct.StructBuilder;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.TypeProblems;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ast.Expression;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.FunctionCall;
import nz.org.riskscape.rl.ast.Lambda;

public class BucketFunction implements AggregationFunction {

  @Getter
  private final ArgumentList arguments = ArgumentList.create(
      "select", Types.ANYTHING,
      "pick", new LambdaType("aggregation_value"),
      "buckets", Struct.EMPTY_STRUCT
  );

  private static class AccumImpl implements Accumulator {

    private final int size;
    private final Accumulator[] bucketAccumulators;
    private final RealizedExpression pickExpr;
    private final Tuple buckets;
    private final Tuple pickInput;
    private final Struct resultType;
    private int inputSize;

    AccumImpl(Struct resultType, RealizedAggregateExpression selectExpr, RealizedExpression pickExpr,
        Tuple buckets
    ) {
      this.size = resultType.size();
      this.resultType = resultType;
      this.bucketAccumulators = new Accumulator[size];
      this.pickExpr = pickExpr;
      this.pickInput = new Tuple((Struct) pickExpr.getInputType());
      this.buckets = buckets;

      for (int i = 0; i < size; i++) {
        this.bucketAccumulators[i] = selectExpr.newAccumulator();
      }

      this.inputSize = selectExpr.getInputType().find(Struct.class).get().size();
    }

    @Override
    public Accumulator combine(Accumulator rhsObject) {
      AccumImpl rhs = (AccumImpl) rhsObject;

      for (int i = 0; i < size; i++) {
        this.bucketAccumulators[i] = this.bucketAccumulators[i].combine(rhs.bucketAccumulators[i]);
      }

      return this;
    }

    @Override
    public void accumulate(Object input) {
      // build input scope from input tuple
      Tuple inputTuple = (Tuple) input;
      pickInput.setAll(inputTuple);

      // apply bucket to the input tuple, test bucket and accumulate if matching
      for (int i = 0; i < size; i++) {
        pickInput.set(inputSize, buckets.fetch(i));

        if (Boolean.TRUE.equals(pickExpr.evaluate(pickInput))) {
          bucketAccumulators[i].accumulate(input);
        }
      }
    }

    @Override
    public Object process() {
      Tuple result = new Tuple(resultType);

      for (int i = 0; i < size; i++) {
        Accumulator bucketAccum = bucketAccumulators[i];
        if (!bucketAccum.isEmpty()) {
          result.set(i, bucketAccum.process());
        }
      }

      return result;
    }

    @Override
    public boolean isEmpty() {
      return false;
    }

  }

  @Override
  public ResultOrProblems<RealizedAggregateExpression> realize(RealizationContext context, Type inputType,
      FunctionCall fc) {

    return ProblemException.catching(() -> {

      RealizedAggregateExpression selectExpression = arguments.get("select").mapFunctionCall(fc, arg ->
          context.getExpressionRealizer().realizeAggregate(
              inputType,
              arg.getExpression()
          )).getOrThrow();

      Tuple buckets = arguments.get("buckets").evaluateConstant(context, fc, Tuple.class).getOrThrow();

      // members are nullable if a new accumulator is empty
      Type aggregateResultType =
          Nullable.ifTrue(selectExpression.newAccumulator().isEmpty(), selectExpression.getResultType());
      // will be a struct of each bucket
      StructBuilder resultTypeBuilder = Struct.builder();
      for (StructMember member : buckets.getStruct().getMembers()) {
        resultTypeBuilder.add(member.getKey(), aggregateResultType);
      }
      Struct resultType = resultTypeBuilder.build();

      Expression givenPickExpression = arguments.getRequiredArgument(fc, "pick").getOrThrow().getExpression();
      Lambda pick = givenPickExpression.isA(Lambda.class).orElse(null);

      if (pick == null) {
        throw new ProblemException(ExpressionProblems.get().mismatch(
            givenPickExpression,
            Lambda.class,
            "bucket_value -> exposure.category = bucket_value"
        ));
      }

      if (pick.getArguments().size() != 1) {
        throw new ProblemException(ExpressionProblems.get().lambdaArityError(
            givenPickExpression,
            pick.getArguments().size(),
            1
        ));
      }

      Type bucketType = buckets.getStruct().getMembers().stream().map(StructMember::getType).findFirst()
          .orElse(Types.NOTHING);

      // check buckets are of a consistent type
      // TODO sanity check that if they are structs they are also the same object
      for (StructMember bucketsMember : buckets.getStruct().getMembers()) {
        if (!bucketsMember.getType().equals(bucketType)) {
          throw new ProblemException(TypeProblems.get().mismatch(
              "bucket " + bucketsMember.getKey(),
              bucketType,
              bucketsMember.getType())
          );
        }
      }

      Struct lambdaScopeType = inputType.find(Struct.class)
          .get()
          .add(pick.getArguments().get(0).value, bucketType);

      RealizedExpression pickLambda = context.getExpressionRealizer().realize(lambdaScopeType, pick.getExpression())
          .getOrThrow(Problems.foundWith(arguments.get("pick")));

      // make sure it's a boolean expression.
      // We allow Nullable[Bool] as null results will never evaluate to true, so will just be ignored.
      // Otherwise it gets very fiddly to bucket a Nullable loss value (especially as most other
      // aggregate functions default to returning Nullable[Float])
      Types.findOrThrow("pick return type", Types.BOOLEAN, Nullable.strip(pickLambda.getResultType()));

      return RealizedAggregateExpression.create(inputType, resultType, fc, () -> new AccumImpl(
          resultType,
          selectExpression,
          pickLambda,
          buckets
      ));
    });
  }

}
