/*
 * 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.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import lombok.Data;
import lombok.Getter;
import nz.org.riskscape.engine.pipeline.RealizationInput;
import nz.org.riskscape.engine.pipeline.RealizedPipeline;
import nz.org.riskscape.engine.pipeline.RealizedStep;
import nz.org.riskscape.engine.projection.Projector;
import nz.org.riskscape.engine.relation.EmptyRelation;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.rl.ast.PipelineDeclaration;

/**
 * Helper class for realizing a child pipeline that gets 'smooshed' back in to a parent as part of realizing a step
 */
@Data
public class ChildPipelineBuilder {

  private enum State {
    PREP, REALIZED_CHILD, COMBINED
  }

  // building state
  private State state = State.PREP;

  private final RealizationInput input;

  // parent pipeline - this came in to realization
  private final RealizedPipeline parent;

  // the ast of a pipeline we will realize and insert back in to the parent somehow
  private final PipelineDeclaration childAst;

  // maps from original to stub step
  private final Map<RealizedStep, RealizedStep> inputSteps = new HashMap<RealizedStep, RealizedStep>();

  // Maps from steps that were in the child pipeline to the ones that we end up putting in the pipeline we return.
  // This lets us rebuild the dependencies for each step as it gets added to the pipeline we return
  Map<RealizedStep, RealizedStep> rebuilt = new HashMap<>();

  // the current state of realizing the child pipeline
  private RealizedPipeline building;

  private RealizedPipeline combined;

  // the steps we spit out get renamed to avoid collisions with the parent pipeline
  // TODO we might want to spit out warnings if users put dots in their step names?
  @Getter
  private String childStepPrefix;

  /**
   * Constructs a new ChildPipelineBuilder for realizing and integrating a child pipeline into a parent pipeline.
   *
   * @param input the realization input containing the parent pipeline and context
   * @param childAst the AST declaration of the child pipeline to be realized
   */
  public ChildPipelineBuilder(RealizationInput input, PipelineDeclaration childAst) {
    this.input = input;
    this.parent = input.getRealizedPipeline();
    this.childAst = childAst;
    this.building = RealizedPipeline.empty(parent.getContext(), childAst);
    this.childStepPrefix = input.newPrototypeStep().getName() + ".";
  }

  /**
   * Adds an input step from the parent pipeline into the child pipeline by creating a stub step.
   * The stub step mirrors the parent step's output schema but won't be executed during child pipeline realization.
   *
   * @param stepFromParent the realized step from the parent pipeline to use as input
   * @param stubName the name to give the stub step in the child pipeline - this is how the child pipeline will refer
   * to it
   */
  public void addInputStep(RealizedStep stepFromParent, String stubName) {
    assertState(State.PREP);

    if (!parent.getRealizedSteps().contains(stepFromParent)) {
      throw new IllegalArgumentException("Parent does not contain this step");
    }

    // Created a stub-step to use to realize the child pipeline (it won't be executed)
    RealizedStep stubInputStep = RealizedStep.named(stubName)
        .withResult(new EmptyRelation(stepFromParent.getProduces()));

    inputSteps.put(stepFromParent, stubInputStep);

    // Seed realization with this `in` step
    building = building.add(stubInputStep);
  }

  private void assertState(State shouldBe) {
    if (this.state != shouldBe) {
      throw new IllegalStateException("Was %s, should be %s".formatted(this.state, shouldBe));
    }
  }

  /**
   * Retrieves the stub step that was created in the child pipeline for a given parent input step.
   *
   * @param originalInputStep the original step from the parent pipeline
   * @return the corresponding stub step in the child pipeline, or null if not found
   */
  public RealizedStep getChildInputStep(RealizedStep originalInputStep) {
    // TODO throw if missing?
    return inputSteps.get(originalInputStep);
  }


  /**
   * Realizes the child pipeline using the configured AST and input steps.
   * This method must be called after all input steps have been added via {@link #addInputStep}.
   *
   * @return the realized child pipeline, which may contain failures if realization encountered problems
   */
  public RealizedPipeline realizeChild() {
    assertState(State.PREP);
    building =
        parent.getContext().getPipelineRealizer().realize(building, childAst);

    state = State.REALIZED_CHILD;

    return building;
  }

