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

import lombok.Data;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.rl.RealizationContext;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.util.SegmentedList;
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.ast.Expression;
import nz.org.riskscape.rl.ast.FunctionCall;

/**
 * Base class for an {@link AggregationFunction} that needs to collect encountered items into a list
 * that the {@link ListProcessor} can extract the aggregated result from.
 *
 * By convention the first argument of any function that uses this class should contain the values to
 * be aggregated.
 */
public abstract class ListCollecting implements AggregationFunction {

  public interface LocalProblems extends ProblemFactory {

    static LocalProblems get() {
      return Problems.get(LocalProblems.class);
    }

    /**
     * Problem to be used when an aggregation function is only applicable to numeric values but a
     * non-numeric type is provided.
     *
     * @param aggregationType type of aggregation wanted, e.g 'median'
     * @param valueType the type that was to be aggregated
     * @return problem
     */
    Problem valueNotNumeric(String aggregationType, Type valueType);
  }

  @Data
  @RequiredArgsConstructor
  public static class ListProcessor {

    public ListProcessor(Type resultType, Function<List<Object>, Object> processFunction) {
      this.resultType = resultType;
      this.processFunction = processFunction;
      this.identity = null;
    }

    private final Type resultType;
    private final Function<List<Object>, Object> processFunction;
    private final Object identity;
  }

  @RequiredArgsConstructor
  private static class AccumInstance implements Accumulator {

    @SuppressWarnings("rawtypes")
    private final List accumulated;
    private final RealizedExpression valueExpression;
    private final ListProcessor listProcessor;

    @Override
    @SuppressWarnings("unchecked")
    public Accumulator combine(Accumulator other) {
      AccumInstance rhs = (AccumInstance) other;
      accumulated.addAll(rhs.accumulated);

      return this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void accumulate(Object input) {
      Object toAccumulate = valueExpression.evaluate(input);
      if (toAccumulate == null) {
        // nulls are not accumulated, because null is not a value.
        return;
      }
      accumulated.add(toAccumulate);
    }

    @Override
    public Object process() {
      if (accumulated.isEmpty()) {
        // If accumulated is empty then we can just return identity, which could well be null.
        return listProcessor.identity;
      }
      @SuppressWarnings("unchecked")
      Object processResult = listProcessor.getProcessFunction().apply(accumulated);

      // identity also applies to a null result from the list processor
      if (processResult == null) {
        return listProcessor.identity;
      } else {
        return processResult;
      }
    }

    @Override
    public boolean isEmpty() {
      return accumulated.isEmpty() && listProcessor.getIdentity() == null;
    }
  }

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

    return ProblemException.<RealizedAggregateExpression>catching(() -> {

      if (fc.getArguments().size() == 0) {
        // NB add support for subclass to tell us how many args we expect
        throw new ProblemException(ArgsProblems.get().wrongNumber(1, 0));
      }

      // get and validate list type
      FunctionCall.Argument arg = fc.getArguments().get(0);
      RealizedExpression valueExpression = context.getExpressionRealizer()
          .realize(inputType, arg.getExpression())
          .getOrThrow(Problems.foundWith(arg));

      RSList listType = RSList.create(valueExpression.getResultType());

      ListProcessor processor = buildProcessor(listType, context, inputType, fc);

      Type resultType;
      if (processor.identity != null) {
        // if identity is given we never return null
        resultType = Nullable.strip(processor.getResultType());
      } else {
        resultType = processor.getResultType();
      }

      return new RealizedAggregateExpression() {

        @Override
        public Accumulator newAccumulator() {
          return new AccumInstance(
              SegmentedList.forType(valueExpression.getResultType()),
              valueExpression,
              processor
          );
        }

        @Override
        public Type getResultType() {
          return resultType;
        }

        @Override
        public Type getInputType() {
          return inputType;
        }

        @Override
        public Expression getExpression() {
          return fc;
        }
      };

      // add context to any error
    }).composeProblems(Problems.foundWith(fc));
  }

  /**
   * Build a {@link ListProcessor} that can produce the aggregated result.
   *
   * @param listType type of the list that will be passed to built processor
   * @param context context to realize any other expressions with
   * @param inputType
   * @param fc
   * @return list processor to capable of producing aggregated result
   * @throws ProblemException with any problems encountered
   */
  protected abstract ListProcessor buildProcessor(RSList listType, RealizationContext context, Type inputType,
      FunctionCall fc) throws ProblemException;


}
