///|
/// A typed structural value. Each alternative holds one diagram family's
/// element type, so family semantics survive the common traversal contract.
#derive(Eq, Debug)
pub(all) enum Element {
  Sequence(SequenceElement)
  Bpmn(BpmnElement)
  Swimlane(SwimlaneElement)
  State(StateElement)
  Flowchart(FlowchartElement)
  Architecture(ArchitectureElement)
  Regex(RegexElement)
  Ebnf(EbnfElement)
  DataTree(DataTreeElement)
}

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

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

///|
/// The family of the element, for example `flowchart`. It equals
/// `@render.Diagram::kind_name` of the diagram that owns the element.
pub fn Element::family(self : Element) -> String {
  match self {
    Sequence(_) => "sequence"
    Bpmn(_) => "bpmn"
    Swimlane(_) => "swimlane"
    State(_) => "state"
    Flowchart(_) => "flowchart"
    Architecture(_) => "architecture"
    Regex(_) => "regex"
    Ebnf(_) => "ebnf"
    DataTree(_) => "data-tree"
  }
}

///|
/// The name of the element's alternative within its family, for example `node`.
pub fn Element::kind_name(self : Element) -> String {
  match self {
    Sequence(e) => e.kind_name()
    Bpmn(e) => e.kind_name()
    Swimlane(e) => e.kind_name()
    State(e) => e.kind_name()
    Flowchart(e) => e.kind_name()
    Architecture(e) => e.kind_name()
    Regex(e) => e.kind_name()
    Ebnf(e) => e.kind_name()
    DataTree(e) => e.kind_name()
  }
}

///|
/// The model identifier of the element, when its family has one. Identifiers
/// are data, not identity: they can repeat or be absent. Use a `Handle` to
/// identify an element.
pub fn Element::id(self : Element) -> String? {
  match self {
    Sequence(e) => e.id()
    Bpmn(e) => e.id()
    Swimlane(e) => e.id()
    State(e) => e.id()
    Flowchart(e) => e.id()
    Architecture(e) => e.id()
    Regex(e) => e.id()
    Ebnf(e) => e.id()
    DataTree(e) => e.id()
  }
}

///|
#derive(Eq, Debug)
pub(all) enum Control {
  Continue
  SkipChildren
  Stop
}

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

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

///|
#derive(Eq, Debug)
pub(all) enum Outcome {
  Running
  Completed
  Stopped
  LimitExceeded
  Failed
}

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

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

///|
#derive(Eq, Debug)
pub(all) enum Phase {
  Enter
  Leave
}

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

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

///|
/// Ordinals and paths belong to one Tree. The host binding supplies its owner token.
#derive(Eq, Debug)
pub struct Observation {
  phase : Phase
  ordinal : Int32
  parent : Int32?
  path : ReadOnlyArray[Int32]
  element : Element
  span : @diagrams.Span?
}

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

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

///|
/// Why an index or a handle could not be built or resolved.
#derive(Eq, Debug)
pub(all) enum IdentityError {
  /// The handle belongs to another tree, even one built from an equal model.
  RevisionMismatch
  /// The ordinal is not an element of this tree.
  OutOfRange
}

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

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

///|
priv struct Record {
  element : Element
  parent : Int32?
  children : ReadOnlyArray[Int32]
  span : @diagrams.Span?
  slot : Int32
}

///|
/// The identity of one tree. Two trees never share a revision, even when they
/// index equal models, so handles never select an element by matching text.
priv struct Revision {
  label : Int32
}

///|
/// A bounded containment index over one immutable model revision. The root is
/// ordinal 0; ordinals follow model order, so repeated walks agree.
pub struct Tree {
  priv records : ReadOnlyArray[Record]
  priv revision : Revision
  priv depth : Int32
}

///|
/// One element of one tree.
pub struct Handle {
  priv revision : Revision
  ordinal : Int32
}

///|
pub fn Handle::ordinal(self : Handle) -> Int32 {
  self.ordinal
}

