///|
/// Lexer for CUE source text with automatic comma insertion, raw/multiline strings,
/// SI numeric multipliers, and string interpolation scanning.
priv struct Lexer {
  chars : Array[Char]
  mut pos : Int32
  mut line : Int32
  mut col : Int32
  mut insert_comma : Bool
}

///|
fn Lexer::new(src : String) -> Lexer {
  { chars: src.to_array(), pos: 0, line: 1, col: 1, insert_comma: false, }
}

///|
fn Lexer::position(self : Lexer) -> Position {
  Position::new(self.pos, self.line, self.col)
}

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

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

///|
fn Lexer::peek_at(self : Lexer, delta : Int32) -> Char? {
  let idx = self.pos + delta
  if idx >= 0 && idx < self.chars.length() {
    Some(self.chars[idx])
  } else {
    None
  }
}

///|
fn Lexer::advance(self : Lexer) -> Char? {
  if self.pos >= self.chars.length() {
    return None
  }
  let ch = self.chars[self.pos]
  self.pos += 1
  if ch == '\n' {
    self.line += 1
    self.col = 1
  } else {
    self.col += 1
  }
  Some(ch)
}

///|
fn is_ident_start(ch : Char) -> Bool {
  (ch >= 'a' && ch <= 'z') ||
  (ch >= 'A' && ch <= 'Z') ||
  ch == '_' ||
  ch == '$' ||
  ch == '#'
}

///|
fn is_ident_continue(ch : Char) -> Bool {
  is_ident_start(ch) || (ch >= '0' && ch <= '9')
}

///|
fn is_digit(ch : Char) -> Bool {
  ch >= '0' && ch <= '9'
}

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

///|
fn hex_val(ch : Char) -> Int32 {
  if ch >= '0' && ch <= '9' {
    ch.to_int() - '0'.to_int()
  } else if ch >= 'a' && ch <= 'f' {
    ch.to_int() - 'a'.to_int() + 10
  } else {
    ch.to_int() - 'A'.to_int() + 10
  }
}

///|
/// Tokenize a CUE source string into a flat token stream ending with `Eof`.
pub fn tokenize(src : String) -> Array[Token] raise CueError {
  let lexer = Lexer::new(src)
  let tokens : Array[Token] = []
  while true {
    let tok = lexer.next_token()
    let is_eof = tok.kind == Eof
    tokens.push(tok)
    if is_eof {
      break
    }
  }
  tokens
}

