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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import nz.org.riskscape.config.ConfigSection;
import nz.org.riskscape.config.ConfigString;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * A set of {@link Parameter} objects that are grouped together, typically as a set of required inputs for something
 * that a user adds to their project.  A {@link ParameterSet} is converted in to a {@link BoundParameters} object
 * via the {@link #bind(BindingContext, Map)} method.
 */
@EqualsAndHashCode(of = "declared")
public class ParameterSet {

  /**
   * Somewhat useful constant to represent an empty parameter set
   */
  public static final ParameterSet EMPTY = new ParameterSet(Collections.emptyList());

  /**
   * Accepts a wild-card map and returns one where all values are lists.  If an existing value is already a List, it's
   * left alone, and everything else (including collections) are returned in a list.
   */
  public static Map<String, List<?>> normaliseParameterMap(Map<String, ?> optionsMap) {
    return Maps.transformValues(optionsMap, v -> (v instanceof List) ? (List<?>) v : Arrays.asList(v));
  }

  public static ParameterSet from(Parameter... declaredParameters) {
    return new ParameterSet(Arrays.asList(declaredParameters));
  }

  public static ParameterSet fromList(Collection<Parameter> declaredParameters) {
    return new ParameterSet(declaredParameters);
  }

  public ParameterSet(Collection<Parameter> from) {
    declared = new LinkedHashSet<>(from.size());
    for (Parameter toAdd : from) {
      Parameter existing =
          declared.stream().filter(p -> p.getName().equals(toAdd.getName())).findFirst().orElse(null);
      if (existing != null) {
        throw new IllegalArgumentException(
          "Can not add two parameters with the same name - " + Arrays.asList(toAdd, existing)
        );
      }

      declared.add(toAdd);
    }
  }

  // use a set here, rather than a list, because while we're interested in preserving the order, it shouldn't matter for
  // equality purposes
  @Getter
  private final LinkedHashSet<Parameter> declared;

  /**
   * Attempt to bind the given config map (See {@link ConfigSection#toConfigMap()}) to this set of parameters.  Using
   * this method will improve any error messages by adding source information (where available).
   */
  public BoundParameters bindConfig(BindingContext context, Map<ConfigString, List<ConfigString>> unboundConfig) {
    Map<String, List<?>> unbound = new HashMap<>();

    Set<Entry<ConfigString,List<ConfigString>>> entrySet = unboundConfig.entrySet();
    for (Entry<ConfigString, List<ConfigString>> entry : entrySet) {
      // only the key is stripped of location - the hashmap of unbound values gets very confused if we start mixing
      // key types.  The values should be fine, as they implement CharSequence and tend to go through binding (where
      // they'll get toStringed)
      unbound.put(entry.getKey().toString(), entry.getValue());
    }

    return bind(context, unbound);
  }

  /**
   * Attempt to bind the given raw, unbound, parameter values to a {@link BoundParameters} object.
   * @param context a {@link BindingContext} to use to convert values.
   * @param unbound the values to bind.
   * @return a {@link BoundParameters} object with the results of binding.  Note that a result is returned even if there
   * were binding errors.  A {@link BoundParameters} object has map and flatMap methods for treating the
   * {@link BoundParameters} object like a {@link ResultOrProblems}
   */
  // TODO review how these errors are presented once we get in to using this code - make sure it's consistent and tested
  // so we don't double bag problems
  public BoundParameters bind(BindingContext context, Map<String, List<?>> unbound) {
    List<Problem> collectedErrors = new ArrayList<>();

    Map<String, List<?>> bound = new HashMap<>();
    for (Parameter param : declared) {
      List<?> valueList = unbound.getOrDefault(param.getName(), Collections.emptyList());
      final int numValues = valueList.size();
      List<?> convertedList;

      if (valueList.isEmpty() && param.getDefaultFunction().isPresent()) {
        try {
          // because models are slightly ... kludged in the way that they save parameters values as defaults
          // against the parameter - we will expect perhaps more than otherwise that defaults can be invalid
          convertedList = param.getDefaultValues(context);
        } catch (ParameterBindingException e) {
          collectedErrors.add(e.getProblem());
          convertedList = Collections.emptyList();
        }
      } else {
        List<Object> boundParameterList = Lists.newArrayListWithExpectedSize(numValues);

        // arity errors...
        if (numValues < param.getMinRequired() || numValues > param.getMaxRequired()) {
          if (numValues == 0) {
            // Nothing was specified. Simplify the error message to: Parameter 'blah' is required
            collectedErrors.add(GeneralProblems.get().required(param));
          } else {
            collectedErrors.add(ParamProblems.get().wrongNumberGiven(param.getName(), param.getArity(), numValues));
          }
        }

        for (Object value : valueList) {
          if (param.getType().isInstance(value)) {
            boundParameterList.add(value);
          } else {
            Object converted;
            ResultOrProblems<?> bindResult = context.bind(value, param);

            if (bindResult.hasErrors()) {
              collectedErrors.addAll(bindResult.getProblems());
            } else if (bindResult.isPresent()) {
              // binding may result in some warnings to deal with (or pass along)
              converted = bindResult
                  .drainWarnings(p -> collectedErrors.add(p))
                  .get();
              if (converted != null) {
                boundParameterList.add(converted);
              }
            } else {
              continue;
            }

          }
        }

        convertedList = boundParameterList;
      }

      bound.put(param.getName(), convertedList);
    }

    return new BoundParameters(this, context, bound, unbound, collectedErrors);
  }

  /**
   * @return if this parameter set contains a parameter with the given name
   */
  public boolean contains(String parameterName) {
    for (Parameter parameter : declared) {
      if (parameter.getName().equals(parameterName)) {
        return true;
      }
    }
    return false;
  }

  /**
   * @return the parameter in this set with the given name, or throw an {@link IllegalArgumentException} if no parameter
   * with this name exists in the parameter set.
   */
  public Parameter get(String parameterName) {
    for (Parameter parameter : declared) {
      if (parameter.getName().equals(parameterName)) {
        return parameter;
      }
    }

    throw new IllegalArgumentException("No such parameter - " + parameterName);
  }

  @Override
  public String toString() {
    return String.format(
        "ParameterSet(%s)",
        declared.stream().map(Parameter::getName).collect(Collectors.joining(", ", "[", "]"))
    );
  }

  /**
   * The number of parameters in this set
   */
  public int size() {
    return declared.size();
  }

  /**
   * @return the declared parameters within, in the order they were declared
   */
  public List<Parameter> toList() {
    return new ArrayList<>(declared);
  }
}
