// MoonBit adaptation and modifications by justjavac, 2026.
// Based on uWebSockets HttpParser.h, authored by Alex Hultman, 2018-2026.
// Intellectual property of third-party. Upstream Apache-2.0: LICENSE-APACHE and NOTICE.

///|
/// Creates an empty parser with independent state and explicit head limits.
///
/// `max_header_bytes` counts the entire request line, fields, and final CRLF;
/// `max_headers` counts actual fields, excluding the request line. Both must be
/// positive or construction raises `InvalidLimits`. No body buffer is allocated.
/// `algorithm` affects scans only; every backend implements the same grammar.
pub fn Parser::new(
  max_header_bytes~ : Int32 = 4096,
  max_headers~ : Int32 = 98,
  algorithm~ : Algorithm = Auto,
) -> Parser raise ParseError {
  guard max_header_bytes > 0 && max_headers > 0 else { raise InvalidLimits }
  {
    max_header_bytes,
    max_headers,
    algorithm,
    buffer: @buffer.Buffer(),
    delimiter: 0,
    phase: Head,
    failure: None,
    active: false,
  }
}

///|
/// Reads just one head without copying following body or pipelined bytes.
fn Parser::read_head(
  self : Parser,
  input : BytesView,
) -> (Int32, Request?) raise ParseError {
  let remaining = self.max_header_bytes - self.buffer.length()
  let count = if input.length() < remaining {
    input.length()
  } else {
    remaining
  }
  let (consumed, matched) = head_end(
    input[:count],
    self.delimiter,
    self.algorithm,
  )
  if matched == 4 {
    let head = if self.buffer.is_empty() {
      input[:consumed].to_owned()
    } else {
      self.buffer.write_bytesview(input[:consumed])
      self.buffer.to_bytes()
    }
    let request = parse_head(head, self.max_headers, self.algorithm)
    self.buffer.reset()
    self.delimiter = 0
    (consumed, Some(request))
  } else {
    self.buffer.write_bytesview(input[:consumed])
    self.delimiter = matched
    guard self.buffer.length() < self.max_header_bytes else {
      raise HeaderTooLarge
    }
    (consumed, None)
  }
}

///|
/// Drives framing with state committed before each callback or resumable stop.
fn Parser::feed_impl(
  self : Parser,
  input : BytesView,
  on_request : (Request) -> Control,
  on_body : (BytesView, UInt64) -> Control,
) -> FeedResult raise ParseError {
  for offset = 0 {
    match self.phase {
      Head => {
        if offset == input.length() {
          return Consumed(offset)
        }
        let (consumed, request) = self.read_head(input[offset:])
        let offset = offset + consumed
        if request is Some(request) {
          self.phase = PendingBody(request)
          if on_request(request) == Stop {
            return Stopped(offset)
          }
          continue offset
        }
        return Consumed(offset)
      }
      PendingBody(request) => {
        self.phase = body_phase(request)
        continue offset
      }
      Fixed(remaining~, initial~) => {
        if !initial && offset == input.length() {
          return Consumed(offset)
        }
        let available = input.length() - offset
        let emitted = if remaining < available.to_uint64() {
          remaining.to_int()
        } else {
          available
        }
        let after = remaining - emitted.to_uint64()
        self.phase = if after == 0 {
          Head
        } else {
          Fixed(remaining=after, initial=false)
        }
        let end = offset + emitted
        if on_body(input[offset:end], after) == Stop {
          return Stopped(end)
        }
        continue end
      }
      Chunked(chunk) => {
        if offset == input.length() {
          return Consumed(offset)
        }
        let (consumed, event) = chunk.step(input[offset:])
        let end = offset + consumed
        if chunk.phase is Done {
          self.phase = Head
        }
        if event is Some((body, remaining)) && on_body(body, remaining) == Stop {
          return Stopped(end)
        }
        continue end
      }
    }
  }
}

