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

import java.util.ArrayList;
import java.util.List;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import nz.org.riskscape.engine.pipeline.Realized;
import nz.org.riskscape.engine.pipeline.RealizedStep;

/**
 * Groups together pipeline steps that can be processed in the same task.
 * Many steps are only ever processed individually (i.e. Collectors, Joins,
 * Relations, Sinks). But Projector and Restrictor steps can be grouped
 * together and processed as a single task. The SchedulerBasedExecutor uses
 * LinkedSteps in order to decompose a pipeline into tasks.
 */
@Data
@ToString(exclude = {"descendants", "predecessors"})
@EqualsAndHashCode(exclude = {"descendants", "predecessors"})
public class LinkedSteps {

  /**
   * The pipeline steps that get processed together as a single TaskSpec
   */
  private final List<RealizedStep> grouped;

  private final List<LinkedSteps> predecessors;
  private final List<LinkedSteps> descendants = new ArrayList<>();

  public LinkedSteps(List<LinkedSteps> predecessors, List<RealizedStep> steps) {
    this.predecessors = predecessors;
    this.grouped = steps;

    for (LinkedSteps predecessor : predecessors) {
      predecessor.descendants.add(this);
    }
  }

  public RealizedStep getLastStep() {
    return grouped.get(grouped.size() - 1);
  }

  public boolean containsOnly(Class<? extends Realized> lookFor) {
    return grouped.stream().allMatch(step -> step.getStepType().equals(lookFor));
  }

  public LinkedSteps getOrderedPredecessor(int index) {
    // we can't guarantee what order our predecessors are in, so use our first
    // realized step to get to the appropriate predecessor
    RealizedStep previousStep = getFirstStep().getDependencies().get(index);

    for (LinkedSteps linkedSteps : predecessors) {
      if (linkedSteps.grouped.contains(previousStep)) {
        return linkedSteps;
      }
    }

    // lookup failure probably indicates an internal inconsistency
    throw new RuntimeException("Could not find " + previousStep + " amongst " + predecessors);
  }

  public RealizedStep getFirstStep() {
    return grouped.get(0);
  }

  /**
   * @return true if these steps fan out into multiple downstream steps
   */
  public boolean hasFanOut() {
    return descendants.size() > 1;
  }
}
