///|
/// 一等公民 Server-Sent Events(SSE)结构化事件帧、泛型强类型事件帧与四目标纯同步增量解码器
#derive(Debug, Eq)
pub(all) struct SseEvent {
  id : String?
  event : String?
  data : String
  retry_ms : Int32?
}

///|
pub fn SseEvent::SseEvent(
  data~ : String,
  id? : String,
  event? : String,
  retry_ms? : Int32,
) -> SseEvent {
  { id, event, data, retry_ms, }
}

///|
fn strip_cr_lf(s : String) -> String {
  let sb = StringBuilder()
  for ch in s {
    if ch != '\r' && ch != '\n' {
      sb.write_char(ch)
    }
  }
  sb.to_string()
}

///|
pub fn SseEvent::encode(self : SseEvent) -> Bytes {
  let sb = StringBuilder()
  match self.id {
    Some(id) => {
      sb.write_string("id: ")
      sb.write_string(strip_cr_lf(id))
      sb.write_char('\n')
    }
    None => ()
  }
  match self.event {
    Some(ev) => {
      sb.write_string("event: ")
      sb.write_string(strip_cr_lf(ev))
      sb.write_char('\n')
    }
    None => ()
  }
  match self.retry_ms {
    Some(ms) => {
      sb.write_string("retry: ")
      sb.write_string(ms.to_string())
      sb.write_char('\n')
    }
    None => ()
  }
  if self.data.is_empty() {
    sb.write_string("data:\n")
  } else {
    for line in self.data.split("\n") {
      let clean = if line.has_suffix("\r") {
        line[:line.length() - 1]
      } else {
        line
      }
      sb.write_string("data: ")
      sb.write_stringview(clean)
      sb.write_char('\n')
    }
  }
  sb.write_char('\n')
  @utf8.encode(sb.to_string())
}

///|
#derive(Debug, Eq)
pub(all) struct TypedSseEvent[T] {
  id : String?
  event : String?
  data : T
  retry_ms : Int32?
}

///|
pub fn[T] TypedSseEvent::TypedSseEvent(
  data~ : T,
  id? : String,
  event? : String,
  retry_ms? : Int32,
) -> TypedSseEvent[T] {
  { id, event, data, retry_ms, }
}

///|
/// 纯同步增量 SSE 解码状态机(支持有界缓冲防 OOM、WHATWG lastEventId 持久状态、首帧 UTF-8 BOM 剥离与跨 chunk 拆包,四目标全通测试)
pub struct SseDecoder {
  priv pending : Array[Byte]
  priv max_buffer_bytes : Int32
  priv mut pending_cr : Bool
  priv mut bom_checked : Bool
  priv bom_buf : Array[Byte]
  priv mut last_event_id : String?
  priv mut cur_event : String?
  priv mut cur_retry : Int32?
  priv cur_data : Array[String]
  priv mut cur_event_bytes : Int32
  priv mut has_data : Bool
}

///|
pub fn SseDecoder::SseDecoder(
  max_buffer_bytes~ : Int32 = 1_048_576,
) -> SseDecoder {
  {
    pending: [],
    max_buffer_bytes,
    pending_cr: false,
    bom_checked: false,
    bom_buf: [],
    last_event_id: None,
    cur_event: None,
    cur_retry: None,
    cur_data: [],
    cur_event_bytes: 0,
    has_data: false,
  }
}

///|
/// 返回 WHATWG 持久化的最近事件 ID(仅收到空 `id` / `id:` 行时重置为 `Some("")`)
pub fn SseDecoder::last_event_id(self : SseDecoder) -> String? {
  self.last_event_id
}

///|
fn SseDecoder::dispatch(self : SseDecoder, out : Array[SseEvent]) -> Unit {
  if self.has_data {
    out.push({
      id: self.last_event_id,
      event: self.cur_event,
      data: self.cur_data.join("\n"),
      retry_ms: self.cur_retry,
    })
  }
  self.cur_event = None
  self.cur_retry = None
  self.cur_data.clear()
  self.cur_event_bytes = 0
  self.has_data = false
}

