///|
/// The direction in which a walk follows the links of the graph.
#derive(Eq, Debug)
pub(all) enum LinkDirection {
  /// The links from a document: what it relies on.
  Outgoing
  /// The links to a document: what relies on it.
  Incoming
  /// Both directions.
  Both
}

///|
/// Raised when a number is not a walk depth.
#derive(Eq, Debug)
pub(all) suberror DepthError {
  /// The depth is less than 1.
  InvalidDepth(Int32)
}

///|
/// The number of link steps of a related-documents walk: 1 or more.
#derive(Eq, Compare, Debug)
struct RelatedDepth {
  steps : Int32
}

///|
pub fn RelatedDepth::RelatedDepth(
  steps : Int32,
) -> RelatedDepth raise DepthError {
  guard steps >= 1 else { raise InvalidDepth(steps) }
  { steps, }
}

///|
/// One link step.
pub fn RelatedDepth::one() -> RelatedDepth {
  { steps: 1, }
}

///|
pub fn RelatedDepth::steps(self : RelatedDepth) -> Int32 {
  self.steps
}

///|
/// The documents that have a broken link to `path`, without duplicates,
/// sorted. A document that is deleted or renamed has no backlinks, so this is
/// how to find the documents that still link to it.
pub fn Graph::broken_links_to(self : Graph, path : StorePath) -> Array[DocKey] {
  let keys = []
  if self.broken_targets.get(path) is Some(list) {
    for i in list {
      let from = self.edges[i].from
      if !keys.contains(from) {
        keys.push(from)
      }
    }
  }
  keys.sort()
  keys
}

///|
/// True when the walk adds the document but does not follow its links: index
/// and log documents link to many documents, so a walk through them would
/// reach most of the bundle.
fn is_hub(key : DocKey) -> Bool {
  let kind = kind_of(key.path)
  kind.is_index() || kind is Log
}

///|
/// The documents that the graph connects to `start` within `depth` link steps
/// in `direction`, with the start documents, without duplicates, sorted.
///
/// The walk follows links to documents of every loaded bundle. It does not add
/// file, URI, fragment or broken targets. It adds index and log documents but
/// does not follow their links, unless they are start documents. For each path
/// in `missing` (a target with no loaded document), a walk that follows
/// incoming links adds the documents with a broken link to that path, one step
/// from the start.
pub fn Graph::related(
  self : Graph,
  start : ArrayView[DocKey],
  depth : RelatedDepth,
  direction : LinkDirection,
  missing~ : ArrayView[StorePath] = [],
) -> Array[DocKey] {
  let incoming = direction is (Incoming | Both)
  let outgoing = direction is (Outgoing | Both)
  let seen : Map[DocKey, Unit] = Map([])
  let mut frontier : Array[DocKey] = []
  for key in start {
    if !seen.contains(key) {
      seen[key] = ()
      frontier.push(key)
    }
  }
  // The sources of broken links to a missing target are one step away.
  let mut next : Array[DocKey] = []
  if incoming {
    for path in missing {
      for key in self.broken_links_to(path) {
        if !seen.contains(key) {
          seen[key] = ()
          next.push(key)
        }
      }
    }
  }
  for step in 0.. 0 && is_hub(key) {
        continue
      }
      let neighbours = []
      if outgoing {
        for edge in self.outbound(key) {
          if edge.target is Doc(target) {
            neighbours.push(target)
          }
        }
      }
      if incoming {
        for edge in self.backlinks(key) {
          neighbours.push(edge.from)
        }
      }
      for n in neighbours {
        if !seen.contains(n) {
          seen[n] = ()
          next.push(n)
        }
      }
    }
    frontier = next
    next = []
  }
  let out = seen.keys().collect()
  out.sort()
  out
}

///|
pub extend LinkDirection with Eq::{not_equal, equal}

///|
pub extend LinkDirection with @debug.Debug::{to_repr}

///|
pub extend DepthError with Eq::{not_equal, equal}

///|
pub extend DepthError with @debug.Debug::{to_repr}

///|
pub extend RelatedDepth with Eq::{not_equal, equal}

///|
pub extend RelatedDepth with Compare::{op_lt, op_le, op_ge, compare, op_gt}

///|
pub extend RelatedDepth with @debug.Debug::{to_repr}