///|
/// Handles are equal when they name the same element of the same tree.
pub impl Eq for Handle with fn equal(self, other) {
  self.same(other)
}

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

///|
pub impl @debug.Debug for Handle with fn to_repr(self) {
  @debug.Repr::Repr(("Handle", self.revision.label, self.ordinal))
}

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

///|
/// True when both handles name the same element of the same tree.
pub fn Handle::same(self : Handle, other : Handle) -> Bool {
  physical_equal(self.revision, other.revision) && self.ordinal == other.ordinal
}

///|
/// The caller's revision label, for example a document version. The label is
/// informative; handle checks use the tree's own identity.
pub fn Tree::revision_label(self : Tree) -> Int32 {
  self.revision.label
}

///|
pub fn Tree::length(self : Tree) -> Int32 {
  self.records.length()
}

///|
/// The deepest containment path, counting the root as depth 1.
pub fn Tree::depth(self : Tree) -> Int32 {
  self.depth
}

///|
pub fn Tree::handle(self : Tree, ordinal : Int32) -> Handle? {
  if ordinal < 0 || ordinal >= self.records.length() {
    None
  } else {
    Some({ revision: self.revision, ordinal, })
  }
}

///|
/// True when `handle` was issued by this tree.
pub fn Tree::owns(self : Tree, handle : Handle) -> Bool {
  physical_equal(self.revision, handle.revision)
}

///|
pub fn Tree::lookup(
  self : Tree,
  handle : Handle,
) -> Result[Element, IdentityError] {
  if !self.owns(handle) {
    Err(RevisionMismatch)
  } else if handle.ordinal < 0 || handle.ordinal >= self.records.length() {
    Err(OutOfRange)
  } else {
    Ok(self.records[handle.ordinal].element)
  }
}

///|
pub fn Tree::resolve(self : Tree, handle : Handle) -> Element? {
  match self.lookup(handle) {
    Ok(element) => Some(element)
    Err(_) => None
  }
}

///|
pub fn Tree::element(self : Tree, ordinal : Int32) -> Element? {
  if ordinal < 0 || ordinal >= self.records.length() {
    None
  } else {
    Some(self.records[ordinal].element)
  }
}

///|
pub fn Tree::parent(self : Tree, ordinal : Int32) -> Int32? {
  if ordinal < 0 || ordinal >= self.records.length() {
    None
  } else {
    self.records[ordinal].parent
  }
}

///|
pub fn Tree::children(self : Tree, ordinal : Int32) -> ReadOnlyArray[Int32] {
  if ordinal < 0 || ordinal >= self.records.length() {
    []
  } else {
    self.records[ordinal].children
  }
}

///|
pub fn Tree::span(self : Tree, ordinal : Int32) -> @diagrams.Span? {
  if ordinal < 0 || ordinal >= self.records.length() {
    None
  } else {
    self.records[ordinal].span
  }
}

///|
/// The position of the element in the model array that holds it, for example
/// the index of a flowchart node in `Flowchart::nodes`, or of a sequence event
/// in the event list of its parent section. The root has slot -1.
pub fn Tree::slot(self : Tree, ordinal : Int32) -> Int32 {
  if ordinal < 0 || ordinal >= self.records.length() {
    -1
  } else {
    self.records[ordinal].slot
  }
}

///|
/// The ordinals of the elements whose `Element::id` equals `id`, in model order.
/// Identifiers can repeat, so the result can have several ordinals.
pub fn Tree::find(self : Tree, id : String) -> ReadOnlyArray[Int32] {
  let found = []
  for i, record in self.records {
    if record.element.id() == Some(id) {
      found.push(i)
    }
  }
  ReadOnlyArray::from_array(found)
}

///|
/// Index limits. `elements` bounds indexed elements, `depth` the containment
/// depth (the root is depth 1) and `work` the effort of resolving containers.
pub struct IndexLimits {
  elements : Int32
  depth : Int32
  work : Int32
}

