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

import java.net.URI;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import com.google.common.collect.Maps;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * A named collection of somewhat ordered key/value pairs appearing as part of {@link Config}
 */
@RequiredArgsConstructor
public abstract class ConfigSection {

  /**
   * Defeat Java's generics checking - it's safe to treat a list of strings as a list of wild things, but to do
   * this with java's generics requires us to declare the receiver as `? extends List<?>` which complicates the receiver
   * *a lot*.  I can't think of any cases where the use of this would cause a class cast exception, and it simplifies
   * the use of APIs that accept a list of anything vs a list of strings (like binding)
   */
  @SuppressWarnings("unchecked")
  public static Map<String, List<?>> wild(Map<String, List<String>> multiMap) {
    @SuppressWarnings("rawtypes")
    Map ungeneric = multiMap;
    return ungeneric;
  }

  /**
   * @return the location that was the source of this configuration section
   */
  @Getter
  private final URI location;

  @Getter
  /**
   * @return a name that uniquely identifies this {@link Config} section among all others from the same {@link Config}
   * object.  This might have a prefix added for the type of thing this config identifies, e.g. "type flood_hazard"
   */
  private final String name;

  /**
   * @return true if this section contains at least one value for the given key
   */
  public boolean hasKey(String key) {
    return getAll(key).size() > 0;
  }

  /**
   * @return a value for the given key, or an error if it was missing or if there multiple values defined
   */
  public ResultOrProblems<String> getOneRequired(String key) {
    // refer to the INI section keys as 'parameters' in the error message
    Parameter parameter = Parameter.required(key, Object.class);
    return getOne(key).orElse(ResultOrProblems.failed(GeneralProblems.get().required(parameter)));
  }

  /**
   * @return a value for the given key, or an error if multiple values were defined.  Also wraps it in an optional (i
   * know...) if the value is not defined.
   */
  public Optional<ResultOrProblems<String>> getOne(String key) {
    List<String> values = getAll(key);

    if (values == null || values.size() == 0) {
      return Optional.empty();
    } else {
      return Optional.of(ResultOrProblems.of(
          values.get(values.size() - 1), values.size() == 1
              ?
              Collections.emptyList()
              :
                // use the declared name, not the assigned one, so the user can trace it back.  NB: this used to report
                // the whole name of the section, but an API change means we can't easily get at this from the base
                // class.  Maybe come back later and see if we can improve this?
              Collections.singletonList(ConfigProblems.get().duplicateKey(getLocation(), getName(), key))
      ));
    }
  }

  /**
   * @return a list of all values defined for the given key, or an empty list if none are defined
   */
  public List<String> getAll(String key) {
    return toMultiMap().getOrDefault(key, List.of());
  }

  /**
   * @return a map view of all the key value pairs, where repeated keys are ignored (last one wins)
   */
  public Map<String, String> toMap() {
    // NB need to come back and see if this breaks any unit tests etc - I *think* we have had defined behaviour for
    // this, e.g. first one wins, but I can't be certain...
    return Maps.transformValues(toMultiMap(), values -> {
      if (values == null) {
        return null;
      } else if (values.size() == 0) {
        return null;
      } else {
        // as per getOne - we return the last defined as the winner
        return values.get(values.size() - 1);
      }
    });
  }

  /**
   * Builds a multi-map view of all the key values, where repeated keys return a list of all the values for the key.
   * This is a version of toConfigMap where the {@link ConfigString}s are converted to strings for cases where the
   * location metadata isn't wanted (or ConfigString isn't yet handled).
   */
  public Map<String, List<String>> toMultiMap() {
    Map<ConfigString, List<ConfigString>> configMap = toConfigMap();
    Map<String, List<String>> multiMap = new LinkedHashMap<String, List<String>>(configMap.size());

    for (Map.Entry<ConfigString, List<ConfigString>> entry : configMap.entrySet()) {
      multiMap.put(entry.getKey().toString(), entry.getValue().stream().map(ConfigString::toString).toList());
    }

    return multiMap;
  }

  /**
   * @return a multi-map view of all the key values, where repeated keys return a list of all the values for the key
   */
  public abstract Map<ConfigString, List<ConfigString>> toConfigMap();

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof ConfigSection rhs) {
      return rhs.name.equals(this.name) && rhs.toMultiMap().equals(this.toMultiMap());
    }

    return false;
  }

  @Override
  public int hashCode() {
    return Objects.hash(this.name, this.toMultiMap());
  }
}
