///|
pub(all) struct OutlineEntry {
  level : Int32
  title : String
  anchor : String
  block_index : Int32
  span : Span
} derive(Eq, Debug)

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

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

///|
fn anchor_base(text : String) -> String {
  let out = StringBuilder()
  let mut separator = false
  for c in text.iter() {
    if (c.is_ascii_alphabetic() || c.is_ascii_digit()) ||
      (!c.is_ascii() && !c.is_whitespace() && !c.is_control()) {
      if separator && !out.is_empty() {
        out.write_char('-')
      }
      out.write_char(c.to_ascii_lowercase())
      separator = false
    } else {
      separator = true
    }
  }
  let base = out.to_string()
  if base == "" {
    "section"
  } else {
    base
  }
}

///|
/// Anchors are deterministic and unique even when explicit suffixes collide.
pub fn outline(doc : Document) -> Array[OutlineEntry] {
  let used : Map[String, Bool] = Map([])
  let next_suffix : Map[String, Int32] = Map([])
  let entries : Array[OutlineEntry] = []
  for i = 0; i < doc.blocks.length(); i = i + 1 {
    let block = doc.blocks[i]
    if block.kind is Heading(level) {
      let title = inline_text(block.inlines)
      let base = anchor_base(title)
      let mut candidate = base
      let mut suffix = next_suffix.get(base).unwrap_or(2)
      while used.contains(candidate) {
        candidate = base + "-" + suffix.to_string()
        suffix = suffix + 1
      }
      used.set(candidate, true)
      next_suffix.set(base, suffix)
      entries.push({
        level,
        title,
        anchor: candidate,
        block_index: i,
        span: block.span,
      })
    }
  }
  entries
}

///|
/// Return the blocks under a heading, stopping before the next peer/ancestor.
pub fn section_blocks(doc : Document, anchor : String) -> Array[Block]? {
  let entries = outline(doc)
  for entry in entries {
    if entry.anchor == anchor {
      let result : Array[Block] = []
      for i = entry.block_index + 1; i < doc.blocks.length(); i = i + 1 {
        let block = doc.blocks[i]
        if block.kind is Heading(level) && level <= entry.level {
          break
        }
        result.push(block)
      }
      return Some(result)
    }
  }
  None
}