///|
/// Pure MoonBit RE2-compatible Regular Expression Engine (Thompson NFA)
/// for CUE `=~` / `!~` string constraints and pattern matching.
///
/// Linear-time O(N*M) guaranteed (no catastrophic backtracking), zero external
/// dependencies, works identically across native, wasm, and js backends.

///|
priv enum CharClassItem {
  Single(Char)
  Range(Char, Char)
  Digit // \d
  NonDigit // \D
  Word // \w
  NonWord // \W
  Space // \s
  NonSpace // \S
}

///|
priv enum CharMatcher {
  AnyChar // . (matches any char except '\n')
  Literal(Char)
  Class(Bool, Array[CharClassItem]) // (negated, items)
}

///|
fn CharMatcher::matches(self : CharMatcher, ch : Char) -> Bool {
  match self {
    AnyChar => ch != '\n'
    Literal(c) => ch == c
    Class(negated, items) => {
      let mut hit = false
      for item in items {
        let matched = match item {
          Single(c) => ch == c
          Range(lo, hi) => ch >= lo && ch <= hi
          Digit => ch >= '0' && ch <= '9'
          NonDigit => !(ch >= '0' && ch <= '9')
          Word =>
            (ch >= 'a' && ch <= 'z') ||
            (ch >= 'A' && ch <= 'Z') ||
            (ch >= '0' && ch <= '9') ||
            ch == '_'
          NonWord =>
            !((ch >= 'a' && ch <= 'z') ||
            (ch >= 'A' && ch <= 'Z') ||
            (ch >= '0' && ch <= '9') ||
            ch == '_')
          Space =>
            ch == ' ' ||
            ch == '\t' ||
            ch == '\n' ||
            ch == '\r' ||
            ch == '\u{000C}'
          NonSpace =>
            !(ch == ' ' ||
            ch == '\t' ||
            ch == '\n' ||
            ch == '\r' ||
            ch == '\u{000C}')
        }
        if matched {
          hit = true
          break
        }
      }
      if negated {
        !hit
      } else {
        hit
      }
    }
  }
}

///|
priv enum RegexNode {
  Empty
  Matcher(CharMatcher)
  AnchorStart // ^ or \A
  AnchorEnd // $ or \z
  WordBoundary(Bool) // \b (true) or \B (false)
  Seq(Array[RegexNode])
  Alt(RegexNode, RegexNode)
  Repeat(RegexNode, Int32, Int32?) // node, min, max (None = unbounded)
}

///|
priv struct RegexParser {
  chars : Array[Char]
  mut pos : Int32
}

///|
fn RegexParser::new(pattern : String) -> RegexParser {
  { chars: pattern.to_array(), pos: 0, }
}

///|
fn RegexParser::eof(self : RegexParser) -> Bool {
  self.pos >= self.chars.length()
}

///|
fn RegexParser::peek(self : RegexParser) -> Char? {
  if self.pos < self.chars.length() {
    Some(self.chars[self.pos])
  } else {
    None
  }
}

///|
fn RegexParser::advance(self : RegexParser) -> Char? {
  if self.pos < self.chars.length() {
    let ch = self.chars[self.pos]
    self.pos += 1
    Some(ch)
  } else {
    None
  }
}

///|
fn RegexParser::parse_alt(self : RegexParser) -> RegexNode raise CueError {
  let mut left = self.parse_seq()
  while self.peek() == Some('|') {
    ignore(self.advance())
    let right = self.parse_seq()
    left = Alt(left, right)
  }
  left
}

///|
fn RegexParser::parse_seq(self : RegexParser) -> RegexNode raise CueError {
  let nodes : Array[RegexNode] = []
  while !self.eof() {
    match self.peek() {
      Some('|') | Some(')') => break
      _ => nodes.push(self.parse_quantified())
    }
  }
  match nodes.length() {
    0 => Empty
    1 => nodes[0]
    _ => Seq(nodes)
  }
}