///|
fn Lexer::next_token(self : Lexer) -> Token raise CueError {
  // Skip whitespace and comments, honoring automatic comma insertion on newline.
  while !self.eof() {
    match self.peek() {
      Some(' ') | Some('\t') | Some('\r') => ignore(self.advance())
      Some('\n') => {
        let start = self.position()
        ignore(self.advance())
        if self.insert_comma {
          self.insert_comma = false
          return Token::new(Comma, Span::new(start, self.position()))
        }
      }
      Some('/') =>
        if self.peek_at(1) == Some('/') {
          // Line comment: stop before '\n' so newline still triggers auto-comma!
          while !self.eof() && self.peek() != Some('\n') {
            ignore(self.advance())
          }
        } else {
          break
        }
      _ => break
    }
  }

  let start = self.position()
  if self.eof() {
    if self.insert_comma {
      self.insert_comma = false
      return Token::new(Comma, Span::new(start, start))
    }
    return Token::new(Eof, Span::new(start, start))
  }

  let ch = self.peek().unwrap()

  // Raw string / bytes: #"..."#, ##"""..."""##, #'...'#
  if ch == '#' {
    let mut hash_count = 0
    while self.peek_at(hash_count) == Some('#') {
      hash_count += 1
    }
    match self.peek_at(hash_count) {
      Some('"') | Some('\'') => {
        let tok = self.scan_string_or_bytes(hash_count)
        self.insert_comma = tok.kind.triggers_auto_comma()
        return tok
      }
      _ => ()
    }
  }

  // Regular or multiline string / bytes
  if ch == '"' || ch == '\'' {
    let tok = self.scan_string_or_bytes(0)
    self.insert_comma = tok.kind.triggers_auto_comma()
    return tok
  }

  // Bottom token `_|_`
  if ch == '_' && self.peek_at(1) == Some('|') && self.peek_at(2) == Some('_') {
    let after = self.peek_at(3)
    let is_boundary = match after {
      None => true
      Some(c) => !is_ident_continue(c)
    }
    if is_boundary {
      ignore(self.advance())
      ignore(self.advance())
      ignore(self.advance())
      let tok = Token::new(Bottom, Span::new(start, self.position()))
      self.insert_comma = true
      return tok
    }
  }

  // Numbers (starting with digit, or '.' followed by digit)
  if is_digit(ch) ||
    (
      ch == '.' &&
      (match self.peek_at(1) {
        Some(c) => is_digit(c)
        None => false
      })
    ) {
    let tok = self.scan_number()
    self.insert_comma = true
    return tok
  }

  // Identifiers and keywords (including #Def, _hidden, _#hiddenDef)
  if is_ident_start(ch) {
    let tok = self.scan_ident()
    self.insert_comma = tok.kind.triggers_auto_comma()
    return tok
  }

  // Operators & punctuation
  ignore(self.advance())
  let kind : TokenKind = match ch {
    '+' => Add
    '-' => Sub
    '*' => Mul
    '/' => Quo
    '&' =>
      if self.peek() == Some('&') {
        ignore(self.advance())
        Land
      } else {
        And
      }
    '|' =>
      if self.peek() == Some('|') {
        ignore(self.advance())
        Lor
      } else {
        Or
      }
    '=' =>
      if self.peek() == Some('=') {
        ignore(self.advance())
        Eq
      } else if self.peek() == Some('~') {
        ignore(self.advance())
        Match
      } else {
        Bind
      }
    '!' =>
      if self.peek() == Some('=') {
        ignore(self.advance())
        Neq
      } else if self.peek() == Some('~') {
        ignore(self.advance())
        NotMatch
      } else {
        Not
      }
    '<' =>
      if self.peek() == Some('=') {
        ignore(self.advance())
        Lte
      } else if self.peek() == Some('-') {
        ignore(self.advance())
        Arrow
      } else {
        Lt
      }
    '>' =>
      if self.peek() == Some('=') {
        ignore(self.advance())
        Gte
      } else {
        Gt
      }
    ':' =>
      if self.peek() == Some('=') {
        ignore(self.advance())
        Assign
      } else {
        Colon
      }
    ',' => Comma
    '?' => Question
    '(' => LParen
    ')' => RParen
    '{' => LBrace
    '}' => RBrace
    '[' => LBrack
    ']' => RBrack
    '.' =>
      if self.peek() == Some('.') && self.peek_at(1) == Some('.') {
        ignore(self.advance())
        ignore(self.advance())
        Ellipsis
      } else {
        Dot
      }
    _ =>
      raise CueError::new(
        LexError,
        "unexpected character '\{ch}'",
        span=Some(Span::new(start, self.position())),
      )
  }
  self.insert_comma = kind.triggers_auto_comma()
  Token::new(kind, Span::new(start, self.position()))
}

///|
fn Lexer::scan_ident(self : Lexer) -> Token raise CueError {
  let start = self.position()
  let buf = StringBuilder()
  // Allow leading `_#` or `#` or `_`
  while !self.eof() {
    match self.peek() {
      Some(c) if is_ident_continue(c) => {
        buf.write_char(c)
        ignore(self.advance())
      }
      _ => break
    }
  }
  let text = buf.to_string()
  if text == "#" || text == "_#" {
    raise CueError::new(
      LexError,
      "invalid definition identifier '\{text}'",
      span=Some(Span::new(start, self.position())),
    )
  }
  let kind : TokenKind = match text {
    "package" => Package
    "import" => Import
    "for" => For
    "in" => In
    "if" => If
    "let" => Let
    "null" => Null
    "true" => True
    "false" => False
    _ => Ident(text)
  }
  Token::new(kind, Span::new(start, self.position()))
}

