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

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import com.google.common.base.CaseFormat;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.ReflectionUtils;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.JavaParameterSet;
import nz.org.riskscape.engine.i18n.RiskscapeMessage;
import nz.org.riskscape.engine.i18n.RiskscapeMessageUtils;
import nz.org.riskscape.engine.pipeline.RealizationInput;
import nz.org.riskscape.engine.pipeline.Realized;
import nz.org.riskscape.engine.pipeline.RealizedPipeline;
import nz.org.riskscape.engine.pipeline.RealizedStep;
import nz.org.riskscape.engine.pipeline.Step;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.problem.ResultOrProblems;

@RequiredArgsConstructor
public abstract class BaseStep<T extends Object> implements Step {

  @Getter
  private final JavaParameterSet<T> parameterSet = JavaParameterSet.fromBindingClass(findParameterClass(getClass()));

  @Getter
  private final Engine engine;
  private final Range<Integer> inputArity;
  @Getter
  private final List<String> inputNames;

  public BaseStep(Engine engine) {
    this.engine = engine;
    this.inputArity = buildArity();
    this.inputNames = buildInputNames();
  }

  @Override
  public String getId() {
    if (getClass().getPackage().getName().equals("nz.org.riskscape.engine.steps")) {
      String truncated = getClass().getSimpleName().replace("Step", "");
      return CaseFormat.UPPER_CAMEL.to(
          CaseFormat.LOWER_UNDERSCORE,
          truncated);
    } else {
      return getClass().getName();
    }
  }
  /**
   * @return A human digestible description for this step.
   */
  @Override
  public RiskscapeMessage getDescription() {
    return RiskscapeMessageUtils.forFieldWithDefault("description", getClass(), "N/A");
  }


  @Override
  public Range<Integer> getInputArity() {
    return inputArity;
  }

  @Override
  public RealizedPipeline realize(RealizationInput input) {
    ResultOrProblems<? extends Realized> realizedOr = buildParametersObject(input)
        .flatMap(paramsObj -> realize(paramsObj));

    RealizedStep newStep = input.newPrototypeStep().realizedBy(this).withResult(realizedOr);

    return input.getRealizedPipeline().add(newStep);
  }

  protected ResultOrProblems<T> buildParametersObject(RealizationInput input) {
    return bindParameters(input)
    .flatMap(paramsObj -> bindInputs(input, paramsObj))
    .map(paramsObj -> {
      bindRealizationInput(input, paramsObj);
      return paramsObj;
    });
  }

  /**
   * Test friendly version of realize that returns just the realized result from the step, rather than a new pipeline
   */
  public ResultOrProblems<? extends Realized> realizeSimple(RealizationInput input) {
    RealizedPipeline newPipeline = realize(input);
    RealizedPipeline prevPipeline = input.getRealizedPipeline();

    SetView<RealizedStep> difference = Sets.difference(
        Set.copyOf(newPipeline.getRealizedSteps()),
        Set.copyOf(prevPipeline.getRealizedSteps())
    );

    assert difference.size() == 1 : "New pipeline added more than one new step - " + difference;

    return difference.iterator().next().getResult();
  }

  private Range<Integer> buildArity() {
    return Range.singleton(ReflectionUtils.getAnnotatedFields(findParameterClass(getClass()), Input.class).size());
  }

  /**
   * Build the input names for this step.
   *
   * Returns an empty list for steps that only require one input as one input does not need to be
   * qualified.
   *
   * Otherwise returns list containing the name of each input in the order that they are defined.
   * @return list of input names, else empty list.
   */
  private List<String> buildInputNames() {
    if (buildArity().upperEndpoint() <= 1) {
      return Collections.emptyList();
    }
    return ReflectionUtils.getAnnotatedFields(findParameterClass(getClass()), Input.class)
        .stream()
        .map(i -> CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, i.getName()))
        .collect(Collectors.toList());
  }

  public abstract ResultOrProblems<? extends Realized> realize(T parameters);

  protected ResultOrProblems<T> bindInputs(RealizationInput input, T parameters) {
    List<RealizedStep> inputs = input.getDependencies();

    List<Field> fields = ReflectionUtils.getAnnotatedFields(parameters.getClass(), Input.class);

    if (!getInputArity().contains(inputs.size())) {
      // TODO might be better to validate this when the pipeline is built?
      return ResultOrProblems.failed(
          GeneralProblems.get().badArity(Input.class, this, getInputArity(), inputs.size()));
    }

    for (int idx = 0; idx < fields.size(); idx++) {
      Field field = fields.get(idx);
      RealizedStep step = inputs.get(idx);
      try {
        field.set(parameters, step);
      } catch (IllegalArgumentException | IllegalAccessException e) {
        throw new RiskscapeException("Unable to set field " + field + " with value " + step, e);
      }
    }

    return ResultOrProblems.of(parameters);
  }

  @SuppressWarnings("unchecked")
  protected Class<T> findParameterClass(Class<?> modelClass) {

    ParameterizedType genericSuperclass;
    try {
      genericSuperclass = (ParameterizedType) modelClass.getGenericSuperclass();
    } catch (ClassCastException e) {
      throw new RuntimeException("BaseModel classes must declare a generic type: " + modelClass, e);
    }

    try {
      return (Class<T>) genericSuperclass.getActualTypeArguments()[0];
    } catch (ArrayIndexOutOfBoundsException ex) {
      throw new RuntimeException("BaseModel classes must declare a generic type: " + modelClass, ex);
    }
  }

  @SuppressWarnings("rawtypes")
  @Override
  public boolean equals(Object obj) {
    if (obj instanceof BaseStep) {
      return ((BaseStep) obj).getId().equals(this.getId());
    } else {
      return false;
    }
  }

  protected ResultOrProblems<T> bindParameters(RealizationInput input) {
    BindingContext bindingContext = input.getExecutionContext().getBindingContext();
    Map<String, List<?>> paramMap = input.getParameters();

    return parameterSet.bindToObject(bindingContext, paramMap)
        .map(bound -> bound.getBoundToObject());
  }

  private void bindRealizationInput(RealizationInput input, T instance) {
    Class<?> ptr = instance.getClass();
    while (ptr != Object.class) {
      Field[] fields = instance.getClass().getFields();
      for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (field.getType().equals(RealizationInput.class)) {
          try {
            field.set(instance, input);
          } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new RiskscapeException("Could not set raw input field " + field, e);
          }
        }
      }
      ptr = ptr.getSuperclass();
    }
  }

  @Override
  public int hashCode() {
    return Objects.hash(this.getId());
  }

  @Override
  public String toString() {
    return getId();
  }

  /**
   * Finds a Parameter for a Step based on name. This is a helper intended
   * for Step sub-classes to report a Problem for a given parameter.
   * @return the Parameter matching the name given, or null if no match was found
   */
  protected Object getParamContext(String name) {
    return parameterSet.get(name);
  }
}
