import { createParser, type EventSourceMessage } from 'eventsource-parser'

export async function parse(stream: ReadableStream<Uint8Array>, onEvent: (event: EventSourceMessage) => void) {
  const parser = createParser({ onEvent })
  const reader = stream.getReader()
  const decoder = new TextDecoder()

  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    parser.feed(decoder.decode(value, { stream: true }))
  }
}

export async function aiStreamParse(
  stream: ReadableStream<Uint8Array>,
  onMessage: (json: any, content: string) => void
) {
  parse(stream, (event) => {
    if (event.data === '[DONE]') return
    const json = JSON.parse(event.data)
    onMessage(json, json.choices[0].delta.content)
  })
}