///|
fn Lexer::scan_number(self : Lexer) -> Token raise CueError {
  let start = self.position()
  let raw = StringBuilder()
  let clean = StringBuilder()

  // Check hex / binary / octal prefix: 0x, 0b, 0o
  if self.peek() == Some('0') {
    match self.peek_at(1) {
      Some('x') | Some('X') => {
        raw.write_char(self.advance().unwrap())
        raw.write_char(self.advance().unwrap())
        let mut val : Int64 = 0L
        let mut digits = 0
        while !self.eof() {
          match self.peek() {
            Some('_') => raw.write_char(self.advance().unwrap())
            Some(c) if is_hex_digit(c) => {
              raw.write_char(self.advance().unwrap())
              val = val * 16L + hex_val(c).to_int64()
              digits += 1
            }
            _ => break
          }
        }
        if digits == 0 {
          raise CueError::new(
            LexError,
            "invalid hexadecimal literal",
            span=Some(Span::new(start, self.position())),
          )
        }
        return Token::new(
          IntLit(val, raw.to_string()),
          Span::new(start, self.position()),
        )
      }
      Some('b') | Some('B') => {
        raw.write_char(self.advance().unwrap())
        raw.write_char(self.advance().unwrap())
        let mut val : Int64 = 0L
        let mut digits = 0
        while !self.eof() {
          match self.peek() {
            Some('_') => raw.write_char(self.advance().unwrap())
            Some('0') => {
              raw.write_char(self.advance().unwrap())
              val = val * 2L
              digits += 1
            }
            Some('1') => {
              raw.write_char(self.advance().unwrap())
              val = val * 2L + 1L
              digits += 1
            }
            _ => break
          }
        }
        if digits == 0 {
          raise CueError::new(
            LexError,
            "invalid binary literal",
            span=Some(Span::new(start, self.position())),
          )
        }
        return Token::new(
          IntLit(val, raw.to_string()),
          Span::new(start, self.position()),
        )
      }
      Some('o') | Some('O') => {
        raw.write_char(self.advance().unwrap())
        raw.write_char(self.advance().unwrap())
        let mut val : Int64 = 0L
        let mut digits = 0
        while !self.eof() {
          match self.peek() {
            Some('_') => raw.write_char(self.advance().unwrap())
            Some(c) if c >= '0' && c <= '7' => {
              raw.write_char(self.advance().unwrap())
              val = val * 8L + (c.to_int() - '0'.to_int()).to_int64()
              digits += 1
            }
            _ => break
          }
        }
        if digits == 0 {
          raise CueError::new(
            LexError,
            "invalid octal literal",
            span=Some(Span::new(start, self.position())),
          )
        }
        return Token::new(
          IntLit(val, raw.to_string()),
          Span::new(start, self.position()),
        )
      }
      _ => ()
    }
  }

  let mut is_float = false
  // Integer digits
  while !self.eof() {
    match self.peek() {
      Some('_') => raw.write_char(self.advance().unwrap())
      Some(c) if is_digit(c) => {
        raw.write_char(self.advance().unwrap())
        clean.write_char(c)
      }
      _ => break
    }
  }

  // Fractional part (ensure not `..` / `...`)
  if self.peek() == Some('.') && self.peek_at(1) != Some('.') {
    is_float = true
    raw.write_char(self.advance().unwrap())
    clean.write_char('.')
    while !self.eof() {
      match self.peek() {
        Some('_') => raw.write_char(self.advance().unwrap())
        Some(c) if is_digit(c) => {
          raw.write_char(self.advance().unwrap())
          clean.write_char(c)
        }
        _ => break
      }
    }
  }

  // Exponent part
  if self.peek() == Some('e') || self.peek() == Some('E') {
    is_float = true
    let e = self.advance().unwrap()
    raw.write_char(e)
    clean.write_char(e)
    if self.peek() == Some('+') || self.peek() == Some('-') {
      let s = self.advance().unwrap()
      raw.write_char(s)
      clean.write_char(s)
    }
    let mut exp_digits = 0
    while !self.eof() {
      match self.peek() {
        Some('_') => raw.write_char(self.advance().unwrap())
        Some(c) if is_digit(c) => {
          raw.write_char(self.advance().unwrap())
          clean.write_char(c)
          exp_digits += 1
        }
        _ => break
      }
    }
    if exp_digits == 0 {
      raise CueError::new(
        LexError,
        "invalid exponent in number literal",
        span=Some(Span::new(start, self.position())),
      )
    }
  }

  // Optional CUE SI multiplier: K, M, G, T, P, Ki, Mi, Gi, Ti, Pi
  let mut multiplier : Int64 = 1L
  let mut has_multiplier = false
  match self.peek() {
    Some('K') | Some('M') | Some('G') | Some('T') | Some('P') => {
      let unit = self.advance().unwrap()
      raw.write_char(unit)
      let is_binary = self.peek() == Some('i')
      if is_binary {
        raw.write_char(self.advance().unwrap())
      }
      has_multiplier = true
      multiplier = match (unit, is_binary) {
        ('K', false) => 1000L
        ('M', false) => 1000000L
        ('G', false) => 1000000000L
        ('T', false) => 1000000000000L
        ('P', false) => 1000000000000000L
        ('K', true) => 1024L
        ('M', true) => 1048576L
        ('G', true) => 1073741824L
        ('T', true) => 1099511627776L
        ('P', true) => 1125899906842624L
        _ => 1L
      }
    }
    _ => ()
  }

  let clean_str = clean.to_string()
  let raw_str = raw.to_string()
  let span = Span::new(start, self.position())

  // Per CUE spec: a decimal with SI multiplier (e.g. `1.5K`) evaluates to an integer if exact!
  if is_float {
    let parsed : Result[Double, Error] = Ok(@string.parse_double(clean_str)) catch {
      e => Err(e)
    }
    match parsed {
      Ok(d) =>
        if has_multiplier {
          let scaled = d * multiplier.to_double()
          let as_int = scaled.to_int64()
          if as_int.to_double() == scaled {
            Token::new(IntLit(as_int, raw_str), span)
          } else {
            Token::new(FloatLit(scaled, raw_str), span)
          }
        } else {
          Token::new(FloatLit(d, raw_str), span)
        }
      Err(_) =>
        raise CueError::new(
          LexError,
          "invalid float literal '\{raw_str}'",
          span=Some(span),
        )
    }
  } else {
    let parsed : Result[Int64, Error] = Ok(@string.parse_int64(clean_str)) catch {
      e => Err(e)
    }
    match parsed {
      Ok(v) => Token::new(IntLit(v * multiplier, raw_str), span)
      Err(_) =>
        raise CueError::new(
          LexError,
          "invalid integer literal '\{raw_str}'",
          span=Some(span),
        )
    }
  }
}

