///|
priv struct UriTemplateVar {
  name : String
  exploded : Bool
}

///|
priv enum UriTemplatePart {
  Literal(String)
  Expr(operator~ : String, vars~ : Array[UriTemplateVar])
}

///|
/// Pure MoonBit RFC 6570 URI Template engine (zero regex, ReDoS-safe).
/// Supports operators `""`, `+`, `#`, `.`, `/`, `;`, `?`, `&` and explode modifier `*`.
pub struct UriTemplate {
  priv raw : String
  priv parts : Array[UriTemplatePart]
  priv names : Array[String]
}

///|
/// Returns true if `s` contains an RFC 6570 `{...}` template expression.
pub fn UriTemplate::is_template(s : String) -> Bool {
  let mut has_open = false
  for ch in s {
    if ch == '{' {
      has_open = true
    } else if ch == '}' && has_open {
      return true
    }
  }
  false
}

///|
fn is_valid_var_name(name : String) -> Bool {
  if name.is_empty() {
    return false
  }
  for ch in name {
    let ok = (ch >= 'a' && ch <= 'z') ||
      (ch >= 'A' && ch <= 'Z') ||
      (ch >= '0' && ch <= '9') ||
      ch == '_' ||
      ch == '.'
    if !ok {
      return false
    }
  }
  true
}

///|
/// Parses an RFC 6570 URI template string.
pub fn UriTemplate::parse(
  template : String,
) -> UriTemplate raise McpProtocolError {
  let chars = template.to_array()
  let len = chars.length()
  let parts : Array[UriTemplatePart] = []
  let names : Array[String] = []
  let lit = StringBuilder()
  let mut i = 0
  while i < len {
    let ch = chars[i]
    if ch == '{' {
      let lit_str = lit.to_string()
      if !lit_str.is_empty() {
        parts.push(Literal(lit_str))
        lit.reset()
      }
      let start = i + 1
      let mut close = -1
      let mut j = start
      while j < len {
        if chars[j] == '}' {
          close = j
          break
        }
        if chars[j] == '{' {
          raise McpProtocolError::invalid_params(
            "Nested '{' in URI template: \{template}",
          )
        }
        j = j + 1
      }
      if close < 0 {
        raise McpProtocolError::invalid_params(
          "Unclosed '{' in URI template: \{template}",
        )
      }
      if close == start {
        raise McpProtocolError::invalid_params(
          "Empty expression '{}' in URI template: \{template}",
        )
      }
      let mut expr_start = start
      let first = chars[start]
      let operator = match first {
        '+' => {
          expr_start = start + 1
          "+"
        }
        '#' => {
          expr_start = start + 1
          "#"
        }
        '.' => {
          expr_start = start + 1
          "."
        }
        '/' => {
          expr_start = start + 1
          "/"
        }
        ';' => {
          expr_start = start + 1
          ";"
        }
        '?' => {
          expr_start = start + 1
          "?"
        }
        '&' => {
          expr_start = start + 1
          "&"
        }
        _ => ""
      }
      let expr_sb = StringBuilder()
      for k = expr_start; k < close; k = k + 1 {
        expr_sb.write_char(chars[k])
      }
      let expr_body = expr_sb.to_string()
      if expr_body.is_empty() {
        raise McpProtocolError::invalid_params(
          "Missing variable name in URI template: \{template}",
        )
      }
      let vars : Array[UriTemplateVar] = []
      for raw_v in expr_body.split(",") {
        let v = raw_v.to_owned()
        let (vname, exploded) = if v.has_suffix("*") && v.length() > 1 {
          (v[:v.length() - 1].to_owned(), true)
        } else {
          (v, false)
        }
        if !is_valid_var_name(vname) {
          raise McpProtocolError::invalid_params(
            "Invalid variable '\{vname}' in URI template: \{template}",
          )
        }
        vars.push({ name: vname, exploded, })
        if !names.contains(vname) {
          names.push(vname)
        }
      }
      parts.push(Expr(operator~, vars~))
      i = close + 1
    } else if ch == '}' {
      raise McpProtocolError::invalid_params(
        "Unmatched '}' in URI template: \{template}",
      )
    } else {
      lit.write_char(ch)
      i = i + 1
    }
  }
  let tail = lit.to_string()
  if !tail.is_empty() {
    parts.push(Literal(tail))
  }
  { raw: template, parts, names, }
}

///|
pub fn UriTemplate::to_string(self : UriTemplate) -> String {
  self.raw
}

///|
pub fn UriTemplate::variable_names(self : UriTemplate) -> Array[String] {
  self.names.copy()
}