///|
fn is_ascii_digits_only(s : String) -> Bool {
  if s.is_empty() {
    return false
  }
  for ch in s {
    let c = ch.to_int()
    if c < 48 || c > 57 {
      return false
    }
  }
  true
}

///|
fn SseDecoder::process_line(
  self : SseDecoder,
  line_bytes : Bytes,
  out : Array[SseEvent],
) -> Unit raise StreamError {
  if line_bytes.is_empty() {
    self.dispatch(out)
    return
  }
  let line = @utf8.decode_lossy(line_bytes)
  if line.has_prefix(":") {
    return
  }
  let (field, val) = match line.find(":") {
    Some(idx) => {
      let f = line[:idx].to_owned()
      let rest = line[idx + 1:].to_owned()
      let v = if rest.has_prefix(" ") { rest[1:].to_owned() } else { rest }
      (f, v)
    }
    None => (line, "")
  }
  match field {
    "data" => {
      let added = line_bytes.length() + 1
      if self.max_buffer_bytes > 0 &&
        self.cur_event_bytes + added > self.max_buffer_bytes {
        raise StreamError::PayloadTooLarge(self.max_buffer_bytes.to_int64())
      }
      self.cur_event_bytes = self.cur_event_bytes + added
      self.cur_data.push(val)
      self.has_data = true
    }
    "event" => {
      let added = line_bytes.length()
      if self.max_buffer_bytes > 0 &&
        self.cur_event_bytes + added > self.max_buffer_bytes {
        raise StreamError::PayloadTooLarge(self.max_buffer_bytes.to_int64())
      }
      self.cur_event_bytes = self.cur_event_bytes + added
      self.cur_event = Some(val)
    }
    "id" => if !val.contains("\u{0}") { self.last_event_id = Some(val) }
    "retry" =>
      if is_ascii_digits_only(val) {
        match (Some(@string.parse_int(val)) catch { _ => None }) {
          Some(ms) => if ms >= 0 { self.cur_retry = Some(ms) }
          None => ()
        }
      }
    _ => ()
  }
}