///|
fn Lexer::consume_hashes(self : Lexer, hash_count : Int32) -> Unit {
  for i = 0; i < hash_count; i = i + 1 {
    ignore(self.advance())
  }
}

///|
fn Lexer::scan_string_or_bytes(
  self : Lexer,
  hash_count : Int32,
) -> Token raise CueError {
  let start = self.position()
  self.consume_hashes(hash_count)
  let quote = self.advance().unwrap() // '"' or '\''
  let is_bytes = quote == '\''

  // Check for multiline `"""` or `'''`
  let is_multiline = self.peek() == Some(quote) &&
    self.peek_at(1) == Some(quote)
  if is_multiline {
    ignore(self.advance())
    ignore(self.advance())
    // Per CUE spec, multiline string must start with a newline immediately after opening quotes
    if self.peek() == Some('\r') {
      ignore(self.advance())
    }
    if self.peek() != Some('\n') {
      raise CueError::new(
        LexError,
        "multiline string must begin with a newline after opening quotes",
        span=Some(Span::new(start, self.position())),
      )
    }
    ignore(self.advance())
  }

  let parts : Array[RawStringPart] = []
  let current = StringBuilder()
  let mut has_interp = false
  let mut closing_indent = ""

  while true {
    if self.eof() {
      raise CueError::new(
        LexError,
        "unterminated string literal",
        span=Some(Span::new(start, self.position())),
      )
    }

    // Check closing delimiter
    if is_multiline {
      if self.peek() == Some(quote) &&
        self.peek_at(1) == Some(quote) &&
        self.peek_at(2) == Some(quote) {
        let mut ok = true
        for i = 0; i < hash_count; i = i + 1 {
          if self.peek_at(3 + i) != Some('#') {
            ok = false
            break
          }
        }
        if ok {
          // Extract indentation before closing delimiter from current buffer
          let text = current.to_string()
          let chars = text.to_array()
          let mut last_nl = -1
          for i = chars.length() - 1; i >= 0; i = i - 1 {
            if chars[i] == '\n' {
              last_nl = i
              break
            }
          }
          let indent_start = last_nl + 1
          let indent_buf = StringBuilder()
          let mut all_ws = true
          for i = indent_start; i < chars.length(); i = i + 1 {
            let c = chars[i]
            if c == ' ' || c == '\t' {
              indent_buf.write_char(c)
            } else {
              all_ws = false
              break
            }
          }
          if all_ws {
            closing_indent = indent_buf.to_string()
            // Trim trailing newline + indentation before closing quotes
            let trimmed = StringBuilder()
            let end_idx = if last_nl >= 0 { last_nl } else { 0 }
            for i = 0; i < end_idx; i = i + 1 {
              trimmed.write_char(chars[i])
            }
            if !trimmed.to_string().is_empty() {
              parts.push(Text(trimmed.to_string()))
            }
          } else {
            parts.push(Text(text))
          }
          ignore(self.advance())
          ignore(self.advance())
          ignore(self.advance())
          self.consume_hashes(hash_count)
          break
        }
      }
    } else if self.peek() == Some(quote) {
      let mut ok = true
      for i = 0; i < hash_count; i = i + 1 {
        if self.peek_at(1 + i) != Some('#') {
          ok = false
          break
        }
      }
      if ok {
        ignore(self.advance())
        self.consume_hashes(hash_count)
        let tail = current.to_string()
        if !tail.is_empty() || parts.is_empty() {
          parts.push(Text(tail))
        }
        break
      }
    }

    let c = self.peek().unwrap()
    if !is_multiline && c == '\n' {
      raise CueError::new(
        LexError,
        "newline in single-line string literal",
        span=Some(Span::new(start, self.position())),
      )
    }

    // Handle escape or interpolation: `\` followed by `hash_count` `#` characters
    if c == '\\' {
      let mut esc_matches = true
      for i = 0; i < hash_count; i = i + 1 {
        if self.peek_at(1 + i) != Some('#') {
          esc_matches = false
          break
        }
      }
      if esc_matches {
        ignore(self.advance()) // consume '\'
        self.consume_hashes(hash_count)
        match self.peek() {
          Some('(') => {
            // Interpolation \(expr)
            has_interp = true
            let prefix = current.to_string()
            if !prefix.is_empty() {
              parts.push(Text(prefix))
              current.reset()
            }
            ignore(self.advance()) // consume '('
            let expr_start = self.position()
            let expr_buf = StringBuilder()
            let mut depth = 1
            while depth > 0 {
              if self.eof() {
                raise CueError::new(
                  LexError,
                  "unterminated string interpolation",
                  span=Some(Span::new(expr_start, self.position())),
                )
              }
              let ic = self.advance().unwrap()
              if ic == '(' {
                depth += 1
                expr_buf.write_char(ic)
              } else if ic == ')' {
                depth -= 1
                if depth > 0 {
                  expr_buf.write_char(ic)
                }
              } else if ic == '"' || ic == '\'' {
                expr_buf.write_char(ic)
                while !self.eof() {
                  let sc = self.advance().unwrap()
                  expr_buf.write_char(sc)
                  if sc == '\\' && !self.eof() {
                    expr_buf.write_char(self.advance().unwrap())
                  } else if sc == ic {
                    break
                  }
                }
              } else {
                expr_buf.write_char(ic)
              }
            }
            let expr_end = self.position()
            parts.push(
              ExprSource(expr_buf.to_string(), Span::new(expr_start, expr_end)),
            )
          }
          Some(esc) => {
            ignore(self.advance())
            match esc {
              'a' => current.write_char('\u{0007}')
              'b' => current.write_char('\b')
              'f' => current.write_char('\u{000C}')
              'n' => current.write_char('\n')
              'r' => current.write_char('\r')
              't' => current.write_char('\t')
              'v' => current.write_char('\u{000B}')
              '\\' => current.write_char('\\')
              '"' => current.write_char('"')
              '\'' => current.write_char('\'')
              '/' => current.write_char('/')
              'u' => {
                let code = self.scan_hex_escape(4, start)
                current.write_char(Int32::unsafe_to_char(code))
              }
              'U' => {
                let code = self.scan_hex_escape(8, start)
                current.write_char(Int32::unsafe_to_char(code))
              }
              'x' => {
                let code = self.scan_hex_escape(2, start)
                current.write_char(Int32::unsafe_to_char(code))
              }
              _ =>
                raise CueError::new(
                  LexError,
                  "unknown escape sequence '\\\{esc}'",
                  span=Some(Span::new(start, self.position())),
                )
            }
          }
          None =>
            raise CueError::new(
              LexError,
              "unterminated escape sequence",
              span=Some(Span::new(start, self.position())),
            )
        }
        continue
      }
    }

    current.write_char(self.advance().unwrap())
  }

  let span = Span::new(start, self.position())
  let final_parts = if is_multiline && !closing_indent.is_empty() {
    strip_multiline_indent(parts, closing_indent)
  } else {
    parts
  }

  if has_interp {
    if is_bytes {
      Token::new(InterpBytes(final_parts), span)
    } else {
      Token::new(InterpString(final_parts), span)
    }
  } else {
    let full = StringBuilder()
    for part in final_parts {
      match part {
        Text(s) => full.write_string(s)
        ExprSource(_, _) => ()
      }
    }
    let s = full.to_string()
    if is_bytes {
      Token::new(BytesLit(string_to_utf8_bytes(s)), span)
    } else {
      Token::new(StringLit(s), span)
    }
  }
}

