///|
/// The seven node kinds in the XPath 1.0 data model.
pub(all) enum NodeKind {
  Root
  Element
  Attribute
  Namespace
  Text
  ProcessingInstruction
  Comment
} derive(Debug, Eq)

///|
/// Expanded XML name. `prefix` is lexical metadata; equality in XPath name
/// tests is based on `local_name` and `namespace_uri`.
pub struct QName {
  prefix : String?
  local_name : String
  namespace_uri : String?
} derive(Debug)

///|
/// Expanded-name equality ignores the lexical prefix.
pub impl Eq for QName with fn equal(self, other) {
  self.local_name == other.local_name &&
  self.namespace_uri == other.namespace_uri
}

///|
/// Construct an expanded name.
pub fn QName::new(
  local_name : String,
  prefix? : String,
  namespace_uri? : String,
) -> QName {
  { prefix, local_name, namespace_uri }
}

///|
/// Original lexical prefix, when one was present.
pub fn QName::prefix(self : QName) -> String? {
  self.prefix
}

///|
/// Local part used by XPath expanded-name comparison.
pub fn QName::local_name(self : QName) -> String {
  self.local_name
}

///|
/// Resolved namespace URI; `None` denotes the null namespace URI.
pub fn QName::namespace_uri(self : QName) -> String? {
  self.namespace_uri
}

///|
/// Stable identity of one node inside a single `Document`.
///
/// The token is deliberately private. Equality uses physical token identity
/// plus the arena offset, so equal offsets from different documents never
/// compare equal.
pub struct NodeId {
  token : Array[Unit]
  index : Int
}

///|
/// Compare node identities, including document provenance.
pub impl Eq for NodeId with fn equal(self, other) {
  physical_equal(self.token, other.token) && self.index == other.index
}

///|
/// Internal arena record shared by the builder and frozen document.
struct NodeRecord {
  kind : NodeKind
  name : QName?
  mut value : String
  parent : Int?
  children : Array[Int]
  attributes : Array[Int]
  namespaces : Array[Int]
  mut order : Int
}

///|
/// Immutable XPath-owned document arena.
///
/// All nested arrays are deep-copied when the builder is finished and are
/// never exposed directly.
pub struct Document {
  token : Array[Unit]
  nodes : Array[NodeRecord]
  root_index : Int
  id_index : Array[(String, Int)]
}

///|
/// Single-owner builder used by XML and external-tree adapters.
pub struct DocumentBuilder {
  token : Array[Unit]
  nodes : Array[NodeRecord]
  id_index : Array[(String, Int)]
  mut root_index : Int?
  mut finished : Bool
}

///|
const XML_PREFIX : String = "xml"

///|
const XMLNS_PREFIX : String = "xmlns"

///|
const XML_NAMESPACE_URI : String = "http://www.w3.org/XML/1998/namespace"

///|
fn model_error(message : String) -> @diagnostic.XPathError {
  Model(message~)
}

///|
fn new_record(
  kind : NodeKind,
  name : QName?,
  value : String,
  parent : Int?,
) -> NodeRecord {
  {
    kind,
    name,
    value,
    parent,
    children: [],
    attributes: [],
    namespaces: [],
    order: -1,
  }
}

///|
fn NodeRecord::deep_copy(self : NodeRecord) -> NodeRecord {
  {
    kind: self.kind,
    name: self.name,
    value: self.value,
    parent: self.parent,
    children: self.children.copy(),
    attributes: self.attributes.copy(),
    namespaces: self.namespaces.copy(),
    order: self.order,
  }
}

///|
fn checked_index(
  token : Array[Unit],
  nodes : Array[NodeRecord],
  node : NodeId,
) -> Int raise @diagnostic.XPathError {
  if !physical_equal(token, node.token) {
    raise model_error("node identity belongs to a different document")
  }
  if node.index < 0 || node.index >= nodes.length() {
    raise model_error("node identity is outside the document arena")
  }
  node.index
}

///|
fn node_id(token : Array[Unit], index : Int) -> NodeId {
  { token, index }
}

///|
fn is_container(kind : NodeKind) -> Bool {
  kind == Root || kind == Element
}

///|
fn namespace_prefix_of(record : NodeRecord) -> String {
  match record.name {
    Some(name) => name.local_name
    None => ""
  }
}

///|
fn compare_prefixes(left : String, right : String) -> Int {
  let common_length = Int::min(left.length(), right.length())
  for index in 0.. right[index] {
      return 1
    }
  }
  left.length().compare(right.length())
}

///|
fn find_namespace_binding(
  nodes : Array[NodeRecord],
  element_index : Int,
  prefix : String,
) -> String? {
  for namespace_index in nodes[element_index].namespaces {
    let binding = nodes[namespace_index]
    if namespace_prefix_of(binding) == prefix {
      return Some(binding.value)
    }
  }
  None
}