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

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * A set of parameter values that have been bound from a particular {@link ParameterSet}.  While all values should be
 * valid, it's possible that the values are incomplete or there are missing or extra values - the
 * {@link ParameterSet#bind(BindingContext, Map)} returns a {@link ResultOrProblems} object that will indicate whether
 * the parameters are valid or not
 */
@RequiredArgsConstructor
@EqualsAndHashCode(of = {"boundTo", "unbound"}) // other fields are computable from these, or are non state
public class BoundParameters  {

  /**
   * The {@link ParameterSet} that the unbound values were bound to
   */
  @Getter
  private final ParameterSet boundTo;

  /**
   * The {@link BindingContext} under which the parameters were bound
   */
  @Getter
  private final BindingContext context;

  /**
   * The bound, valid, values that correspond to the {@link #boundTo} parameter set.
   */
  @Getter
  private final Map<String, List<?>> valueMap;

  /**
   * The original, given values that were bound.  May not be present, depending on how the parameters were
   * created.  May also contain values that were not bound, because they were invalid or surplus.
   */
  @Getter
  private final Map<String, List<?>> unbound;

  /**
   * @return any {@link Problem}s encountered during binding - the presence of error-level problems indicates a failed
   * result
   */
  @Getter
  private final List<Problem> validationProblems;

  /**
   * @return the value bound to the parameter with the given name, or null if not set
   * @throws IllegalArgumentException if the parameter has a max arity of greater than one
   */
  public Object getValue(String parameterName) {
    Parameter param = boundTo.get(parameterName);

    if (param.isMany()) {
      throw new IllegalArgumentException("parameter " + parameterName
          + " can have many values - use getValues instead");
    }

    List<?> values = valueMap.getOrDefault(parameterName, Collections.emptyList());
    return values.isEmpty() ? null : values.get(0);
  }

  /**
   * @return the values bound to the parameter with the given name
   */
  public List<?> getValues(String parameterName) {
    // NB causes an exception if parameterName does not exist
    boundTo.get(parameterName);

    return valueMap.getOrDefault(parameterName, Collections.emptyList());
  }

  /**
   * @return a map of parameters that were given but not used during binding (because they didn't correspond to a
   * parameter in the parameter set).  Note that extra parameters do not create a warning or an error.
   */
  public Map<String, List<?>> getExtraneous() {
    Map<String, List<?>> clone = new HashMap<>(getUnbound());
    // drop any values that are keyed after parameters in the parameter set
    clone.keySet().removeIf(key -> boundTo.contains(key));
    return clone;
  }

  public boolean isValid() {
    return !Problem.hasErrors(validationProblems);
  }

  /**
   * {@link ResultOrProblems} like method for mapping the parameters in to another object, but only if the parameters
   * are valid
   */
  public <T> ResultOrProblems<T> map(Function<BoundParameters, T> function) {
    if (isValid()) {
      return ResultOrProblems.of(function.apply(this));
    } else {
      return ResultOrProblems.failed(validationProblems);
    }
  }

  /**
   * {@link ResultOrProblems} like method for mapping the parameters in to another ResultOrProblems object, but only if
   * the parameters are valid
   */
  public <T> ResultOrProblems<T> flatMap(Function<BoundParameters, ResultOrProblems<T>> function) {
    if (isValid()) {
      return function.apply(this);
    } else {
      return ResultOrProblems.failed(validationProblems);
    }
  }

  @Override
  public String toString() {
    return String.format("BoundParameters(%s)", valueMap);
  }

  /**
   * Merge these bound parameters with other such that any parameter that is set in other will replace
   * one that this set in these bound parameters.
   *
   * @param other bound parameters that will set/replace values set in these bound parameters
   * @return new bound parameters with updated parameter values
   * @throws IllegalArgumentException if this and other have a different context or boundTo
   */
  public BoundParameters merge(BoundParameters other) {
    if (other.boundTo != boundTo) {
      // fail fast on programmer errors
      throw new IllegalArgumentException("Cannot merge if boundTo not the same");
    }
    if (other.context != context) {
      // fail fast on programmer errors
      throw new IllegalArgumentException("Cannot merge if context not the same");
    }

    Map<String, List<?>> newValueMap = new HashMap<>();
    Map<String, List<?>> newUnbound = new HashMap<>();

    // start off with values from these bound parameters
    newValueMap.putAll(valueMap);
    newUnbound.putAll(unbound);

    // now replace values from other, but we do this by iterating over the unbound values to ensure we
    // aren't just over writing values with default bound values from other.
    for (Entry<String, List<?>> entry: other.getUnbound().entrySet()) {
      newUnbound.put(entry.getKey(), entry.getValue());
      newValueMap.put(entry.getKey(), other.getValueMap().get(entry.getKey()));
    }

    // Now we validate what we've got against the parameter set requirements
    List<Problem> collectedErrors = new ArrayList<>();
    for (Parameter param : boundTo.getDeclared()) {
      int numValues = newValueMap.getOrDefault(param.getName(), Collections.emptyList()).size();
      if (numValues < param.getMinRequired() || numValues > param.getMaxRequired()) {
        if (numValues == 0) {
          if (newUnbound.containsKey(param.getName())) {
            // if there are no bound values but there is an unbound value then this would be due to a binding
            // error. Rather than try to find the previous bind problem we just rebuild it.
            BindingContext ctx = other.getUnbound().containsKey(param.getName()) ? other.context : context;
            for (Object value : newUnbound.get(param.getName())) {
              ResultOrProblems<?> bindResult = ctx.bind(value, param);
              if (bindResult.hasProblems()) {
                collectedErrors.addAll(bindResult.getProblems());
              }
            }
          } else {
            // Nothing was specified. Simplify the error message to: Parameter 'blah' is required
            collectedErrors.add(GeneralProblems.required(param.getName(), Parameter.class));
          }
        } else {
          collectedErrors.add(ParamProblems.get().wrongNumberGiven(param.getName(), param.getArity(), numValues));
        }
      }
    }

    return new BoundParameters(boundTo, context, newValueMap, newUnbound, collectedErrors);
  }

  /**
   * Lets the calling code include more bespoke validation problems besides the
   * straight-forward binding errors.
   *
   * @return a new BoundParameters with the additional problems included.
   */
  public BoundParameters withMoreProblems(List<Problem> moreProblems) {
    List<Problem> combinedProblems = new ArrayList<>();
    combinedProblems.addAll(moreProblems);
    combinedProblems.addAll(validationProblems);
    return new BoundParameters(boundTo, context, valueMap, unbound, combinedProblems);
  }
}
