/*
 * 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.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;

import lombok.Getter;
import lombok.NonNull;
import nz.org.riskscape.dsl.Token;
import nz.org.riskscape.engine.pipeline.Step;
import nz.org.riskscape.engine.util.Pair;
import nz.org.riskscape.rl.TokenTypes;

/**
 * Defines a step. May optionally include parameter defaults and name for the step.
 */
public class StepDefinition extends StepDeclaration {

  public static class Argument extends GenericArgument<AST> {

    public Argument(AST arg, Optional<Token> nameToken) {
      super(arg, nameToken);
      // this is enough to assert that the arg is either an expression or a step chain input
      switchArgument(x -> {}, x -> {});
    }

    public void switchArgument(Consumer<Expression> ifExpression, Consumer<InputChain> ifInput) {
      if (getValue() instanceof Expression expr) {
        ifExpression.accept(expr);
      } else if (getValue() instanceof InputChain input) {
        ifInput.accept(input);
      } else {
        throw new AssertionError("Unexpected type " + getValue());
      }
    }

    /**
     * @return true if this argument's value is an input chain a.k.a pipeline argument.
     */
    public boolean isInputChain() {
      return getValue().isA(InputChain.class).isPresent();
    }
  }

  @Getter @NonNull
  private final List<Argument> arguments;

  @Getter @NonNull
  private final Optional<Token> nameToken;

  @Getter @NonNull
  private final Optional<Pair<Token, Token>> boundary;

  public StepDefinition(String id) {
    this(
        TokenTypes.identToken(id),
        List.of(),
        Optional.empty(),
        Optional.empty(),
        Optional.empty()
    );
  }

  public StepDefinition(
      Token identifier,
      List<Argument> arguments,
      Optional<Token> nameToken,
      Optional<Token> namedInputToken,
      Optional<Pair<Token, Token>> boundary
  ) {
    super(identifier, namedInputToken);
    this.arguments = List.copyOf(arguments);
    this.nameToken = nameToken;
    this.boundary = boundary;
  }

  /**
   * @return an identifier used to link the step definition to a {@link Step} that the engine provides for pipeline
   * processing
   */
  public String getStepId() {
    return identToken.getValue();
  }

  /**
   * @return a name that the user assigned to this step definition, or empty if the step is anonymous
   */
  public Optional<String> getName() {
    return nameToken.map(Token::getValue);
  }

  public List<Argument> getStepParameters() {
    return getArguments();
  }

  /**
   * @return the ast token for the identifier used to link the step definition to a {@link Step} that the engine
   * provides for pipeline processing
   */
  public Token getStepIdToken() {
    return getIdentToken();
  }

  @Override
  protected void appendSource(StringBuilder appendTo) {
    appendTo.append(getIdentToken().rawValue());
    join(appendTo, arguments, (sb, a) -> a.appendSource(sb), ", ", "(", ")");

    getNamedInput().ifPresent(input -> appendTo.append(".").append(TokenTypes.quoteIdent(input)));
    getName().ifPresent(name -> appendTo.append(" as ").append(TokenTypes.quoteIdent(name)));
  }

  @Override
  protected void appendString(StringBuilder appendTo) {
    if (!nameToken.isPresent()) {
      // we use a ? to make it clear that it has no alias
      appendTo.append("?");
    }

    appendTo.append(getName().orElse(getIdent())).append("(");
    if (!getArguments().isEmpty()) {
      appendTo.append("…");
    }
    appendTo.append(")");

    if (namedInputToken.isPresent()) {
      appendTo.append(".").append(namedInputToken.get().getValue());
    }
  }

  @Override
  public boolean equals(Object o) {
    if (o instanceof StepDefinition rhs) {
      return super.equals(o) && rhs.arguments.equals(this.arguments) && rhs.nameToken.equals(this.nameToken);
    }

    return false;
  }

  @Override
  public int hashCode() {
    return Objects.hash(arguments, nameToken, identToken, namedInputToken);
  }

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

  /**
   * Collects all the {@link StepReference}s from any arguments via {@link InputChain#getStepReferences()}
   */
  public List<StepReference> getInputChainStepReferences() {
    return getArguments().stream()
        .flatMap(arg -> arg.getValue()
            .isA(InputChain.class)
            .map(InputChain::getStepReferences)
            .orElse(List.of()).stream()
        )
        .toList();
  }
}
