///|
#non_exhaustive
#derive(Debug, Eq)
pub(all) suberror RouteConflict {
  DuplicateRoute(meth~ : @http.Method, path~ : String)
  AmbiguousParam(path~ : String, existing~ : String, incoming~ : String)
  InvalidPattern(pattern~ : String, reason~ : String)
}

///|
#derive(Debug, Eq)
pub(all) struct RouteParams {
  values : Array[(String, String)]
}

///|
pub fn RouteParams::RouteParams(
  values~ : Array[(String, String)] = [],
) -> RouteParams {
  { values: values.copy(), }
}

///|
pub fn RouteParams::get(self : RouteParams, name : StringView) -> String? {
  for pair in self.values {
    if pair.0[:] == name {
      return Some(pair.1)
    }
  }
  None
}

///|
pub fn RouteParams::entries(self : RouteParams) -> Array[(String, String)] {
  self.values.copy()
}

///|
#derive(Debug, Eq)
pub(all) struct RouteMatch[T] {
  value : T
  params : RouteParams
  pattern : String
}

///|
/// Compressed character-level Radix node for static segment lookup (splits shared prefixes like "users" / "user-groups")
/// Children are kept sorted ascending by `first_cu` for O(log K) dispatch when fanout > 4.
priv struct StaticRadixNode[V] {
  mut value : V?
  children : Array[StaticRadixEdge[V]]
}

///|
priv struct StaticRadixEdge[V] {
  first_cu : UInt16
  mut prefix : String
  node : StaticRadixNode[V]
}

///|
fn[V] StaticRadixNode::new() -> StaticRadixNode[V] {
  { value: None, children: [], }
}

///|
fn[V] insert_edge_sorted(
  children : Array[StaticRadixEdge[V]],
  edge : StaticRadixEdge[V],
) -> Unit {
  let target = edge.first_cu
  let mut idx = children.length()
  for i in 0.. target {
      idx = i
      break
    }
  }
  children.insert(idx, edge)
}

///|
fn[V] find_edge_by_first_cu(
  children : Array[StaticRadixEdge[V]],
  cu : UInt16,
) -> StaticRadixEdge[V]? {
  let len = children.length()
  if len <= 4 {
    for i in 0.. cu {
        return None
      }
    }
    None
  } else {
    let mut lo = 0
    let mut hi = len - 1
    while lo <= hi {
      let mid = lo + (hi - lo) / 2
      let edge = children[mid]
      if edge.first_cu == cu {
        return Some(edge)
      } else if edge.first_cu < cu {
        lo = mid + 1
      } else {
        hi = mid - 1
      }
    }
    None
  }
}

///|
fn common_prefix_len(a : String, b : String) -> Int32 {
  let min_len = if a.length() < b.length() { a.length() } else { b.length() }
  let mut i = 0
  while i < min_len && a.code_unit_at(i) == b.code_unit_at(i) {
    i = i + 1
  }
  i
}

///|
fn[V] StaticRadixNode::get_or_insert(
  self : StaticRadixNode[V],
  key : String,
  make_default : () -> V,
) -> V {
  let mut cur = self
  let mut rem = key
  for ;; {
    if rem.is_empty() {
      match cur.value {
        Some(v) => return v
        None => {
          let v = make_default()
          cur.value = Some(v)
          return v
        }
      }
    }
    let first = rem.code_unit_at(0)
    match find_edge_by_first_cu(cur.children, first) {
      None => {
        let leaf : StaticRadixNode[V] = StaticRadixNode::new()
        let v = make_default()
        leaf.value = Some(v)
        insert_edge_sorted(cur.children, {
          first_cu: first,
          prefix: rem,
          node: leaf,
        })
        return v
      }
      Some(edge) => {
        let lcp = common_prefix_len(edge.prefix, rem)
        if lcp == edge.prefix.length() {
          rem = rem[lcp:].to_owned()
          cur = edge.node
        } else {
          // Split edge.prefix at lcp; edge.first_cu stays unchanged
          let shared = edge.prefix[:lcp].to_owned()
          let old_suffix = edge.prefix[lcp:].to_owned()
          let new_suffix = rem[lcp:].to_owned()
          let moved_old : StaticRadixNode[V] = {
            value: edge.node.value,
            children: edge.node.children.copy(),
          }
          edge.prefix = shared
          edge.node.value = None
          edge.node.children.clear()
          insert_edge_sorted(edge.node.children, {
            first_cu: old_suffix.code_unit_at(0),
            prefix: old_suffix,
            node: moved_old,
          })
          if new_suffix.is_empty() {
            let v = make_default()
            edge.node.value = Some(v)
            return v
          } else {
            let new_leaf : StaticRadixNode[V] = StaticRadixNode::new()
            let v = make_default()
            new_leaf.value = Some(v)
            insert_edge_sorted(edge.node.children, {
              first_cu: new_suffix.code_unit_at(0),
              prefix: new_suffix,
              node: new_leaf,
            })
            return v
          }
        }
      }
    }
  }
}

