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

import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;

import nz.org.riskscape.dsl.LexerException;
import nz.org.riskscape.dsl.ParseException;
import nz.org.riskscape.rl.ast.PipelineDeclaration;
import nz.org.riskscape.rl.ast.StepChain;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;
import nz.org.riskscape.rl.ExpressionParser;
import nz.org.riskscape.wizard.Answer;
import nz.org.riskscape.wizard.Question;
import nz.org.riskscape.wizard.QuestionSet;
import nz.org.riskscape.wizard.bld.change.AppendStepChange;
import nz.org.riskscape.wizard.bld.change.BadPipelineChangeException;
import nz.org.riskscape.wizard.bld.change.MultipleChanges;
import nz.org.riskscape.wizard.bld.change.NoChange;
import nz.org.riskscape.wizard.bld.change.SimpleChange;
import nz.org.riskscape.wizard.bld.change.StartChainChange;
import nz.org.riskscape.wizard.bld.dsl.IncompletePipelineChange;

/**
 * An operation that can return a possibly new {@link IncrementalBuildState} in response to an {@link Answer}.  The
 * returned build state reflects the change.
 */
public interface PipelineChange {

  /**
   * Chains a {@link StepChain} to an existing {@link StepChain}, appending the chain to the last implicit step
   */
  static IncompletePipelineChange chainStep(String pipelineFragment, Object... args) {
    return answer -> new AppendStepChange(answer, String.format(pipelineFragment, args));
  }

  /**
   * Add a new {@link StepChain} to the pipeline, disconnected from any other {@link StepChain}s.
   */
  static IncompletePipelineChange newChain(String pipelineFragment, Object... args) {
    return answer -> new StartChainChange(answer, String.format(pipelineFragment, args));
  }

  /**
   * @return a {@link PipelineChange} based on a function that returns a new {@link PipelineDeclaration}.
   */
  static IncompletePipelineChange simple(BiFunction<Answer, IncrementalBuildState, PipelineDeclaration> function) {
    return answer -> new SimpleChange(answer, function);
  }

  /**
   * @return a {@link PipelineChange} that is composed of many other changes that get applied on order
   */
  static IncompletePipelineChange many(List<IncompletePipelineChange> children) {
    return answer -> new MultipleChanges(
      answer,
      children
    );
  }

  /**
   * @return a {@link PipelineChange} that is composed of many other changes that get applied on order
   */
  static IncompletePipelineChange many(IncompletePipelineChange... children) {
    return answer -> new MultipleChanges(
      answer,
      Arrays.asList(children)
    );
  }

  /**
   * @return a {@link PipelineChange} that does nothing
   */
  static IncompletePipelineChange noChange() {
    return answer -> new NoChange(answer);
  }

  /**
   * @return a {@link PipelineChange} that will always fail with the given problems.
   */
  static IncompletePipelineChange failed(List<Problem> problems) {
    return answer -> new PipelineChange() {

      @Override
      public ResultOrProblems<IncrementalBuildState> make(IncrementalBuildState currentState)
          throws BadPipelineChangeException {
        return ResultOrProblems.failed(problems);
      }

      @Override
      public Answer getAnswer() {
        return answer;
      }
    };
  }

  /**
   * Attempt to create a new IncrementalBuildState for this change
   * @return a new IncrementalBuildState with this change applied
   * @throws BadPipelineChangeException if something went wrong that wasn't the user's fault
   */
  ResultOrProblems<IncrementalBuildState> make(IncrementalBuildState currentState)
      throws BadPipelineChangeException;

  /**
   * @return the Answer that was ultimately responsible for this {@link PipelineChange} being introduced.  Note that
   * this might not be the only thing that predicated this change, but it is the *last* thing that caused it (the straw
   * that broke the camel's back, so to speak)
   */
  Answer getAnswer();

  /**
   * Helper method to attempt parsing some pipeline dsl source, wrapping any {@link ParseException}s in a
   * {@link BadPipelineChangeException}
   */
  default PipelineDeclaration parse(String pipelineSource) {
    try {
      return ExpressionParser.INSTANCE.parsePipeline(pipelineSource);
    } catch (LexerException e) {
      throw new BadPipelineChangeException(this, "Could not parse " + pipelineSource, e);
    } catch (ParseException e) {
      throw new BadPipelineChangeException(this, "Could not parse " + pipelineSource, e);
    }
  }

  /**
   * @return the QuestionSet that was responsible for this change
   */
  default QuestionSet getQuestionSet() {
    return getAnswer().getQuestionSet();
  }

  /**
   * @return the Question that was responsible for this change
   */
  default Question getQuestion() {
    return getAnswer().getQuestion();
  }


}
