/*
 * 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.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Stores a property that represents a key-value pair, e.g. `min: 0`. Most
 * ParameterProperty are enum-based, however, a KeyValueProperty needs to be an
 * object, because it takes a configurable value. The idea is we can create the
 * property with a placeholder value (e.g. `min: -Infinity`), then swap out the
 * placeholder later with the user's actual config (e.g. `min: 0`)
 */
@RequiredArgsConstructor
@EqualsAndHashCode(of = "keyword")
public class KeyValueProperty<T> implements ParameterProperty {

  /**
   * Returns a numeric KeyValueProperty with a placeholder value. Note that we work
   * with Double for Numeric values, mostly because we don't support binding to Numbers.
   */
  public static KeyValueProperty<Double> numeric(String name, double placeholder) {
      return new KeyValueProperty<>(name, placeholder)
        .withImplied(TypedProperty.NUMERIC)
        .withCompatibility(prop -> TypedProperty.NUMERIC.isCompatible(prop));
    }

  @Getter
  private final String keyword;

  @Getter
  private final T value;

  @Getter
  private final List<ParameterProperty> implied;

  @Getter
  private final Function<ParameterProperty, Boolean> checkCompatible;

  @Getter
  private final BiFunction<KeyValueProperty<T>, Object, List<Problem>> checkValid;

  // NB: here we're just binding the value part of the key-value pair, e.g. '100' in 'max: 100'.
  // (the user-specified value for the parameter itself is still bound using the Parameter class)
  private final BiFunction<BindingContext, Object, ResultOrProblems<T>> valueBinder;

  /**
   * Construct a new KeyValueProperty with no default value.
   * @param bindType the expected type of values - will be used to bind any value that is given to this
   * property
   */
  public KeyValueProperty(String key, Class<T> bindType) {
    this(key, null, Collections.emptyList(), p -> true, (c, v) -> Collections.emptyList(),
        (c, v) -> c.bind(v, bindType));
  }

  public KeyValueProperty(String key, @NonNull T value) {
    this(key, value, Collections.emptyList(), p -> true, (c, v) -> Collections.emptyList(),
        (c, v) -> (ResultOrProblems<T>) c.bind(v, value.getClass()));
  }

  @Override
  public boolean isCompatible(ParameterProperty other) {
    return checkCompatible.apply(other);
  }

  @Override
  public Optional<?> getValueOr() {
    return Optional.ofNullable(value);
  }

  @Override
  public List<Problem> validate(BindingContext context, Object bound) {
    // currently the validation is simple, so we don't use the context, but we might want to in future
    return checkValid.apply(this, bound);
  }

  @Override
  public ParameterProperty withValue(Object newValue) {
    return new KeyValueProperty<>(keyword, (T) newValue, implied, checkCompatible, checkValid, valueBinder);
  }

  @Override
  public ResultOrProblems<ParameterProperty> withValue(BindingContext context, Object newValue) {
    return valueBinder.apply(context, newValue)
        .map(bound -> this.withValue(bound))
        .composeProblems(Problems.foundWith(this));
  }

  public KeyValueProperty<T> withImplied(ParameterProperty... newImplied) {
    return new KeyValueProperty<>(keyword, value, Arrays.asList(newImplied), checkCompatible, checkValid, valueBinder);
  }

  public KeyValueProperty<T> withCompatibility(Function<ParameterProperty, Boolean> isCompatible) {
    return new KeyValueProperty<>(keyword, value, implied, isCompatible, checkValid, valueBinder);
  }

  public KeyValueProperty<T> withValidation(BiFunction<KeyValueProperty<T>, Object, List<Problem>> newValidation) {
    return new KeyValueProperty<>(keyword, value, implied, checkCompatible, newValidation, valueBinder);
  }

  public KeyValueProperty<T> withValueBinding(BiFunction<BindingContext, Object, ResultOrProblems<T>> newBindValue) {
    return new KeyValueProperty<>(keyword, value, implied, checkCompatible, checkValid, newBindValue);
  }

  @Override
  public String toString() {
    return keyword.toUpperCase() + ": " + Objects.toString(value);
  }

  @Override
  public boolean hasKeyValuePair() {
    // key value properties always expect a value
    return true;
  }
}