///|
fn Lexer::scan_hex_escape(
  self : Lexer,
  count : Int32,
  start : Position,
) -> Int32 raise CueError {
  let mut code = 0
  for i = 0; i < count; i = i + 1 {
    match self.advance() {
      Some(c) if is_hex_digit(c) => code = code * 16 + hex_val(c)
      _ =>
        raise CueError::new(
          LexError,
          "invalid hex escape sequence",
          span=Some(Span::new(start, self.position())),
        )
    }
  }
  code
}

///|
fn strip_multiline_indent(
  parts : Array[RawStringPart],
  indent : String,
) -> Array[RawStringPart] {
  let out : Array[RawStringPart] = []
  let mut at_line_start = true
  for part in parts {
    match part {
      ExprSource(_, _) => {
        at_line_start = false
        out.push(part)
      }
      Text(s) => {
        let buf = StringBuilder()
        let lines = s.split("\n").collect()
        for i = 0; i < lines.length(); i = i + 1 {
          if i > 0 {
            buf.write_char('\n')
            at_line_start = true
          }
          let line = lines[i].to_owned()
          if at_line_start && line.has_prefix(indent) {
            buf.write_string(
              line.clamped_view(start=indent.length()).to_owned(),
            )
          } else {
            buf.write_string(line)
          }
          at_line_start = false
        }
        out.push(Text(buf.to_string()))
      }
    }
  }
  out
}

///|
fn string_to_utf8_bytes(s : String) -> Bytes {
  let bytes : Array[Byte] = []
  for ch in s {
    let cp = ch.to_int()
    if cp <= 0x7F {
      bytes.push(cp.to_byte())
    } else if cp <= 0x7FF {
      bytes.push((0xC0 | (cp >> 6)).to_byte())
      bytes.push((0x80 | (cp & 0x3F)).to_byte())
    } else if cp <= 0xFFFF {
      bytes.push((0xE0 | (cp >> 12)).to_byte())
      bytes.push((0x80 | ((cp >> 6) & 0x3F)).to_byte())
      bytes.push((0x80 | (cp & 0x3F)).to_byte())
    } else {
      bytes.push((0xF0 | (cp >> 18)).to_byte())
      bytes.push((0x80 | ((cp >> 12) & 0x3F)).to_byte())
      bytes.push((0x80 | ((cp >> 6) & 0x3F)).to_byte())
      bytes.push((0x80 | (cp & 0x3F)).to_byte())
    }
  }
  Bytes::from_array(bytes)
}