///|
pub fn IndexLimits::new(
  elements~ : Int32 = 100000,
  depth~ : Int32 = 100000,
  work~ : Int32 = 1000000,
) -> IndexLimits {
  { elements, depth, work, }
}

///|
/// A builder shared by family adapters. Containers are registered by kind and
/// identifier; a repeated identifier is ambiguous only when a child names it.
priv struct Builder {
  values : Array[Element]
  owners : Array[Int32?]
  spans : Array[@diagrams.Span?]
  slots : Array[Int32]
  counters : Map[String, Int32]
  containers : Map[String, Int32]
  limits : IndexLimits
  mut overflow : Bool
  mut error : String?
  mut work : Int32
}

///|
fn Builder::new(root : Element, limits : IndexLimits) -> Builder {
  {
    values: [root],
    owners: [None],
    spans: [None],
    slots: [-1],
    counters: Map([]),
    containers: Map([]),
    limits,
    overflow: limits.elements < 1 || limits.depth < 1 || limits.work < 1,
    error: None,
    work: 0,
  }
}

///|
/// Spend adapter work; false after recording `work-limit`.
fn Builder::charge(self : Builder, amount : Int32) -> Bool {
  if amount > self.limits.work - self.work {
    self.fail("work-limit")
    return false
  }
  self.work += amount
  true
}

///|
/// Add an identifier graph in pre-order without recursion. The first visit of
/// an identifier owns it; later references and missing identifiers are not
/// followed, so shared or cyclic references terminate.
fn Builder::graph(
  self : Builder,
  roots : Array[(String, Int32)],
  children : (String) -> ReadOnlyArray[String]?,
  add : (String, Int32) -> Int32,
) -> Unit {
  let visited : Map[String, Bool] = Map([])
  let stack = roots.rev()
  while stack.pop() is Some((id, parent)) {
    if visited.contains(id) || parent < 0 {
      continue
    }
    guard children(id) is Some(items) else { continue }
    if !self.charge(1 + items.length()) {
      return
    }
    visited[id] = true
    let index = add(id, parent)
    for i = items.length() - 1; i >= 0; i = i - 1 {
      stack.push((items[i], index))
    }
  }
}

///|
/// Add an element owned by the root. Returns its ordinal, or -1 past the limit.
fn Builder::add(
  self : Builder,
  element : Element,
  span~ : @diagrams.Span? = None,
  parent~ : Int32 = 0,
  slot~ : Int32 = -1,
) -> Int32 {
  let index = self.values.length()
  if self.overflow || index >= self.limits.elements {
    self.overflow = true
    return -1
  }
  self.values.push(element)
  self.owners.push(Some(parent))
  self.spans.push(span)
  self.slots.push(slot)
  index
}

///|
/// The next slot of a model array, for adapters that add each array in order.
fn Builder::slot(self : Builder, field : String) -> Int32 {
  let n = self.counters.get(field).unwrap_or(0)
  self.counters[field] = n + 1
  n
}

///|
fn Builder::fail(self : Builder, error : String) -> Unit {
  if self.error is None {
    self.error = Some(error)
  }
}

///|
/// Register `index` as the container `kind`/`id`. A second registration of the
/// same key makes the key ambiguous.
fn Builder::register(
  self : Builder,
  kind : String,
  id : String,
  index : Int32,
) -> Unit {
  if index < 0 {
    return
  }
  let key = kind + "\u{0}" + id
  if self.containers.contains(key) {
    self.containers[key] = -1
  } else {
    self.containers[key] = index
  }
}

///|
/// The ordinal of a registered container, or -1 after recording an error.
fn Builder::container(self : Builder, kind : String, id : String) -> Int32 {
  match self.containers.get(kind + "\u{0}" + id) {
    Some(-1) => {
      self.fail("ambiguous-\{kind}")
      -1
    }
    Some(index) => index
    None => {
      self.fail("missing-parent")
      -1
    }
  }
}