///|
fn RegexParser::parse_quantified(
  self : RegexParser,
) -> RegexNode raise CueError {
  let mut node = self.parse_atom()
  while !self.eof() {
    match self.peek() {
      Some('*') => {
        ignore(self.advance())
        if self.peek() == Some('?') {
          ignore(self.advance())
        }
        node = Repeat(node, 0, None)
      }
      Some('+') => {
        ignore(self.advance())
        if self.peek() == Some('?') {
          ignore(self.advance())
        }
        node = Repeat(node, 1, None)
      }
      Some('?') => {
        ignore(self.advance())
        if self.peek() == Some('?') {
          ignore(self.advance())
        }
        node = Repeat(node, 0, Some(1))
      }
      Some('{') => {
        let saved = self.pos
        ignore(self.advance())
        match self.try_parse_brace_quantifier() {
          Some((lo, hi)) => {
            if self.peek() == Some('?') {
              ignore(self.advance())
            }
            node = Repeat(node, lo, hi)
          }
          None => {
            self.pos = saved
            break
          }
        }
      }
      _ => break
    }
  }
  node
}

///|
fn RegexParser::try_parse_brace_quantifier(
  self : RegexParser,
) -> (Int32, Int32?)? raise CueError {
  let lo_opt = self.parse_uint()
  match lo_opt {
    None => None
    Some(lo) =>
      match self.peek() {
        Some('}') => {
          ignore(self.advance())
          Some((lo, Some(lo)))
        }
        Some(',') => {
          ignore(self.advance())
          if self.peek() == Some('}') {
            ignore(self.advance())
            Some((lo, None))
          } else {
            match self.parse_uint() {
              Some(hi) =>
                if self.peek() == Some('}') {
                  ignore(self.advance())
                  if hi < lo {
                    raise CueError::new(
                      RegexError,
                      "invalid repeat range {\{lo},\{hi}}",
                    )
                  }
                  Some((lo, Some(hi)))
                } else {
                  None
                }
              None => None
            }
          }
        }
        _ => None
      }
  }
}

///|
fn RegexParser::parse_uint(self : RegexParser) -> Int32? {
  let mut v = 0
  let mut count = 0
  while !self.eof() {
    match self.peek() {
      Some(c) if c >= '0' && c <= '9' => {
        ignore(self.advance())
        v = v * 10 + (c.to_int() - '0'.to_int())
        count += 1
      }
      _ => break
    }
  }
  if count == 0 {
    None
  } else {
    Some(v)
  }
}

///|
fn RegexParser::parse_atom(self : RegexParser) -> RegexNode raise CueError {
  match self.advance() {
    None => Empty
    Some('.') => Matcher(AnyChar)
    Some('^') => AnchorStart
    Some('$') => AnchorEnd
    Some('(') => {
      // Support `(?:...)` non-capturing and simple flags `(?i)`? Handle `(?:...)` cleanly
      if self.peek() == Some('?') {
        ignore(self.advance())
        if self.peek() == Some(':') {
          ignore(self.advance())
        } else {
          // Skip unknown inline flag prefix up to ':' or ')'
          while !self.eof() &&
                self.peek() != Some(':') &&
                self.peek() != Some(')') {
            ignore(self.advance())
          }
          if self.peek() == Some(':') {
            ignore(self.advance())
          }
        }
      }
      let inner = self.parse_alt()
      if self.advance() != Some(')') {
        raise CueError::new(RegexError, "unclosed '(' in regular expression")
      }
      inner
    }
    Some('[') => Matcher(self.parse_char_class())
    Some('\\') => self.parse_escape()
    Some('*') | Some('+') | Some('?') =>
      raise CueError::new(RegexError, "unexpected quantifier without atom")
    Some(c) => Matcher(Literal(c))
  }
}

///|
fn RegexParser::parse_escape(self : RegexParser) -> RegexNode raise CueError {
  match self.advance() {
    None =>
      raise CueError::new(
        RegexError,
        "trailing backslash in regular expression",
      )
    Some('d') => Matcher(Class(false, [Digit]))
    Some('D') => Matcher(Class(false, [NonDigit]))
    Some('w') => Matcher(Class(false, [Word]))
    Some('W') => Matcher(Class(false, [NonWord]))
    Some('s') => Matcher(Class(false, [Space]))
    Some('S') => Matcher(Class(false, [NonSpace]))
    Some('A') => AnchorStart
    Some('z') | Some('Z') => AnchorEnd
    Some('b') => WordBoundary(true)
    Some('B') => WordBoundary(false)
    Some('n') => Matcher(Literal('\n'))
    Some('r') => Matcher(Literal('\r'))
    Some('t') => Matcher(Literal('\t'))
    Some('f') => Matcher(Literal('\u{000C}'))
    Some(c) => Matcher(Literal(c))
  }
}