///|
fn is_reserved_or_unreserved(ch : Char) -> Bool {
  (ch >= 'a' && ch <= 'z') ||
  (ch >= 'A' && ch <= 'Z') ||
  (ch >= '0' && ch <= '9') ||
  ch == '-' ||
  ch == '.' ||
  ch == '_' ||
  ch == '~' ||
  ch == ':' ||
  ch == '/' ||
  ch == '?' ||
  ch == '#' ||
  ch == '[' ||
  ch == ']' ||
  ch == '@' ||
  ch == '!' ||
  ch == '$' ||
  ch == '&' ||
  ch == '\'' ||
  ch == '(' ||
  ch == ')' ||
  ch == '*' ||
  ch == '+' ||
  ch == ',' ||
  ch == ';' ||
  ch == '='
}

///|
fn is_hex_digit(ch : Char) -> Bool {
  (ch >= '0' && ch <= '9') ||
  (ch >= 'a' && ch <= 'f') ||
  (ch >= 'A' && ch <= 'F')
}

///|
fn encode_reserved(value : String) -> String {
  let chars = value.to_array()
  let len = chars.length()
  let sb = StringBuilder()
  let mut i = 0
  while i < len {
    let ch = chars[i]
    if ch == '%' &&
      i + 2 < len &&
      is_hex_digit(chars[i + 1]) &&
      is_hex_digit(chars[i + 2]) {
      sb.write_char(ch)
      sb.write_char(chars[i + 1])
      sb.write_char(chars[i + 2])
      i = i + 3
      continue
    }
    if is_reserved_or_unreserved(ch) {
      sb.write_char(ch)
    } else {
      sb.write_string(@url.percent_encode(ch.to_string()))
    }
    i = i + 1
  }
  sb.to_string()
}

///|
fn encode_for_operator(operator : String, value : String) -> String {
  if operator == "+" || operator == "#" {
    encode_reserved(value)
  } else {
    @url.percent_encode(value)
  }
}

///|
fn decode_segment(raw : String) -> String {
  @url.percent_decode(raw) catch {
    _ => raw
  }
}

///|
/// Expands the template using the supplied variable map.
pub fn UriTemplate::expand(
  self : UriTemplate,
  vars : Map[String, String],
) -> String {
  let sb = StringBuilder()
  for part in self.parts {
    match part {
      Literal(s) => sb.write_string(s)
      Expr(operator~, vars=expr_vars) => {
        let prefix = if operator == "+" { "" } else { operator }
        let sep = match operator {
          "." => "."
          "/" => "/"
          ";" => ";"
          "?" | "&" => "&"
          _ => ","
        }
        let named = operator == ";" || operator == "?" || operator == "&"
        let mut first = true
        for v in expr_vars {
          match vars.get(v.name) {
            Some(val) => {
              if first {
                sb.write_string(prefix)
                first = false
              } else {
                sb.write_string(sep)
              }
              if named {
                sb.write_string(v.name)
                if operator == ";" && val.is_empty() {
                  ()
                } else {
                  sb.write_char('=')
                  sb.write_string(encode_for_operator(operator, val))
                }
              } else {
                sb.write_string(encode_for_operator(operator, val))
              }
            }
            None => ()
          }
        }
      }
    }
  }
  sb.to_string()
}

///|
fn starts_with_at(
  haystack : Array[Char],
  pos : Int32,
  needle : Array[Char],
) -> Bool {
  if pos + needle.length() > haystack.length() {
    return false
  }
  for i = 0; i < needle.length(); i = i + 1 {
    if haystack[pos + i] != needle[i] {
      return false
    }
  }
  true
}

///|
fn find_subarray(
  haystack : Array[Char],
  from : Int32,
  needle : Array[Char],
) -> Int32? {
  if needle.is_empty() {
    return Some(from)
  }
  let limit = haystack.length() - needle.length()
  for i = from; i <= limit; i = i + 1 {
    if starts_with_at(haystack, i, needle) {
      return Some(i)
    }
  }
  None
}

///|
fn slice_chars_to_string(
  chars : Array[Char],
  start : Int32,
  end : Int32,
) -> String {
  let sb = StringBuilder()
  for i = start; i < end; i = i + 1 {
    sb.write_char(chars[i])
  }
  sb.to_string()
}