///|
fn bytes_from_slice(arr : Array[Byte], start : Int32, end : Int32) -> Bytes {
  let buf = @buffer.Buffer(capacity=end - start)
  for i in start.. Unit raise StreamError {
  if self.max_buffer_bytes > 0 &&
    self.cur_event_bytes + self.pending.length() >= self.max_buffer_bytes {
    raise StreamError::PayloadTooLarge(self.max_buffer_bytes.to_int64())
  }
  self.pending.push(b)
}

///|
fn SseDecoder::process_byte(
  self : SseDecoder,
  b : Byte,
  out : Array[SseEvent],
) -> Unit raise StreamError {
  if self.pending_cr {
    self.pending_cr = false
    if b == b'\n' {
      return
    }
  }
  if b == b'\n' {
    let line_bytes = bytes_from_slice(self.pending, 0, self.pending.length())
    self.pending.clear()
    self.process_line(line_bytes, out)
  } else if b == b'\r' {
    let line_bytes = bytes_from_slice(self.pending, 0, self.pending.length())
    self.pending.clear()
    self.process_line(line_bytes, out)
    self.pending_cr = true
  } else {
    self.push_pending_byte(b)
  }
}

///|
pub fn SseDecoder::feed(
  self : SseDecoder,
  chunk : BytesView,
) -> Array[SseEvent] raise StreamError {
  let out : Array[SseEvent] = []
  for b in chunk {
    if !self.bom_checked {
      let idx = self.bom_buf.length()
      let expected : Byte = if idx == 0 {
        b'\xef'
      } else if idx == 1 {
        b'\xbb'
      } else {
        b'\xbf'
      }
      if b == expected {
        self.bom_buf.push(b)
        if self.bom_buf.length() == 3 {
          self.bom_buf.clear()
          self.bom_checked = true
        }
        continue
      } else {
        self.bom_checked = true
        for prev in self.bom_buf {
          self.process_byte(prev, out)
        }
        self.bom_buf.clear()
      }
    }
    self.process_byte(b, out)
  }
  out
}

///|
pub fn SseDecoder::finish(self : SseDecoder) -> Array[SseEvent] {
  let out : Array[SseEvent] = []
  if !self.bom_checked && !self.bom_buf.is_empty() {
    self.bom_checked = true
    for prev in self.bom_buf {
      self.pending.push(prev)
    }
    self.bom_buf.clear()
  }
  if !self.pending.is_empty() {
    let line_bytes = bytes_from_slice(self.pending, 0, self.pending.length())
    self.pending.clear()
    self.process_line(line_bytes, out) catch {
      _ => ()
    }
  }
  self.pending_cr = false
  self.dispatch(out)
  out
}

///|
/// 纯同步增量 NDJSON 解码状态机(支持有界行缓冲与首帧 UTF-8 BOM 剥离,四目标全通测试)
pub struct NdjsonDecoder {
  priv pending : Array[Byte]
  priv max_line_bytes : Int32
  priv mut bom_checked : Bool
  priv bom_buf : Array[Byte]
}

///|
pub fn NdjsonDecoder::NdjsonDecoder(
  max_line_bytes~ : Int32 = 1_048_576,
) -> NdjsonDecoder {
  { pending: [], max_line_bytes, bom_checked: false, bom_buf: [], }
}

///|
fn parse_ndjson_line(
  line_bytes : Bytes,
  out : Array[Json],
) -> Unit raise StreamError {
  let raw = @utf8.decode(line_bytes) catch {
    _ => raise StreamError::StreamReadError("invalid UTF-8 in NDJSON line")
  }
  let trimmed = raw.trim()
  if trimmed.is_empty() {
    return
  }
  let parsed = @json.parse(trimmed) catch {
    err => raise StreamError::StreamReadError("invalid NDJSON: \{err}")
  }
  out.push(parsed)
}

///|
fn NdjsonDecoder::process_byte(
  self : NdjsonDecoder,
  b : Byte,
  out : Array[Json],
) -> Unit raise StreamError {
  if b == b'\n' {
    let mut end = self.pending.length()
    if end > 0 && self.pending[end - 1] == b'\r' {
      end = end - 1
    }
    let line_bytes = bytes_from_slice(self.pending, 0, end)
    self.pending.clear()
    parse_ndjson_line(line_bytes, out)
  } else if b == b'\r' {
    // Allow trailing CR right before LF without counting CR toward max_line_bytes
    self.pending.push(b)
  } else {
    let eff_len = self.pending.length()
    if self.max_line_bytes > 0 && eff_len >= self.max_line_bytes {
      raise StreamError::PayloadTooLarge(self.max_line_bytes.to_int64())
    }
    self.pending.push(b)
  }
}

///|
pub fn NdjsonDecoder::feed(
  self : NdjsonDecoder,
  chunk : BytesView,
) -> Array[Json] raise StreamError {
  let out : Array[Json] = []
  for b in chunk {
    if !self.bom_checked {
      let idx = self.bom_buf.length()
      let expected : Byte = if idx == 0 {
        b'\xef'
      } else if idx == 1 {
        b'\xbb'
      } else {
        b'\xbf'
      }
      if b == expected {
        self.bom_buf.push(b)
        if self.bom_buf.length() == 3 {
          self.bom_buf.clear()
          self.bom_checked = true
        }
        continue
      } else {
        self.bom_checked = true
        for prev in self.bom_buf {
          self.process_byte(prev, out)
        }
        self.bom_buf.clear()
      }
    }
    self.process_byte(b, out)
  }
  out
}

///|
pub fn NdjsonDecoder::finish(
  self : NdjsonDecoder,
) -> Array[Json] raise StreamError {
  let out : Array[Json] = []
  if !self.bom_checked && !self.bom_buf.is_empty() {
    self.bom_checked = true
    for prev in self.bom_buf {
      self.pending.push(prev)
    }
    self.bom_buf.clear()
  }
  if !self.pending.is_empty() {
    let mut end = self.pending.length()
    if end > 0 && self.pending[end - 1] == b'\r' {
      end = end - 1
    }
    let line_bytes = bytes_from_slice(self.pending, 0, end)
    self.pending.clear()
    parse_ndjson_line(line_bytes, out)
  }
  out
}