///|
fn[V] StaticRadixNode::find_slice(
  self : StaticRadixNode[V],
  path : StringView,
  seg_start : Int32,
  seg_end : Int32,
) -> V? {
  let mut cur = self
  let mut pos = seg_start
  while pos < seg_end {
    let cu = path.code_unit_at(pos)
    match find_edge_by_first_cu(cur.children, cu) {
      None => return None
      Some(edge) => {
        let plen = edge.prefix.length()
        if pos + plen > seg_end {
          return None
        }
        let mut i = 1
        while i < plen {
          if path.code_unit_at(pos + i) != edge.prefix.code_unit_at(i) {
            return None
          }
          i = i + 1
        }
        pos = pos + plen
        cur = edge.node
      }
    }
  }
  cur.value
}

///|
priv struct RouteEntry[T] {
  value : T
  pattern : String
}

///|
priv struct RouteNode[T] {
  handlers : Map[@http.Method, RouteEntry[T]]
  static_children : StaticRadixNode[RouteNode[T]]
  mut param_child : (String, RouteNode[T])?
  mut wildcard_child : (String, RouteNode[T])?
}

///|
fn[T] RouteNode::new() -> RouteNode[T] {
  {
    handlers: Map([]),
    static_children: StaticRadixNode::new(),
    param_child: None,
    wildcard_child: None,
  }
}

///|
/// Radix/Trie 路由表(不透明类型,分段匹配完成后再对单段参数做 RFC 3986 解码以防 %2F 穿越)
pub struct Router[T] {
  priv root : RouteNode[T]
  priv registered : Array[(@http.Method, String)]
}

///|
pub fn[T] Router::Router() -> Router[T] {
  { root: RouteNode::new(), registered: [], }
}

///|
fn normalize_path(path : StringView) -> String {
  let s = path.to_owned()
  if s.length() <= 1 {
    return s
  }
  let mut end = s.length()
  while end > 1 && s.code_unit_at(end - 1) == '/' {
    end = end - 1
  }
  s[:end].to_owned()
}

///|
fn split_segments(norm : String) -> Array[String] {
  if norm == "/" || norm.is_empty() {
    return []
  }
  let trimmed = if norm.has_prefix("/") { norm[1:].to_owned() } else { norm }
  let segs : Array[String] = []
  for part in trimmed.split("/") {
    segs.push(part.to_owned())
  }
  segs
}

///|
pub fn[T] Router::add(
  self : Router[T],
  meth : @http.Method,
  pattern : StringView,
  value : T,
) -> Unit raise RouteConflict {
  let raw = pattern.to_owned()
  if raw.is_empty() || !raw.has_prefix("/") {
    raise RouteConflict::InvalidPattern(
      pattern=raw,
      reason="route pattern must start with '/'",
    )
  }
  let norm = normalize_path(raw)
  let segs = split_segments(norm)
  let mut cur = self.root
  for i in 0..
          if existing != pname {
            raise RouteConflict::AmbiguousParam(
              path=norm,
              existing~,
              incoming=pname,
            )
          } else {
            cur = child
          }
        None => {
          let child : RouteNode[T] = RouteNode::new()
          cur.param_child = Some((pname, child))
          cur = child
        }
      }
    } else if seg.has_prefix("*") {
      if i != segs.length() - 1 {
        raise RouteConflict::InvalidPattern(
          pattern=raw,
          reason="wildcard segment must be the final segment",
        )
      }
      let wname = seg[1:].to_owned()
      let effective_name = if wname.is_empty() { "*" } else { wname }
      match cur.wildcard_child {
        Some((existing, child)) =>
          if existing != effective_name {
            raise RouteConflict::AmbiguousParam(
              path=norm,
              existing~,
              incoming=effective_name,
            )
          } else {
            cur = child
          }
        None => {
          let child : RouteNode[T] = RouteNode::new()
          cur.wildcard_child = Some((effective_name, child))
          cur = child
        }
      }
    } else {
      cur = cur.static_children.get_or_insert(seg, () => RouteNode::new())
    }
  }
  if cur.handlers.contains(meth) {
    raise RouteConflict::DuplicateRoute(meth~, path=norm)
  }
  cur.handlers[meth] = { value, pattern: norm, }
  self.registered.push((meth, norm))
}

///|
fn[T] lookup_handler(
  node : RouteNode[T],
  meth : @http.Method,
) -> RouteEntry[T]? {
  match node.handlers.get(meth) {
    Some(entry) => Some(entry)
    None =>
      if meth == @http.Method::Head {
        node.handlers.get(@http.Method::Get)
      } else {
        None
      }
  }
}