///|
fn Builder::contains(self : Builder, kind : String, id : String) -> Bool {
  self.containers.contains(kind + "\u{0}" + id)
}

///|
/// Change the owner of `index`. Negative values are ignored, so a failed
/// container lookup keeps the earlier owner and its recorded error.
fn Builder::own(self : Builder, index : Int32, parent : Int32) -> Unit {
  if index > 0 && parent >= 0 && index < self.owners.length() {
    self.owners[index] = Some(parent)
  }
}

///|
/// Check containment without recursion, so depth does not use the host stack.
fn Builder::finish(self : Builder, revision : Int32) -> Result[Tree, String] {
  if self.overflow {
    return Err("element-limit")
  }
  if self.error is Some(error) {
    return Err(error)
  }
  let n = self.values.length()
  // 0 = unvisited, 1 = on the current chain, 2 = done.
  let state : Array[Int32] = Array::make(n, 0)
  let depth : Array[Int32] = Array::make(n, 0)
  state[0] = 2
  depth[0] = 1
  let mut work = 0
  let mut deepest = 1
  let chain : Array[Int32] = []
  for i in 1.. self.limits.work {
        return Err("work-limit")
      }
      state[current] = 1
      chain.push(current)
      guard self.owners[current] is Some(parent) else {
        return Err("missing-parent")
      }
      current = parent
    }
    if state[current] == 1 {
      return Err("containment-cycle")
    }
    let mut base = depth[current]
    while chain.pop() is Some(index) {
      base += 1
      if base > self.limits.depth {
        return Err("depth-limit")
      }
      depth[index] = base
      state[index] = 2
      if base > deepest {
        deepest = base
      }
    }
  }
  let children : Array[Array[Int32]] = Array::makei(n, _ => [])
  for i, owner in self.owners {
    if owner is Some(parent) {
      children[parent].push(i)
    }
  }
  Ok({
    records: ReadOnlyArray::from_array(
      self.values.mapi((i, element) => {
        element,
        parent: self.owners[i],
        children: ReadOnlyArray::from_array(children[i]),
        span: self.spans[i],
        slot: self.slots[i],
      }),
    ),
    revision: { label: revision, },
    depth: deepest,
  })
}

///|
/// Index any shared Diagram. Each family documents its containment map.
pub fn Tree::of(
  diagram : @render.Diagram,
  limits~ : IndexLimits = IndexLimits::new(),
  revision~ : Int32 = 0,
) -> Result[Tree, String] {
  match diagram {
    Sequence(view) => Tree::sequence(view, limits~, revision~)
    Bpmn(view) => Tree::bpmn(view, limits~, revision~)
    Swimlane(view) => Tree::swimlane(view, limits~, revision~)
    State(view) => Tree::state(view, limits~, revision~)
    Flowchart(view) => Tree::flowchart(view, limits~, revision~)
    Architecture(view) => Tree::architecture(view, limits~, revision~)
    Regex(view) => Tree::regex(view, limits~, revision~)
    Ebnf(view) => Tree::ebnf(view, limits~, revision~)
    DataTree(view) => Tree::data_tree(view, limits~, revision~)
  }
}

///|
priv struct Frame {
  ordinal : Int32
  mut next : Int32
}

///|
/// A resumable pull traversal. Budgets are cumulative across `next` calls.
pub struct Cursor {
  priv tree : Tree
  priv stack : Array[Frame]
  priv mut pending : Int32?
  priv mut started : Bool
  priv limit : Int32
  priv visits_limit : Int32
  priv depth_limit : Int32
  priv mut emitted : Int32
  priv mut visits : Int32
  priv mut result : Outcome
}

///|
/// `observations_limit` bounds enter and leave observations, `visits_limit`
/// the entered elements and `depth_limit` the containment depth of an enter.
pub fn Tree::cursor(
  self : Tree,
  observations_limit~ : Int32 = 200000,
  visits_limit~ : Int32 = 100000,
  depth_limit~ : Int32 = 100000,
) -> Cursor {
  {
    tree: self,
    stack: [],
    pending: Some(0),
    started: false,
    limit: observations_limit,
    visits_limit,
    depth_limit,
    emitted: 0,
    visits: 0,
    result: Running,
  }
}