///|
fn RegexParser::parse_class_char(
  self : RegexParser,
) -> CharClassItem raise CueError {
  match self.advance() {
    None => raise CueError::new(RegexError, "unterminated character class '['")
    Some('\\') =>
      match self.advance() {
        None =>
          raise CueError::new(RegexError, "unterminated escape in char class")
        Some('d') => Digit
        Some('D') => NonDigit
        Some('w') => Word
        Some('W') => NonWord
        Some('s') => Space
        Some('S') => NonSpace
        Some('n') => Single('\n')
        Some('r') => Single('\r')
        Some('t') => Single('\t')
        Some(c) => Single(c)
      }
    Some(c) => Single(c)
  }
}

///|
fn RegexParser::parse_char_class(
  self : RegexParser,
) -> CharMatcher raise CueError {
  let negated = if self.peek() == Some('^') {
    ignore(self.advance())
    true
  } else {
    false
  }
  let items : Array[CharClassItem] = []
  let mut first = true
  while !self.eof() {
    if !first && self.peek() == Some(']') {
      ignore(self.advance())
      return Class(negated, items)
    }
    first = false
    let item = self.parse_class_char()
    match item {
      Single(lo) =>
        if self.peek() == Some('-') &&
          self.pos + 1 < self.chars.length() &&
          self.chars[self.pos + 1] != ']' {
          ignore(self.advance()) // consume '-'
          let hi_item = self.parse_class_char()
          match hi_item {
            Single(hi) =>
              if hi < lo {
                raise CueError::new(
                  RegexError,
                  "invalid character class range '\{lo}-\{hi}'",
                )
              } else {
                items.push(Range(lo, hi))
              }
            _ => {
              items.push(Single(lo))
              items.push(Single('-'))
              items.push(hi_item)
            }
          }
        } else {
          items.push(Single(lo))
        }
      _ => items.push(item)
    }
  }
  raise CueError::new(RegexError, "unterminated character class '['")
}

///|
/// NFA instruction for Thompson simulation.
priv enum NfaState {
  Match
  Consume(CharMatcher, Int32) // matcher -> next state
  Split(Int32, Int32) // epsilon branch
  Jump(Int32) // epsilon jump
  AssertStart(Int32) // ^ -> next
  AssertEnd(Int32) // $ -> next
  AssertWordBound(Bool, Int32) // \b / \B -> next
}

///|
priv struct NfaBuilder {
  states : Array[NfaState]
}

///|
fn NfaBuilder::new() -> NfaBuilder {
  { states: [], }
}

///|
fn NfaBuilder::emit(self : NfaBuilder, st : NfaState) -> Int32 {
  let id = self.states.length()
  self.states.push(st)
  id
}

///|
fn NfaBuilder::compile(
  self : NfaBuilder,
  node : RegexNode,
  next : Int32,
) -> Int32 {
  match node {
    Empty => next
    Matcher(m) => self.emit(Consume(m, next))
    AnchorStart => self.emit(AssertStart(next))
    AnchorEnd => self.emit(AssertEnd(next))
    WordBoundary(pos) => self.emit(AssertWordBound(pos, next))
    Seq(nodes) => {
      let mut target = next
      for i = nodes.length() - 1; i >= 0; i = i - 1 {
        target = self.compile(nodes[i], target)
      }
      target
    }
    Alt(a, b) => {
      let s_a = self.compile(a, next)
      let s_b = self.compile(b, next)
      self.emit(Split(s_a, s_b))
    }
    Repeat(inner, lo, hi_opt) => {
      // Build tail: either unbounded `*` or up to `hi - lo` optional copies
      let mut tail = next
      match hi_opt {
        None => {
          let split_id = self.emit(Jump(0)) // placeholder
          let body_start = self.compile(inner, split_id)
          self.states[split_id] = Split(body_start, next)
          tail = split_id
        }
        Some(hi) => {
          let extra = hi - lo
          for _i = 0; _i < extra; _i = _i + 1 {
            let body = self.compile(inner, tail)
            tail = self.emit(Split(body, next))
          }
        }
      }
      // Prepend `lo` mandatory copies
      let mut head = tail
      for _i = 0; _i < lo; _i = _i + 1 {
        head = self.compile(inner, head)
      }
      head
    }
  }
}

