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

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.wizard.Question;
import nz.org.riskscape.wizard.bld.IncrementalBuildState;

/**
 * Imposes an ordered-tree structure on to a list of questions to centralize the logic of moving through a set of
 * questions in the order that the questions impose with their dependencies and order in relation to each other.
 */
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class QuestionTree {

  public static QuestionTree singleton(Question question) {
    return fromList(Collections.singletonList(question));
  }

  public static QuestionTree empty() {
    return fromList(Collections.emptyList());
  }

  /**
   * Builds a QuestionTree by searching through the questions in order and building a tree from their dependencies.
   * Questions that share the same dependency are ordered relative to each other in the list such that any question
   * that is before another is also asked/considered in that order.
   */
  public static QuestionTree fromList(List<Question> questions) {
    QuestionTree tree = new QuestionTree(new Node(IncrementalBuildState.EMPTY_QUESTION));

    // contains any questions whose dependencies weren't yet in the tree
    LinkedList<Question> visitList = new LinkedList<>(questions);
    int skips = 0;
    while  (!visitList.isEmpty()) {
      Question q = visitList.removeFirst();
      Node attachTo;

      if (q.getDependsOn().isPresent()) {
        // search for the dependency in the tree
        attachTo = tree.findOne(n -> {
          return n.question.equals(q.getDependsOn().get());
        }).orElse(null);

        if (attachTo == null) {
          // not there, come back later
          visitList.addLast(q);
          skips++;

          if (skips == visitList.size()) {
            // either a loop or a missing dependency
            throw new IllegalStateException("Can not resolve dependencies within " + visitList);
          }
          continue;
        } else {
          // reset skip counter for loop/error detection
          skips = 0;
        }

      } else {
        // no dependency means it's at the root
        attachTo = tree.root;
      }

      attachTo.nodes.add(new Node(q));
    }

    tree.link();
    return tree;
  }

  /**
   * The root of the tree - note that the question here is a placeholder and should never be asked - this is to make it
   * simpler to support multiple questions without any dependencies - these questions are children of the root.
   */
  @Getter
  private final Node root;

  /**
   * A node in the question tree
   */
  @RequiredArgsConstructor
  public static class Node {

    @Getter
    private final Question question;

    private final List<Node> nodes = new LinkedList<>();

    private Node parent;

    public boolean isTopLevel() {
      return parent == null;
    }

    public Node getParent() {
      return parent == null ? this : parent;
    }
  }

  // visits the tree to ensure it is bi-directional for simpler traversal
  void link() {
    LinkedList<Node> queue = new LinkedList<>();

    queue.add(root);

    while (!queue.isEmpty()) {
      Node next = queue.removeFirst();

      next.nodes.forEach(child -> {
        child.parent = next;
        queue.add(child);
      });
    }
  }

  /**
   * Visit the tree in breadth first order
   * @param consumer a function to call that accepts each node that should return some data of the same type to be
   * passed to the next node
   * @param data some data to pass between visits, could be a list or an AtomicReference or whatever
   * @return the data that was given
   */
  public <T> T visitBfs(BiFunction<Node, T, T> consumer, T data) {
    LinkedList<Node> queue = new LinkedList<>();

    queue.add(root);

    while (!queue.isEmpty()) {
      Node next = queue.removeFirst();
      data = consumer.apply(next, data);

      next.nodes.forEach(child -> {
        queue.add(child);
      });
    }

    return data;
  }

  /**
   * Simpler version of {@link #visitBfs(BiFunction, Object)} that doesn't require the visitor to return data - it just
   * returns whatever was given as the `data` parameter
   */
  public <T> T visitBfs(BiConsumer<Node, T> consumer, T data) {
    return visitBfs((node, d) -> {
        consumer.accept(node, d);
        return d;
      },
      data
    );
  }

  /**
   * Find all the nodes in the tree that match the given predicate in breadth-first order
   */
  public List<Node> find(Predicate<Node> predicate) {
    return visitBfs((node, list) -> {
      if (predicate.test(node)) {
        list.add(node);
      }
    }, new LinkedList<>());
  }

  /**
   * Find a single node in the tree using the given predicate
   */
  public Optional<Node> findOne(Predicate<Node> predicate) {
    List<Node> all = find(predicate);

    if (all.size() == 0) {
      return Optional.empty();
    } else if (all.size() == 1) {
      return Optional.of(all.get(0));
    } else {
      throw new IllegalStateException("found many - " + all);
    }
  }

  /**
   * Locate the node that points to the given question
   */
  public Optional<Node> findQuestion(Question question) {
    List<Node> found = visitBfs((node, list) -> {
      if (node.question.equals(question)) {
        list.add(node);
      }
    }, new LinkedList<>());

    return found.isEmpty() ? Optional.empty() : Optional.of(found.get(0));
  }

  /**
   * @return if there are no questions in this tree
   */
  public boolean isEmpty() {
    return root.nodes.isEmpty();
  }

  List<Question> filterReady(Stream<Question> questions, IncrementalBuildState buildState) {
    // NB skip answered already
    return questions
        .filter(q -> !buildState.getAnswer(q).isPresent() && q.readyToBeAsked(buildState))
        .collect(Collectors.toList());
  }

  /**
   * Query the tree to find the list of questions that should be presented to the user as being asked next.  The first
   * question must be answered first, even if it is skipped (by supplying an empty response).
   */
  public List<Question> getNextQuestions(IncrementalBuildState buildState) {
    Node answeredNode = findQuestion(buildState.getQuestion()).orElse(root);

    Node visitPtr = answeredNode;
    while (true) {

      List<Question> children = filterReady(visitPtr.nodes.stream().map(n -> n.question), buildState);

      if (!children.isEmpty()) {
        return children;
      }

      if (visitPtr.isTopLevel()) {
        return Collections.emptyList();
      }

      visitPtr = visitPtr.getParent();
    }
  }

  /**
   * @return true if no more questions can be answered from this tree.
   */
  public boolean isComplete(IncrementalBuildState buildState) {
    return getNextQuestions(buildState).isEmpty();
  }

  /**
   * @return a list of questions that are being skipped if the next question to be answered is `chosen`.  These should
   * be skipped via the {@link Survey2#skip(IncrementalBuildState, Question)} method.
   */
  public List<Question> getSkipped(IncrementalBuildState buildState, Question chosen) {
    List<Question> next = getNextQuestions(buildState);
    int index = next.indexOf(chosen);
    if (index == -1) {
      throw new IllegalArgumentException("question " + chosen + " is not one of the next questions: " + next);
    }
    return next.subList(0, index);
  }

}