///|
/// Consumes unpadded immutable input, emitting requests and streaming body views.
///
/// Request callbacks run after head/Host/TE+CL validation and before detailed
/// body-framing validation. Returning `Stop` permits protocol handoff; resume
/// by feeding the unconsumed suffix, possibly empty, to the same parser.
/// Fixed-body events report exact remaining bytes; chunked payload reports
/// `18446744073709551615UL`, then an empty event with zero before trailers complete.
/// No-body requests emit one empty event with zero. A fixed body whose head
/// arrived alone initially emits an empty event with its full remaining length.
/// Body storage is never accumulated. Views are immutable and may be retained.
/// Malformed input raises a sticky `ParseError`; `reset` is required to recover.
/// This parser must not be fed, copied, reset, or finished from its callbacks.
pub fn Parser::feed(
  self : Parser,
  input : BytesView,
  on_request~ : (Request) -> Control,
  on_body~ : (BytesView, UInt64) -> Control,
) -> FeedResult raise ParseError {
  guard !self.active else { raise ReentrantCall }
  if self.failure is Some(error) {
    raise error
  }
  self.active = true
  defer {
    self.active = false
  }
  let result = Ok(self.feed_impl(input, on_request, on_body)) catch {
    error => Err(error)
  }
  match result {
    Ok(result) => result
    Err(error) => {
      self.failure = Some(error)
      raise error
    }
  }
}

///|
/// Returns whether the parser is healthy and at an empty request boundary.
/// A body-end event can precede chunked trailers, so it alone does not prove idle.
/// A paused request callback leaves pending body validation and is not idle.
pub fn Parser::is_idle(self : Parser) -> Bool {
  self.failure is None && self.phase is Head && self.buffer.is_empty()
}

///|
/// Returns the number of buffered incomplete-head bytes, excluding all body bytes.
/// The value is at most `max_header_bytes`, including bytes retained on error.
pub fn Parser::buffered_bytes(self : Parser) -> Int32 {
  self.buffer.length()
}

///|
/// Checks EOF without accepting an unfinished request, payload, or trailers.
/// Healthy idle state succeeds without closing the parser. An unfinished state
/// raises sticky `UnexpectedEof`; existing wire errors are raised unchanged.
/// Call this only after any paused request callback has been resumed.
pub fn Parser::finish(self : Parser) -> Unit raise ParseError {
  guard !self.active else { raise ReentrantCall }
  if self.failure is Some(error) {
    raise error
  }
  guard self.is_idle() else {
    self.failure = Some(UnexpectedEof)
    raise UnexpectedEof
  }
}

///|
/// Discards buffered input, framing state, and any sticky error for reuse.
/// Limits and algorithm are retained; existing request/body views stay valid.
/// Aliased parser references observe the reset; independent copies do not.
/// Raises `ReentrantCall` if invoked on this parser inside a callback.
pub fn Parser::reset(self : Parser) -> Unit raise ParseError {
  guard !self.active else { raise ReentrantCall }
  self.buffer.reset()
  self.delimiter = 0
  self.phase = Head
  self.failure = None
}

///|
/// Creates an independent parser at the same framing and buffered-head position.
/// Limits, algorithm, pending request metadata, and sticky errors are copied.
/// Immutable wire bytes are safely shared; all mutable cursor/buffer state is
/// independent. Raises `ReentrantCall` when called from this parser's callback.
pub fn Parser::copy(self : Parser) -> Parser raise ParseError {
  guard !self.active else { raise ReentrantCall }
  let buffer = @buffer.Buffer(capacity=self.buffer.length())
  buffer.write_bytesview(Bytes::from_array(self.buffer.view()))
  {
    max_header_bytes: self.max_header_bytes,
    max_headers: self.max_headers,
    algorithm: self.algorithm,
    buffer,
    delimiter: self.delimiter,
    phase: match self.phase {
      Head => Head
      PendingBody(request) => PendingBody(request.copy())
      Fixed(remaining~, initial~) => Fixed(remaining~, initial~)
      Chunked(chunk) => Chunked(chunk.copy())
    },
    failure: self.failure,
    active: false,
  }
}