///|
/// 将 ASCII 小写字母转为大写(用于字符区间大小写不敏感匹配)。
fn to_ascii_upper(c : Char) -> Char {
  if c >= 'a' && c <= 'z' {
    Int32::unsafe_to_char(c.to_int() - 32)
  } else {
    c
  }
}

///|
/// 判断单个字符是否命中字符类。
fn match_char_class(
  negated : Bool,
  items : Array[CharClassItem],
  ch : Char,
  case_sensitive : Bool,
) -> Bool {
  let mut matched = false
  let ch_code = ch.to_int()
  let ch_lo = fold_ascii_char(ch).to_int()
  let ch_hi = to_ascii_upper(ch).to_int()
  for item in items {
    match item {
      Single(target) =>
        if chars_equal(ch, target, case_sensitive) {
          matched = true
          break
        }
      Range(start, end) => {
        let lo = start.to_int()
        let hi = end.to_int()
        if case_sensitive {
          if ch_code >= lo && ch_code <= hi {
            matched = true
            break
          }
        } else if (ch_code >= lo && ch_code <= hi) ||
          (ch_lo >= lo && ch_lo <= hi) ||
          (ch_hi >= lo && ch_hi <= hi) {
          matched = true
          break
        }
      }
    }
  }
  if negated {
    !matched
  } else {
    matched
  }
}

///|
/// 使用滚动布尔动态规划(Thompson NFA 前沿)对单段模式进行线性空间、无回溯匹配。
/// 最坏时间复杂度严格为 O(|atoms| * |text|),免疫指数级 ReDoS 回溯灾难。
pub fn match_segment_atoms(
  atoms : Array[SegmentAtom],
  text : String,
  case_sensitive~ : Bool = true,
) -> Bool {
  let m = atoms.length()
  let chars = text.to_array()
  let mut dp = Array::make(m + 1, false)
  dp[0] = true
  for j = 0; j < m; j = j + 1 {
    if dp[j] && atoms[j] == AnySeq {
      dp[j + 1] = true
    }
  }
  for c in chars {
    let next = Array::make(m + 1, false)
    for j = 0; j < m; j = j + 1 {
      if !dp[j] {
        continue
      }
      match atoms[j] {
        AnySeq => next[j] = true
        AnyChar => next[j + 1] = true
        Literal(expected) =>
          if chars_equal(c, expected, case_sensitive) {
            next[j + 1] = true
          }
        CharClass(negated, items) =>
          if match_char_class(negated, items, c, case_sensitive) {
            next[j + 1] = true
          }
      }
    }
    for j = 0; j < m; j = j + 1 {
      if next[j] && atoms[j] == AnySeq {
        next[j + 1] = true
      }
    }
    dp = next
  }
  dp[m]
}

///|
/// 使用滚动布尔动态规划对多段路径模式(含任意数量 `**`)进行无回溯匹配。
/// 最坏时间复杂度为 O(|pat_segs| * |path_segs| * 单个段匹配耗时)。
pub fn match_path_segments(
  pat_segs : Array[PatternSegment],
  path_segs : Array[String],
  case_sensitive~ : Bool = true,
) -> Bool {
  let m = pat_segs.length()
  let mut dp = Array::make(m + 1, false)
  dp[0] = true
  for j = 0; j < m; j = j + 1 {
    if dp[j] && pat_segs[j] == GlobStar {
      dp[j + 1] = true
    }
  }
  for seg in path_segs {
    let next = Array::make(m + 1, false)
    for j = 0; j < m; j = j + 1 {
      if !dp[j] {
        continue
      }
      match pat_segs[j] {
        GlobStar => next[j] = true
        Segment(atoms) =>
          if match_segment_atoms(atoms, seg, case_sensitive~) {
            next[j + 1] = true
          }
      }
    }
    for j = 0; j < m; j = j + 1 {
      if next[j] && pat_segs[j] == GlobStar {
        next[j + 1] = true
      }
    }
    dp = next
  }
  dp[m]
}

///|
/// 在已相对化至规则作用域的路径上判断单条规则是否命中。
pub fn CompiledRule::matches_relative(
  self : CompiledRule,
  rel_path : NormalizedPath,
  case_sensitive~ : Bool = true,
) -> Bool {
  if self.dir_only && !rel_path.is_dir {
    return false
  }
  if self.anchored {
    return match_path_segments(
      self.segments,
      rel_path.segments,
      case_sensitive~,
    )
  }
  if self.segments.length() == 1 {
    match self.segments[0] {
      GlobStar => true
      Segment(atoms) => {
        let last = rel_path.segments[rel_path.segments.length() - 1]
        match_segment_atoms(atoms, last, case_sensitive~)
      }
    }
  } else {
    match_path_segments(self.segments, rel_path.segments, case_sensitive~)
  }
}

///|
/// 在仓库完整路径上判断单条规则(含作用域过滤)是否命中。
pub fn CompiledRule::matches(
  self : CompiledRule,
  path : NormalizedPath,
  case_sensitive~ : Bool = true,
) -> Bool {
  match path.relative_to(self.scope_segments, case_sensitive~) {
    None => false
    Some(rel) => self.matches_relative(rel, case_sensitive~)
  }
}

///|
/// 单行 Glob 模式快速匹配入口:适合无需多文件级联的轻量路径匹配场景。
pub fn glob_match(
  pattern : String,
  path : String,
  is_dir~ : Bool = false,
  case_sensitive~ : Bool = true,
) -> Result[Bool, String] {
  let rule = match compile_rule(pattern) {
    Ok(r) => r
    Err(e) => return Err("invalid pattern: " + e.message())
  }
  let normalized = match normalize_path(path, is_dir~) {
    Ok(p) => p
    Err(e) => return Err("invalid path: " + e.message())
  }
  Ok(rule.matches(normalized, case_sensitive~))
}