// Adapted from uWebSockets at 05e6c8b55b4d28293cf23570f0f61318f8600560.
// MoonBit adaptation and modifications by justjavac, 2026.
// Authored by Alex Hultman, 2018-2026. Intellectual property of third-party.
// See LICENSE-APACHE and NOTICE for the upstream license and adaptation notice.

///|
/// Selects bounded byte scanning, without changing the accepted grammar.
///
/// `Simd` requests V128 scans on native and linear-memory Wasm. Inputs shorter
/// than sixteen bytes and the Wasm GC/JavaScript backends use scalar scans.
/// `Auto` uses scalar scans until a complete CI snapshot establishes dispatch.
#derive(Debug, Eq)
pub(all) enum Algorithm {
  Auto
  Scalar
  Simd
}

///|
/// Controls whether a callback lets the parser continue consuming this input.
///
/// `Stop` leaves the parser resumable and returns an exact consumed byte count.
/// After a request callback it also supports protocol handoff: body framing
/// has not been interpreted, and the unconsumed suffix belongs to the caller.
#derive(Debug, Eq)
pub(all) enum Control {
  Continue
  Stop
}

///|
/// Describes how much of the supplied view a `feed` call consumed.
///
/// `Consumed` includes bytes buffered for an incomplete header, and does not
/// imply a complete request or body. `Stopped` means a callback returned
/// `Stop`. In both cases the count is relative to the supplied view, in bytes.
#derive(Debug, Eq)
pub(all) enum FeedResult {
  Consumed(Int32)
  Stopped(Int32)
}

///|
/// Returns the consumed byte count for advancing the caller's input view.
/// This operation does not change the result or parser state.
pub fn FeedResult::consumed(self : FeedResult) -> Int32 {
  match self {
    Consumed(length) | Stopped(length) => length
  }
}

///|
/// Distinguishes a query flag from a query value, including an empty value.
///
/// `Valueless` represents `?debug`; `Value(b"")` represents `?debug=`.
/// Bytes can include NUL and invalid UTF-8. Keys are matched without decoding;
/// values use the pinned upstream's permissive percent arithmetic and `+` rule.
#derive(Debug, Eq)
pub(all) enum QueryValue {
  Valueless
  Value(Bytes)
}

///|
/// Reports invalid wire input, incomplete EOF, or an invalid parser operation.
///
/// Wire errors correspond to upstream 400 Bad Request, including header limits.
/// `UnexpectedEof` rejects an unfinished head, body, chunk, or trailer section.
/// `InvalidLimits` rejects nonpositive limits at construction; `ReentrantCall`
/// rejects feeding, copying, resetting, or finishing the same parser inside a
/// callback. Wire/EOF errors remain sticky until `reset`, and no later feed
/// emits callbacks. Callbacks cannot raise errors through this API.
#derive(Debug, Eq)
pub(all) suberror ParseError {
  InvalidRequestLine
  InvalidHeaderName
  InvalidHeaderValue
  MissingHost
  DuplicateHost
  InvalidHost
  ConflictingBodyFraming
  InvalidContentLength
  InvalidTransferEncoding
  HeaderTooLarge
  TooManyHeaders
  InvalidChunkedEncoding
  UnexpectedEof
  InvalidLimits
  ReentrantCall
}

///|
/// Holds one normalized name and its trimmed immutable value view.
priv struct Header {
  name : Bytes
  value : BytesView
}

///|
/// An owned, retainable request head with independently mutable routing metadata.
///
/// Wire data is immutable and remains valid after callbacks and parser reset.
/// Header names are lowercase, values are trimmed, and order/duplicates remain
/// intact. Byte views preserve obs-text without requiring valid UTF-8. Assignment
/// aliases the routing metadata; use `copy` for independent yield/parameters.
/// The original method and query never change when using compatibility getters.
pub struct Request {
  priv original_method : BytesView
  priv lowercase_method : Bytes
  priv target : BytesView
  priv query_separator : Int32
  priv fields : Array[Header]
  priv mut yielded : Bool
  priv mut parameters : Array[Bytes]
  priv mut parameter_offsets : Map[String, Int32]
}

///|
/// Records framing separately from request ownership and callbacks.
priv enum Phase {
  Head
  PendingBody(Request)
  Fixed(remaining~ : UInt64, initial~ : Bool)
  Chunked(ChunkState)
}

///|
/// Identifies bounded, allocation-free chunk-size, payload, and trailer states.
priv enum ChunkPhase {
  Size
  Extension
  ExtensionLf
  Data
  DataCr
  DataLf
  TrailerStart
  TrailerEndLf
  TrailerLine
  TrailerLineLf
  Done
}

///|
/// Keeps chunk sizes separate from control bits to prevent upstream size overflow.
priv struct ChunkState {
  mut phase : ChunkPhase
  mut size : UInt64
  mut expects_name : Bool
  mut in_name : Bool
  mut quoted : Bool
}

///|
/// An incremental HTTP/1.1 request parser with bounded header storage.
///
/// The parser buffers only incomplete request heads, streams body views through
/// callbacks, skips chunked trailers, and parses pipelined requests in order.
/// Default limits are 4096 head bytes and 98 fields, matching upstream defaults.
/// State has reference semantics: assignment aliases it; `copy` creates an
/// independent cursor and buffer. Use `reset` after a wire error or to reuse it.
/// Callbacks may inspect requests but must not reenter this parser.
pub struct Parser {
  priv max_header_bytes : Int32
  priv max_headers : Int32
  priv algorithm : Algorithm
  priv buffer : @buffer.Buffer
  priv mut delimiter : Int32
  priv mut phase : Phase
  priv mut failure : ParseError?
  priv mut active : Bool
}

///|
/// Bounds fixed bodies exactly as the pinned upstream's 56-bit state register.
const MAX_BODY_LENGTH : UInt64 = 72057594037927935UL

///|
/// Leaves two bytes of headroom for upstream's chunk payload CRLF accounting.
const MAX_CHUNK_LENGTH : UInt64 = 72057594037927933UL

///|
/// Signals unknown chunked remaining length through the public body callback.
const UNKNOWN_BODY_LENGTH : UInt64 = 18446744073709551615UL