/**
 * Shared SSE (Server-Sent Events) parsing utilities.
 * Previously duplicated in api.js and convert.js.
 */

/** Single parsed SSE event */
export interface SseEvent {
  event: string
  data: string
}

/**
 * Parse a raw SSE event chunk into { event, data }.
 * Handles multi-line data fields and explicit event type overrides.
 *
 * @example
 * parseSseEvent('event: result\ndata: {"ok":true}')
 * // → { event: 'result', data: '{"ok":true}' }
 */
export function parseSseEvent(rawEvent: string): SseEvent {
  const lines = String(rawEvent || '').replace(/\r/g, '').split('\n')
  let event = 'message'
  const dataLines: string[] = []

  for (const line of lines) {
    if (!line) continue
    if (line.startsWith('event:')) {
      event = line.slice(6).trim() || 'message'
      continue
    }
    if (line.startsWith('data:')) {
      dataLines.push(line.slice(5).trimStart())
    }
  }

  return { event, data: dataLines.join('\n') }
}
