///|
pub(all) struct ManualReference {
  name : String
  section : String
  block_indices : Array[Int32]
} derive(Eq, Debug)

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

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

///|
pub(all) struct LinkEntry {
  target : String
  label : String
  block_index : Int32
  safe : Bool
} derive(Eq, Debug)

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

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

///|
fn reference_name_char(c : Char) -> Bool {
  c.is_ascii_alphabetic() ||
  c.is_ascii_digit() ||
  c == '_' ||
  c == '-' ||
  c == '.' ||
  c == '+'
}

///|
/// Extract conventional name(section) references, including split font runs.
pub fn references(doc : Document) -> Array[ManualReference] {
  let refs : Array[ManualReference] = []
  let indices : Map[String, Int32] = Map([])
  for bi = 0; bi < doc.blocks.length(); bi = bi + 1 {
    let block = doc.blocks[bi]
    let text = match block.kind {
      Tagged(term) => inline_text(term) + " " + inline_text(block.inlines)
      _ => inline_text(block.inlines)
    }
    let chars = text.to_array()
    for i = 1; i < chars.length(); i = i + 1 {
      if chars[i] != '(' || !reference_name_char(chars[i - 1]) {
        continue
      }
      let mut start = i - 1
      while start > 0 && reference_name_char(chars[start - 1]) {
        start = start - 1
      }
      let mut end = i + 1
      while end < chars.length() &&
            (chars[end].is_ascii_digit() || chars[end].is_ascii_alphabetic()) {
        end = end + 1
      }
      if end == i + 1 ||
        end >= chars.length() ||
        chars[end] != ')' ||
        end - i > 9 {
        continue
      }
      if chars[i + 1] < '1' || chars[i + 1] > '9' {
        continue
      }
      let name = chars_string(chars, start, i)
      let section = chars_string(chars, i + 1, end)
      let key = name + "(" + section + ")"
      match indices.get(key) {
        None => {
          indices.set(key, refs.length())
          refs.push({ name, section, block_indices: [bi], })
        }
        Some(index) => {
          let locations = refs[index].block_indices
          if locations[locations.length() - 1] != bi {
            locations.push(bi)
          }
        }
      }
    }
  }
  refs
}

///|
fn collect_links(
  runs : Array[Inline],
  bi : Int32,
  result : Array[LinkEntry],
) -> Unit {
  let mut target : String? = None
  let label = StringBuilder()
  for run in runs {
    if run.target != target {
      if target is Some(value) {
        result.push({
          target: value,
          label: label.to_string(),
          block_index: bi,
          safe: safe_target(value),
        })
      }
      label.reset()
      target = run.target
    }
    if target is Some(_) {
      label.write_string(run.text)
    }
  }
  if target is Some(value) {
    result.push({
      target: value,
      label: label.to_string(),
      block_index: bi,
      safe: safe_target(value),
    })
  }
}

///|
pub fn links(doc : Document) -> Array[LinkEntry] {
  let result : Array[LinkEntry] = []
  for i = 0; i < doc.blocks.length(); i = i + 1 {
    let block = doc.blocks[i]
    if block.kind is Tagged(term) {
      collect_links(term, i, result)
    }
    collect_links(block.inlines, i, result)
  }
  result
}

///|
/// Editorial checks are separate from parsing so incomplete documents stay useful.
pub fn lint(doc : Document) -> Array[Diagnostic] {
  let result : Array[Diagnostic] = []
  if doc.metadata.title == "" {
    result.push(diagnostic("missing-th", "Document has no TH title", 1))
  }
  let mut has_section = false
  let mut has_name = false
  for block in doc.blocks {
    match block.kind {
      Heading(level) => {
        let title = inline_text(block.inlines).trim().to_owned()
        if level == 1 {
          has_section = true
        } else if !has_section {
          result.push(
            diagnostic(
              "orphan-subsection",
              "SS appears before SH",
              block.span.line,
            ),
          )
        }
        if title.to_lower() == "name" {
          has_name = true
        }
        if title == "" {
          result.push(
            diagnostic(
              "empty-heading",
              "Heading text is empty",
              block.span.line,
            ),
          )
        }
      }
      Tagged(term) =>
        if inline_text(term).trim().is_empty() {
          result.push(
            diagnostic(
              "empty-tag",
              "Definition has an empty term",
              block.span.line,
            ),
          )
        }
      _ => ()
    }
  }
  if !has_name {
    result.push(diagnostic("missing-name-section", "No NAME section found", 1))
  }
  result
}