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

import com.google.common.collect.Range;

import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.bind.ParamProblems;
import nz.org.riskscape.engine.bind.ParameterField;
import nz.org.riskscape.engine.function.ArgumentList;
import nz.org.riskscape.engine.function.BaseRealizableFunction;
import nz.org.riskscape.engine.function.FunctionArgument;
import nz.org.riskscape.engine.function.RiskscapeFunction;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.problem.ProblemFactory;
import nz.org.riskscape.engine.rl.RealizationContext;
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.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.util.FunctionCallOptions;
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.FunctionCall;

public class ListToColumns extends BaseRealizableFunction {

  public interface LocalProblems extends ProblemFactory {
    Problem insufficientListItemsEncountered(int required, int found);
  }

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

  public static final String OPTIONS_ARG_NAME = "columns";

  /**
   * A {@link Struct} defining all options that may be passed to this function.
   */
  public static class Options {

    /**
     * A list of column names to use.
     */
    @ParameterField
    public List<String> names = null;

    /**
     * A prefix to apply to all column names.
     */
    @ParameterField
    public String prefix = "";

    /**
     * The number of columns to process. Used instead of {@link #names}
     */
    @ParameterField
    public Optional<Integer> number = Optional.empty();

    /**
     * The number to assign to the first column when naming {@link #number}.
     */
    @ParameterField
    public Optional<Integer> startNumbering = Optional.empty();

    @ParameterField
    public boolean nullable = true;
  }

  public ListToColumns() {
    super(
        ArgumentList.fromArray(
            new FunctionArgument("list", Nullable.of(RSList.LIST_ANYTHING)),
            FunctionCallOptions.options(OPTIONS_ARG_NAME, Options.class)
        ),
        Types.ANYTHING
    );
  }


  @Override
  public ResultOrProblems<RiskscapeFunction> realize(RealizationContext context, FunctionCall functionCall,
      List<Type> argumentTypes) {
    return ProblemException.catching(() -> {
      getArguments().validateArity(argumentTypes);

      RSList listType = arguments.getRequiredAs(argumentTypes, 0, RSList.class).getOrThrow();
      // options is required in this case.
      arguments.getRequiredArgument(functionCall, OPTIONS_ARG_NAME).getOrThrow();
      Options options = getValidatedOptions(functionCall, context);

      if (options.names.isEmpty()) {
        // the user didn't specify the names so we need to create them using the indexes
        int start = options.startNumbering.orElse(1);
        int end = options.number.get() + options.startNumbering.orElse(1);
        for (int i = start; i < end; i++) {
          options.names.add(String.valueOf(i));
        }
      }

      // struct member type is nullable because we don't know if the list will have as many items
      // as required to fill all the columns
      Type structMemberType = Nullable.ifTrue(options.nullable, listType.getContainedType());
      StructBuilder builder = new StructBuilder();
      for (int i = 0; i < options.names.size(); i++) {
        builder.add(options.prefix + options.names.get(i), structMemberType);
      }
      Struct resultType = builder.build();

      return RiskscapeFunction.create(this, argumentTypes, resultType, args -> {
        List<?> values = (List<?>) args.get(0);
        if (!options.nullable && (values == null || values.size() < resultType.size())) {
          throw new RiskscapeException(
              PROBLEMS.insufficientListItemsEncountered(resultType.size(), values == null ? 0 : values.size())
          );
        }
        if (values == null) {
          return new Tuple(resultType);
        } else {
          Object[] valueArray = values.toArray();
          if (valueArray.length > resultType.size()) {
            // if the value list has more items than required we need to truncate it otherwise the
            // Tuple will blow up
            valueArray = Arrays.copyOf(valueArray, resultType.size());
          }
          return Tuple.ofValues(resultType, valueArray);
        }
      });
    });
  }

  private Options getValidatedOptions(FunctionCall functionCall, RealizationContext context) throws ProblemException {
    // validate that options are okay
    return arguments.getRequiredArgument(functionCall, OPTIONS_ARG_NAME)
        .flatMap(optionsArg -> FunctionCallOptions
            .bindOptions(OPTIONS_ARG_NAME, Options.class, context, arguments, functionCall))
        .flatMap(options -> {
          List<Problem> problems = new ArrayList<>();
          if (options.number.isEmpty() && options.names.isEmpty()) {
            // need one of listLength or names
            // Note, ideally we would be able to detect the case the the user has explicitly supplied
            // an emtpy map and not give this error. But due to parameter binding the user supplied
            // empty map looks the same as names not being set at all (See: GL#1449)
            problems.add(ParamProblems.oneOfTheseRequired("number", "names"));
          } else if (options.number.isPresent() && !options.names.isEmpty()) {
            // cannot have both
            problems.add(ParamProblems.get().mutuallyExclusive("number", "names"));
          }
          if (options.startNumbering.isPresent() && !options.names.isEmpty()) {
            // cannot have both
            problems.add(ParamProblems.get().mutuallyExclusive("start_numbering", "names"));
          }
          if (options.number.isPresent() && options.number.get() < 0) {
            problems.add(
                GeneralProblems.get().valueOutOfRange("number", options.number.get(), Range.atLeast(0L)));
          }
          return ResultOrProblems.of(options, problems);
        }).getOrThrow(problems -> Problems.foundWith(OPTIONS_ARG_NAME, problems));
  }

}
