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

import nz.org.riskscape.engine.ArgsProblems;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.function.ArgumentList;
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.Struct;
import nz.org.riskscape.engine.types.Struct.StructBuilder;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.rl.ast.ExpressionProblems;
import nz.org.riskscape.rl.ast.FunctionCall;

import lombok.RequiredArgsConstructor;

/**
 * Calculates percentiles using the nearest-rank method.
 */
public class PercentileAggregationFunction extends ListCollecting {

  public static final Type PERCENTILE_TYPE = Types.INTEGER;
  public static final RSList PERCENTILES_TYPE = RSList.create(PERCENTILE_TYPE);

  public interface LocalProblems extends ProblemFactory {

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

    Problem percentileOutOfRange(Long percentile);
  }

  @Override
  public ArgumentList getArguments() {
    return ArgumentList.create(
            "items", RSList.LIST_ANYTHING,
            "percentiles", RSList.create(Types.INTEGER)
    );
  }

  /**
   * A {@link PercentileAggregationFunction} that returns a single predefined percentile. The return
   * type matches the input type as there is no need to wrap the result in a struct
   */
  @RequiredArgsConstructor
  public static class SingleFixed extends PercentileAggregationFunction {
    private final Long percentile;

    @Override
    public ArgumentList getArguments() {
      return ArgumentList.create(
              "items", RSList.LIST_ANYTHING,
              "percentile", Types.INTEGER
      );
    }

    @Override
    protected List<Long> getPercentiles(RealizationContext context, FunctionCall fc) throws ProblemException {
      if (fc.getArguments().size() != 1) {
        throw new ProblemException(ArgsProblems.get().wrongNumber(1, fc.getArguments().size()));
      }
      return Arrays.asList(percentile);
    }

    @Override
    protected Type getResultTypeFor(Type internalType, List<Long> percentiles) throws ProblemException {
      return internalType;
    }

    @Override
    protected Object buildResult(Object[] results, Type resultType) {
      return results[0];
    }
  }

  /**
   * A {@link PercentileAggregationFunction} that returns a single percentile. The return
   * type matches the input type as there is no need to wrap the result in a struct
   */
  @RequiredArgsConstructor
  public static class Single extends PercentileAggregationFunction {

    @Override
    protected List<Long> getPercentiles(RealizationContext context, FunctionCall fc) throws ProblemException {
      if (fc.getArguments().size() != 2) {
        throw new ProblemException(ArgsProblems.get().wrongNumber(2, fc.getArguments().size()));
      }

      RealizedExpression percentilesExpression = context.getExpressionRealizer()
          .realize(Struct.EMPTY_STRUCT, fc.getArguments().get(1).getExpression())
          .orElse(null);
      if (percentilesExpression == null) {
        throw new ProblemException(ExpressionProblems.get().constantRequired(
            fc.getArguments().get(1).getExpression()));
      }
      Types.findOrThrow(fc.getArguments().get(1), PERCENTILE_TYPE, percentilesExpression.getResultType());

      return Arrays.asList((Long) percentilesExpression.evaluate(Tuple.EMPTY_TUPLE));
    }

    @Override
    protected Type getResultTypeFor(Type internalType, List<Long> percentiles) throws ProblemException {
      return internalType;
    }

    @Override
    protected Object buildResult(Object[] results, Type resultType) {
      return results[0];
    }
  }

  @Override
  protected ListProcessor buildProcessor(RSList listType, RealizationContext context, Type inputType,
      FunctionCall fc) throws ProblemException {

    if (!listType.getMemberType().isNumeric()) {
      throw new ProblemException(ListCollecting.LocalProblems.get()
          .valueNotNumeric("percentiles", listType.getMemberType()));
    }

    List<Long> percentiles = getPercentiles(context, fc);
    Type resultType = getResultTypeFor(listType.getMemberType(), percentiles);
    return new ListProcessor(resultType, values -> buildResult(pickPercentiles(values, percentiles), resultType));
  }

  /**
   * @return list of percentiles that need to be found.
   */
  @SuppressWarnings("unchecked")
  protected List<Long> getPercentiles(RealizationContext context, FunctionCall fc) throws ProblemException {
    if (fc.getArguments().size() != 2) {
      throw new ProblemException(ArgsProblems.get().wrongNumber(2, fc.getArguments().size()));
    }

    RealizedExpression percentilesExpression = context.getExpressionRealizer()
          .realize(Struct.EMPTY_STRUCT, fc.getArguments().get(1).getExpression())
          .orElse(null);
    if (percentilesExpression == null) {
      throw new ProblemException(ExpressionProblems.get().constantRequired(
          fc.getArguments().get(1).getExpression()));
    }
    // percentiles argument must contain a list of integers
    RSList percentilesType = Types.findOrThrow(fc.getArguments().get(1),
        PERCENTILES_TYPE, percentilesExpression.getResultType());
    Types.findOrThrow(fc.getArguments().get(1), PERCENTILE_TYPE, percentilesType.getContainedType());

    return (List<Long>)percentilesExpression.evaluate(Tuple.EMPTY_TUPLE);
  }

  @SuppressWarnings("unchecked")
  private Object[] pickPercentiles(List values, List<Long> percentiles) {
    List<Number> numbers = (List<Number>) values;
    numbers.sort((l, r) -> ((Comparable) l).compareTo(r));

    Object[] results = new Object[percentiles.size()];
    for (int i = 0; i < percentiles.size(); i++) {
      int percentile = percentiles.get(i).intValue();
      int index = (percentile * numbers.size()) / 100;
      if (index >= numbers.size()) {
        // we can't go beyond the last item
        index = numbers.size() - 1;
      }
      results[i] = numbers.get(index);
    }

    return results;
  }

  protected Object buildResult(Object[] results, Type resultType) {
    return Tuple.ofValues(Nullable.strip(resultType).asStruct(), results);
  }

  protected Type getResultTypeFor(Type internalType, List<Long> percentiles) throws ProblemException {
    StructBuilder sb = Struct.builder();
    boolean nullable = Nullable.is(internalType);
    for (Long percentile : percentiles) {
      if (percentile < 0 || percentile > 100) {
        throw new ProblemException(LocalProblems.get().percentileOutOfRange(percentile));
      }
      sb.add(String.format("P%02d", percentile), Nullable.strip(internalType));
    }
    return Nullable.ifTrue(nullable, sb.buildOr().getOrThrow());
  }

}
