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

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

import com.google.common.collect.ImmutableList;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import nz.org.riskscape.dsl.Token;
import nz.org.riskscape.engine.OsUtils;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.rl.TokenTypes;
import nz.org.riskscape.util.ListUtils;

/**
 * AST for a list of {@link StepDeclaration}s that are chained together.
 *
 * Steps that are chained together should have their output connected to the input of the following
 * step in the chain.
 *
 * Steps that are declared (but not chained to another) will be on the only step in the step chain.
 * In this case it would be expected that the the same step be present in another step chain to be
 * chained together with other steps.
 */
@EqualsAndHashCode(callSuper = false)
public class StepChain extends BaseAST implements PipelineAST {

  /**
   * A handy constant for building AST in code (instead of parsing it)
   */
  public static final Token CHAIN_TOKEN = Token.token(TokenTypes.CHAIN, "->");

  /**
   * A special "empty" instance of a {@link StepChain} that can be used in place of null in various situations.  Note
   * that an empty {@link StepChain} is not a valid part of a pipeline.
   *
   */
  public static final StepChain EMPTY = new StepChain(Collections.emptyList(), Collections.emptyList());

  @Getter
  private final List<StepDeclaration> steps;
  private final List<Token> links;

  public StepChain(List<StepDeclaration> steps) {
    this(steps, Collections.nCopies(steps.size() - 1, CHAIN_TOKEN));
  }

  public StepChain(List<StepDeclaration> steps, List<Token> links) {
    this.steps = ImmutableList.copyOf(steps);
    this.links = ImmutableList.copyOf(links);
}

  @Override
  public Optional<Pair<Token, Token>> getBoundary() {
    if (steps.isEmpty()) {
      return Optional.empty();
    } else {
      StepDeclaration first = steps.get(0);
      StepDeclaration last = steps.get(steps.size() - 1);

      // this folds first and last's boundaries, which might be absent, in to our own boundary
      return first
        .getBoundary()
        .flatMap(firstPair
            -> last.getBoundary().map(lastPair -> Pair.of(firstPair.getLeft(), lastPair.getRight()))
        );
    }
  }

  /**
   * Returns a new StepChain with all the steps from the given chain appended to this chain
   */
  public StepChain append(StepChain appendStepsFrom) {
    return new StepChain(ListUtils.concat(this.steps, appendStepsFrom.steps));
  }

  /**
   * Returns a new StepChain with the given step appended
   */
  public StepChain append(StepDeclaration stepDeclaration) {
    return new StepChain(ListUtils.append(this.steps, stepDeclaration));
  }

  @Override
  protected void appendSource(StringBuilder appendTo) {
    boolean first = true;
    for (StepDeclaration decl : steps) {

      if (!first) {
        appendTo.append(OsUtils.LINE_SEPARATOR);
        appendTo.append(" -> ");
      }

      decl.appendSource(appendTo);

      first = false;
    }
  }

  @Override
  protected void appendString(StringBuilder appendTo) {
    boolean first = true;
    for (StepDeclaration stepDeclaration : steps) {
      if (!first) {
        appendTo.append(" -> ");
      }
      stepDeclaration.appendString(appendTo);
      first = false;
    }
  }

  /**
   * Nicer form of StepChain#getSteps().get(0)
   * @throws IndexOutOfBoundsException if this chain is empty
   */
  public StepDeclaration getFirst() {
    return steps.get(0);
  }

  /**
   * Nicer form of `StepChain.getSteps().get(StepChain.getSteps().size() - 1);`
   * @throws IndexOutOfBoundsException if this chain is empty
   */
  public StepDeclaration getLast() {
    return steps.get(steps.size() - 1);
  }

  public StepLink getLink(int index) {
    if (index >= getLinkCount()) {
      throw new NoSuchElementException("this chain has only " + getLinkCount() + " links");
    }

    return new StepLink(steps.get(index), links.get(index), steps.get(index + 1));
  }

  public int getLinkCount() {
    return size() - 1;
  }

  /**
   * @return the number of steps in this chain
   */
  public int size() {
    return steps.size();
  }

  /**
   * Replace `step` with `replacement, returning a new {@link StepChain} that includes the change.
   */
  public StepChain replace(StepDeclaration step, StepDeclaration replacement) {
    if (!steps.contains(step)) {
      throw new IllegalArgumentException("This chain does not contain " + step);
    }

    List<StepDeclaration> newSteps = new ArrayList<>(steps);
    newSteps.set(newSteps.indexOf(step), replacement);

    return new StepChain(List.copyOf(newSteps), links);
  }

  @Override
  public <T, R> R accept(PipelineVisitor<T, R> visitor, T data) {
    return visitor.visit(this, data);
  }
}