///|
/// Matches a concrete URI against this RFC 6570 template, returning extracted
/// variable bindings on success or `None` if it does not match.
pub fn UriTemplate::match_uri(
  self : UriTemplate,
  uri : String,
) -> Map[String, String]? {
  let chars = uri.to_array()
  let len = chars.length()
  let result : Map[String, String] = Map([])
  let mut pos = 0
  let num_parts = self.parts.length()
  for idx = 0; idx < num_parts; idx = idx + 1 {
    match self.parts[idx] {
      Literal(lit) => {
        let needle = lit.to_array()
        if !starts_with_at(chars, pos, needle) {
          return None
        }
        pos = pos + needle.length()
      }
      Expr(operator~, vars~) => {
        // Find end boundary of this expression by looking ahead to next Literal or next
        // prefix-delimited Expression (e.g. `{id}{?format}` or `{+path}{#frag}`).
        let next_lit : Array[Char]? = if idx + 1 < num_parts {
          match self.parts[idx + 1] {
            Literal(s) => Some(s.to_array())
            _ => None
          }
        } else {
          None
        }
        let next_expr_delim : Char? = if idx + 1 < num_parts {
          match self.parts[idx + 1] {
            Expr(operator=op, ..) =>
              match op {
                "?" => Some('?')
                "&" => Some('&')
                "#" => Some('#')
                "/" => Some('/')
                ";" => Some(';')
                "." => Some('.')
                _ => None
              }
            _ => None
          }
        } else {
          None
        }
        // Query operators (? / &) are optional when absent
        if operator == "?" || operator == "&" {
          let expected_char = if operator == "?" { '?' } else { '&' }
          if pos >= len || chars[pos] != expected_char {
            // Optional query expression omitted
            continue
          }
          let end_pos = match next_lit {
            Some(nl) =>
              match find_subarray(chars, pos + 1, nl) {
                Some(found) => found
                None => return None
              }
            None => len
          }
          let raw_query = slice_chars_to_string(chars, pos + 1, end_pos)
          let allowed : Map[String, Bool] = Map([])
          for v in vars {
            allowed[v.name] = true
          }
          for pair in raw_query.split("&") {
            let p = pair.to_owned()
            if p.is_empty() {
              continue
            }
            match p.find("=") {
              Some(eq) => {
                let k = p[:eq].to_owned()
                let v = p[eq + 1:].to_owned()
                if allowed.contains(k) {
                  result[k] = decode_segment(v)
                }
              }
              None => if allowed.contains(p) { result[p] = "" }
            }
          }
          pos = end_pos
          continue
        }

        // Prefix-delimited operators: #, ., /, ;
        if operator == "#" ||
          operator == "." ||
          operator == "/" ||
          operator == ";" {
          let prefix_char = match operator {
            "#" => '#'
            "." => '.'
            "/" => '/'
            _ => ';'
          }
          if pos >= len || chars[pos] != prefix_char {
            return None
          }
          pos = pos + 1
        }

        let end_pos = match next_lit {
          Some(nl) =>
            match find_subarray(chars, pos, nl) {
              Some(found) => found
              None => return None
            }
          None =>
            match next_expr_delim {
              Some(dch) =>
                match find_subarray(chars, pos, [dch]) {
                  Some(found) => found
                  None => len
                }
              None => len
            }
        }
        let captured = slice_chars_to_string(chars, pos, end_pos)
        if captured.is_empty() {
          return None
        }

        // For simple expansion (operator == "") or dot/semicolon with single var, disallow '/'
        if operator == "" && vars.length() == 1 && !vars[0].exploded {
          if captured.contains("/") {
            return None
          }
          result[vars[0].name] = decode_segment(captured)
        } else if operator == "+" || operator == "#" {
          if vars.length() == 1 {
            result[vars[0].name] = decode_segment(captured)
          } else {
            let segs = captured.split(",").map(s => s.to_owned()).collect()
            if segs.length() != vars.length() {
              return None
            }
            for i = 0; i < vars.length(); i = i + 1 {
              result[vars[i].name] = decode_segment(segs[i])
            }
          }
        } else if operator == "/" {
          if vars.length() == 1 && vars[0].exploded {
            result[vars[0].name] = decode_segment(captured)
          } else {
            let segs = captured.split("/").map(s => s.to_owned()).collect()
            if segs.length() != vars.length() {
              return None
            }
            for i = 0; i < vars.length(); i = i + 1 {
              if segs[i].is_empty() {
                return None
              }
              result[vars[i].name] = decode_segment(segs[i])
            }
          }
        } else if operator == "." {
          let segs = captured.split(".").map(s => s.to_owned()).collect()
          if segs.length() != vars.length() {
            return None
          }
          for i = 0; i < vars.length(); i = i + 1 {
            if segs[i].is_empty() || segs[i].contains("/") {
              return None
            }
            result[vars[i].name] = decode_segment(segs[i])
          }
        } else if operator == ";" {
          let allowed : Map[String, Bool] = Map([])
          for v in vars {
            allowed[v.name] = true
          }
          for pair in captured.split(";") {
            let p = pair.to_owned()
            match p.find("=") {
              Some(eq) => {
                let k = p[:eq].to_owned()
                let v = p[eq + 1:].to_owned()
                if allowed.contains(k) {
                  result[k] = decode_segment(v)
                }
              }
              None => if allowed.contains(p) { result[p] = "" }
            }
          }
        } else {
          // Simple comma-separated multiple vars: {a,b}
          let segs = captured.split(",").map(s => s.to_owned()).collect()
          if segs.length() != vars.length() {
            return None
          }
          for i = 0; i < vars.length(); i = i + 1 {
            if segs[i].is_empty() || segs[i].contains("/") {
              return None
            }
            result[vars[i].name] = decode_segment(segs[i])
          }
        }
        pos = end_pos
      }
    }
  }
  if pos != len {
    return None
  }
  Some(result)
}