  /**
   * Combines the realized child pipeline back into the parent pipeline.
   *
   * If the child pipeline failed to realize, a failure step is added to the resulting pipeline to represent those
   * errors
   *
   * All child steps are prefixed with the parent step name to ensure unique naming.
   *
   * @return the combined pipeline containing both parent and child steps
   */
  public RealizedPipeline combine() {
    assertState(State.REALIZED_CHILD);

    combined = parent;

    // if the child failed to realize, we start by adding a step in to the pipeline with the input name that contains
    // all of the child pipeline's errors
    RealizedStep failed;
    if (isChildFailed()) {
      failed = input.newPrototypeStep().withProblems(SubpipelineStep.PROBLEMS.childFailed(
          building.getAst().getMetadata().getLocation(),
          building.getFailures().toArray(Problem[]::new))
      );
      combined = combined.add(failed);
    } else {
      failed = null;
    }

    LinkedList<RealizedStep> visitStack = new LinkedList<>(building.getRealizedSteps());


    for (Map.Entry<RealizedStep, RealizedStep> originalToRenamedInputStep : inputSteps.entrySet()) {
      // this seems a little backwards at first, but it makes sense:  The renamed input is the one we put in the child
      // pipeline, but ultimately we want the steps we add to the resulting pipeline to refer to the original input step
      rebuilt.put(originalToRenamedInputStep.getValue(), originalToRenamedInputStep.getKey());
      // we don't need to visit this one, we did it 'manually' above
      visitStack.remove(originalToRenamedInputStep.getValue());
    }

    // for assertions
    int cycleDetect = 0;

    visitLoop:
    while (!visitStack.isEmpty()) {
      RealizedStep childStep = visitStack.removeFirst();

      // rename it
      RealizedStep renamed = childStep.withName(childStepPrefix + childStep.getName());

      // rebuild dependencies
      List<RealizedStep> rebuiltDependencies = new ArrayList<>(childStep.getDependencies().size());
      for (RealizedStep originalDependency : childStep.getDependencies()) {
        RealizedStep rebuiltDependency = rebuilt.get(originalDependency);

        // TODO see if this is necessary - I suspect it won't ever happen because the steps should already be
        // in traversal order (but then we might need to assert that somewhere else in a test)
        if (rebuiltDependency == null) {
          visitStack.add(childStep);

          if (cycleDetect == visitStack.size()) {
            throw new AssertionError("cycle detected " + visitStack);
          }

          cycleDetect++;
          continue visitLoop;
        }

        rebuiltDependencies.add(rebuiltDependency);
      }

      if (failed != null) {
        // if this step depends on our magic failed step, it'll prevent the error coming out twice, but will preserve
        // the entire pipeline for --print (maybe this is a bad reason, let's see how this pans out)
        rebuiltDependencies.add(failed);
      }

      // reset assertion counter
      cycleDetect = 0;

      // update the pipeline
      RealizedStep rebuiltStep = renamed.withDependencies(rebuiltDependencies);
      combined = combined.add(rebuiltStep);
      rebuilt.put(childStep, rebuiltStep);
    }

    state = State.COMBINED;

    return combined;
  }

  /**
   * Adds a step to the combined pipeline named after the input's prototype step (so will have the expected name) for
   * any dependencies that are chained to this step.
   */
  public RealizedPipeline addWellKnownOutput(RealizedStep outputStep, List<Problem> warnings) {
    assertState(State.COMBINED);

    // there's no need to add the noop step (below) if failed, the combine method will have already added one
    if (isChildFailed()) {
      return combined;
    }

    // tack on a step with a well-known name if wellKnownOutput is given

    Projector noop = Projector.identity(outputStep.getProduces());

    RealizedStep rebuiltOutput = rebuilt.get(outputStep);
    if (rebuiltOutput == null) {
      throw new IllegalArgumentException("output not rebuilt " + outputStep);
    }

    // this will fail on a second call
    combined = combined.add(input.newPrototypeStep()
                .withResult(noop)
                .withProblems(warnings)
                .withDependencies(rebuiltOutput));

    return combined;
  }

  public RealizedPipeline getCombined() {
    assertState(State.COMBINED);

    return combined;
  }
  /**
   * @return true if the child pipeline has failures.
   */
  public boolean isChildFailed() {
    return building.hasFailures();
  }

  /**
   * @return the step in combined pipeline that was rebuilt for the child step, i.e. it is the child step, but renamed
   * and in the combined pipeline
   */
  public RealizedStep getRebuiltStep(RealizedStep childStep) {
    assertState(State.COMBINED);

    return rebuilt.get(childStep);
  }
}