///|
/// Zero-copy path normalization end index: returns -1 if path does not start with '/',
/// otherwise returns the exclusive end index after stripping trailing slashes (keeping root "/").
fn effective_path_end(path : StringView) -> Int32 {
  let len = path.length()
  if len == 0 || path.code_unit_at(0) != '/' {
    return -1
  }
  let mut end = len
  while end > 1 && path.code_unit_at(end - 1) == '/' {
    end = end - 1
  }
  end
}

///|
fn[T] match_node_cursor(
  node : RouteNode[T],
  meth : @http.Method,
  path : StringView,
  pos : Int32,
  end : Int32,
  raw_params : Ref[Array[(String, Int32, Int32)]?],
) -> RouteEntry[T]? {
  if pos > end {
    return lookup_handler(node, meth)
  }
  let mut slash = pos
  while slash < end && path.code_unit_at(slash) != '/' {
    slash = slash + 1
  }
  let next_pos = if slash < end { slash + 1 } else { end + 1 }
  // 1. Static (highest priority)
  match node.static_children.find_slice(path, pos, slash) {
    Some(child) =>
      match match_node_cursor(child, meth, path, next_pos, end, raw_params) {
        Some(res) => return Some(res)
        None => ()
      }
    None => ()
  }
  // 2. Param (middle priority; single non-empty segment)
  if slash > pos {
    match node.param_child {
      Some((pname, child)) => {
        let arr = match raw_params.val {
          Some(a) => a
          None => {
            let a : Array[(String, Int32, Int32)] = []
            raw_params.val = Some(a)
            a
          }
        }
        arr.push((pname, pos, slash))
        match match_node_cursor(child, meth, path, next_pos, end, raw_params) {
          Some(found) => return Some(found)
          None => ignore(arr.pop())
        }
      }
      None => ()
    }
  }
  // 3. Wildcard (lowest priority; captures remaining slice path[pos:end] without split/join)
  match node.wildcard_child {
    Some((wname, child)) =>
      match lookup_handler(child, meth) {
        Some(entry) => {
          let arr = match raw_params.val {
            Some(a) => a
            None => {
              let a : Array[(String, Int32, Int32)] = []
              raw_params.val = Some(a)
              a
            }
          }
          arr.push((wname, pos, end))
          return Some(entry)
        }
        None => ()
      }
    None => ()
  }
  None
}

///|
pub fn[T] Router::match_route(
  self : Router[T],
  meth : @http.Method,
  path : StringView,
) -> RouteMatch[T]? raise @url.UrlError {
  let end = effective_path_end(path)
  if end < 0 {
    return None
  }
  let start_pos = if end <= 1 { end + 1 } else { 1 }
  let raw_params : Ref[Array[(String, Int32, Int32)]?] = { val: None, }
  match match_node_cursor(self.root, meth, path, start_pos, end, raw_params) {
    None => None
    Some(entry) => {
      let decoded_params : Array[(String, String)] = match raw_params.val {
        None => []
        Some(captured) => {
          let out : Array[(String, String)] = Array(capacity=captured.length())
          for item in captured {
            let decoded = @url.percent_decode(path[item.1:item.2])
            out.push((item.0, decoded))
          }
          out
        }
      }
      Some({
        value: entry.value,
        params: { values: decoded_params, },
        pattern: entry.pattern,
      })
    }
  }
}

///|
fn[T] collect_methods_cursor(
  node : RouteNode[T],
  path : StringView,
  pos : Int32,
  end : Int32,
  out : Array[@http.Method],
) -> Unit {
  if pos > end {
    node.handlers.each((m, _) => if !out.contains(m) { out.push(m) })
    return
  }
  let mut slash = pos
  while slash < end && path.code_unit_at(slash) != '/' {
    slash = slash + 1
  }
  let next_pos = if slash < end { slash + 1 } else { end + 1 }
  match node.static_children.find_slice(path, pos, slash) {
    Some(child) => collect_methods_cursor(child, path, next_pos, end, out)
    None => ()
  }
  if slash > pos {
    match node.param_child {
      Some((_, child)) =>
        collect_methods_cursor(child, path, next_pos, end, out)
      None => ()
    }
  }
  match node.wildcard_child {
    Some((_, child)) =>
      child.handlers.each((m, _) => if !out.contains(m) { out.push(m) })
    None => ()
  }
}

///|
pub fn[T] Router::allowed_methods(
  self : Router[T],
  path : StringView,
) -> Array[@http.Method] {
  let end = effective_path_end(path)
  if end < 0 {
    return []
  }
  let start_pos = if end <= 1 { end + 1 } else { 1 }
  let out : Array[@http.Method] = []
  collect_methods_cursor(self.root, path, start_pos, end, out)
  if !out.is_empty() {
    if out.contains(@http.Method::Get) && !out.contains(@http.Method::Head) {
      out.push(@http.Method::Head)
    }
    if !out.contains(@http.Method::Options) {
      out.push(@http.Method::Options)
    }
  }
  out
}

///|
pub fn[T] Router::routes(self : Router[T]) -> Array[(@http.Method, String)] {
  self.registered.copy()
}