///|
pub fn Cursor::outcome(self : Cursor) -> Outcome {
  self.result
}

///|
/// The tree that this cursor walks.
pub fn Cursor::tree(self : Cursor) -> Tree {
  self.tree
}

///|
/// Mark the traversal as failed, for example after a consumer failure.
pub fn Cursor::fail(self : Cursor) -> Unit {
  if self.result == Running {
    self.result = Failed
  }
  self.pending = None
  self.stack.clear()
}

///|
pub fn Cursor::stop(self : Cursor) -> Unit {
  if self.result == Running {
    self.result = Stopped
  }
  self.pending = None
  self.stack.clear()
}

///|
fn Cursor::exceed(self : Cursor) -> Observation? {
  self.stop()
  self.result = LimitExceeded
  None
}

///|
/// Apply `control` to the previous enter, then return the next observation.
/// SkipChildren still yields the matching leave; Stop yields nothing more.
pub fn Cursor::next(
  self : Cursor,
  control~ : Control = Continue,
) -> Observation? {
  if self.result != Running {
    return None
  }
  if control == Stop {
    self.stop()
    return None
  }
  if self.started {
    if self.pending is Some(ordinal) {
      self.pending = None
      self.stack.push({
        ordinal,
        next: if control == SkipChildren {
          self.tree.records[ordinal].children.length()
        } else {
          0
        },
      })
    }
  } else {
    self.started = true
  }
  let pair = if self.pending is Some(ordinal) {
    Some((Enter, ordinal))
  } else if self.stack.last() is Some(frame) {
    let children = self.tree.records[frame.ordinal].children
    if frame.next < children.length() {
      let ordinal = children[frame.next]
      frame.next += 1
      self.pending = Some(ordinal)
      Some((Enter, ordinal))
    } else {
      self.stack.pop() |> ignore
      Some((Leave, frame.ordinal))
    }
  } else {
    None
  }
  guard pair is Some((phase, ordinal)) else {
    self.result = Completed
    return None
  }
  if self.emitted >= self.limit {
    return self.exceed()
  }
  if phase == Enter {
    if self.visits >= self.visits_limit ||
      self.stack.length() + 1 > self.depth_limit {
      return self.exceed()
    }
    self.visits += 1
  }
  self.emitted += 1
  let record = self.tree.records[ordinal]
  let path = self.stack.map(f => f.ordinal)
  path.push(ordinal)
  Some({
    phase,
    ordinal,
    parent: record.parent,
    path: ReadOnlyArray::from_array(path),
    element: record.element,
    span: record.span,
  })
}

///|
/// Push traversal over the same resumable engine as `cursor`. A consumer
/// failure stops delivery immediately and propagates to the caller.
pub fn Tree::walk(
  self : Tree,
  consume : (Observation) -> Control raise?,
  observations_limit~ : Int32 = 200000,
  visits_limit~ : Int32 = 100000,
  depth_limit~ : Int32 = 100000,
) -> Outcome raise? {
  let cursor = self.cursor(observations_limit~, visits_limit~, depth_limit~)
  let mut control = Continue
  errdefer cursor.fail()
  while cursor.next(control~) is Some(event) {
    control = consume(event)
  }
  cursor.outcome()
}

///|
/// Fold observations into consumer state without a visual tree. The step
/// returns the next state and the control for the following observation.
pub fn[S] Tree::fold(
  self : Tree,
  initial : S,
  step : (S, Observation) -> (S, Control) raise?,
  observations_limit~ : Int32 = 200000,
) -> (S, Outcome) raise? {
  let mut state = initial
  let outcome = self.walk(
    event => {
      let (next, control) = step(state, event)
      state = next
      control
    },
    observations_limit~,
  )
  (state, outcome)
}