// State transitions adapted from uWebSockets ChunkedEncoding.h.
// MoonBit adaptation and modifications by justjavac, 2026.
// Authored by Alex Hultman, 2018-2026. See LICENSE-APACHE and NOTICE.
// Intellectual property of third-party.

///|
/// Initializes a chunked stream with no buffered size digits or payload.
fn ChunkState::new() -> ChunkState {
  { phase: Size, size: 0, expects_name: false, in_name: false, quoted: false, }
}

///|
/// Copies a chunk cursor so fragmented parsing can continue independently.
fn ChunkState::copy(self : ChunkState) -> ChunkState {
  {
    phase: self.phase,
    size: self.size,
    expects_name: self.expects_name,
    in_name: self.in_name,
    quoted: self.quoted,
  }
}

///|
/// Finishes a size line, signaling body completion before consuming trailers.
fn ChunkState::finish_size(self : ChunkState) -> Bool {
  self.expects_name = false
  self.in_name = false
  self.quoted = false
  if self.size == 0 {
    self.phase = TrailerStart
    true
  } else {
    self.phase = Data
    false
  }
}

///|
/// Consumes framing until one payload event, body-end event, or input exhaustion.
fn ChunkState::step(
  self : ChunkState,
  input : BytesView,
) -> (Int32, (BytesView, UInt64)?) raise ParseError {
  for offset = 0; offset < input.length(); {
    let byte = input[offset]
    match self.phase {
      Size => {
        match byte {
          b';' => {
            self.phase = Extension
            self.expects_name = true
          }
          13 => self.phase = ExtensionLf
          10 => if self.finish_size() { return (offset + 1, Some((b"", 0UL))) }
          _ => {
            let digit = match byte {
              b'0'..<=b'9' => (byte - b'0').to_uint64()
              b'a'..<=b'f' => (byte - b'a' + 10).to_uint64()
              b'A'..<=b'F' => (byte - b'A' + 10).to_uint64()
              _ => raise InvalidChunkedEncoding
            }
            // Explicit limits prevent size+CRLF from entering upstream control bits.
            guard self.size <= (MAX_CHUNK_LENGTH - digit) / 16 else {
              raise InvalidChunkedEncoding
            }
            self.size = self.size * 16 + digit
          }
        }
        continue offset + 1
      }
      ExtensionLf => {
        guard byte == 10 else { raise InvalidChunkedEncoding }
        if self.finish_size() {
          return (offset + 1, Some((b"", 0UL)))
        }
        continue offset + 1
      }
      Extension => {
        guard byte != 0 && !(byte < 32 && byte != 13 && byte != 10 && byte != 9) else {
          raise InvalidChunkedEncoding
        }
        if byte == 13 {
          guard !self.expects_name else { raise InvalidChunkedEncoding }
          self.phase = ExtensionLf
          continue offset + 1
        }
        if self.expects_name {
          guard is_token(byte) else { raise InvalidChunkedEncoding }
          self.expects_name = false
          self.in_name = true
        } else if self.in_name {
          if byte == b'=' {
            self.in_name = false
          } else if byte == b';' {
            self.in_name = false
            self.expects_name = true
          } else {
            guard is_token(byte) else { raise InvalidChunkedEncoding }
          }
        } else {
          if byte == b'"' {
            self.quoted = !self.quoted
          }
          if byte == b';' && !self.quoted {
            self.expects_name = true
          }
        }
        if byte == 10 && !self.quoted {
          guard !self.expects_name else { raise InvalidChunkedEncoding }
          if self.finish_size() {
            return (offset + 1, Some((b"", 0UL)))
          }
        }
        continue offset + 1
      }
      Data => {
        let available = input.length() - offset
        let emitted = if self.size < available.to_uint64() {
          self.size.to_int()
        } else {
          available
        }
        let end = offset + emitted
        let remaining = self.size - emitted.to_uint64()
        if remaining == 0 {
          // Validate available CRLF before emitting, as upstream does for whole chunks.
          if end < input.length() {
            guard input[end] == 13 else { raise InvalidChunkedEncoding }
            if input.length() - end >= 2 {
              guard input[end + 1] == 10 else { raise InvalidChunkedEncoding }
              self.size = 0
              self.phase = Size
              return (end + 2, Some((input[offset:end], UNKNOWN_BODY_LENGTH)))
            }
            self.size = 0
            self.phase = DataLf
            return (end + 1, Some((input[offset:end], UNKNOWN_BODY_LENGTH)))
          }
          self.phase = DataCr
        }
        self.size = remaining
        return (end, Some((input[offset:end], UNKNOWN_BODY_LENGTH)))
      }
      DataCr => {
        guard byte == 13 else { raise InvalidChunkedEncoding }
        self.phase = DataLf
        continue offset + 1
      }
      DataLf => {
        guard byte == 10 else { raise InvalidChunkedEncoding }
        self.phase = Size
        self.size = 0
        continue offset + 1
      }
      TrailerStart => {
        guard byte != 10 else { raise InvalidChunkedEncoding }
        self.phase = if byte == 13 { TrailerEndLf } else { TrailerLine }
        continue offset + 1
      }
      TrailerEndLf => {
        guard byte == 10 else { raise InvalidChunkedEncoding }
        self.phase = Done
        return (offset + 1, None)
      }
      TrailerLine => {
        guard byte != 10 else { raise InvalidChunkedEncoding }
        if byte == 13 {
          self.phase = TrailerLineLf
        }
        continue offset + 1
      }
      TrailerLineLf => {
        // Preserve upstream's permissive treatment of CR inside skipped trailer lines.
        if byte == 10 {
          self.phase = TrailerStart
        } else if byte != 13 {
          self.phase = TrailerLine
        }
        continue offset + 1
      }
      Done => return (offset, None)
    }
  } nobreak {
    (offset, None)
  }
}