///|
/// Compiled regular expression for CUE `=~` / `!~`.
pub struct CompiledRegex {
  pattern : String
  priv states : Array[NfaState]
  priv start : Int32
}

///|
pub fn compile_regex(pattern : String) -> CompiledRegex raise CueError {
  let parser = RegexParser::new(pattern)
  let ast = parser.parse_alt()
  if !parser.eof() {
    raise CueError::new(
      RegexError,
      "unexpected ')' in regular expression '\{pattern}'",
    )
  }
  let builder = NfaBuilder::new()
  let accept = builder.emit(Match)
  let start = builder.compile(ast, accept)
  { pattern, states: builder.states, start, }
}

///|
fn is_word_char(ch : Char) -> Bool {
  (ch >= 'a' && ch <= 'z') ||
  (ch >= 'A' && ch <= 'Z') ||
  (ch >= '0' && ch <= '9') ||
  ch == '_'
}

///|
fn is_word_boundary(chars : Array[Char], idx : Int32) -> Bool {
  let left_word = idx > 0 && is_word_char(chars[idx - 1])
  let right_word = idx < chars.length() && is_word_char(chars[idx])
  left_word != right_word
}

///|
fn CompiledRegex::add_closure(
  self : CompiledRegex,
  state_id : Int32,
  chars : Array[Char],
  pos : Int32,
  visited : Array[Bool],
  out : Array[Int32],
) -> Unit {
  if visited[state_id] {
    return
  }
  visited[state_id] = true
  match self.states[state_id] {
    Jump(next) => self.add_closure(next, chars, pos, visited, out)
    Split(a, b) => {
      self.add_closure(a, chars, pos, visited, out)
      self.add_closure(b, chars, pos, visited, out)
    }
    AssertStart(next) =>
      if pos == 0 {
        self.add_closure(next, chars, pos, visited, out)
      }
    AssertEnd(next) =>
      if pos == chars.length() {
        self.add_closure(next, chars, pos, visited, out)
      }
    AssertWordBound(want, next) =>
      if is_word_boundary(chars, pos) == want {
        self.add_closure(next, chars, pos, visited, out)
      }
    _ => out.push(state_id)
  }
}

///|
/// Matches `text` using Go RE2 `MatchString` semantics (unanchored search unless
/// `^` / `$` anchors are present in the pattern).
pub fn CompiledRegex::is_match(self : CompiledRegex, text : String) -> Bool {
  let chars = text.to_array()
  let n_states = self.states.length()
  let mut current : Array[Int32] = []
  let mut visited = Array::make(n_states, false)
  self.add_closure(self.start, chars, 0, visited, current)

  for pos = 0; pos <= chars.length(); pos = pos + 1 {
    // Check if any active state is accepting
    for st in current {
      match self.states[st] {
        Match => return true
        _ => ()
      }
    }
    if pos == chars.length() {
      break
    }
    let ch = chars[pos]
    let next_states : Array[Int32] = []
    visited = Array::make(n_states, false)
    for st in current {
      match self.states[st] {
        Consume(matcher, target) =>
          if matcher.matches(ch) {
            self.add_closure(target, chars, pos + 1, visited, next_states)
          }
        _ => ()
      }
    }
    // Unanchored search: allow a fresh match starting at `pos + 1`
    self.add_closure(self.start, chars, pos + 1, visited, next_states)
    current = next_states
  }
  false
}

///|
/// Convenience helper: compile and match regex against text.
pub fn regex_match(pattern : String, text : String) -> Bool raise CueError {
  let re = compile_regex(pattern)
  re.is_match(text)
}