# streaming.py — SSE (Server-Sent Events) parser for the COS SDK.
#
# Parses the text/event-stream format that /api/v2/validate/stream returns.
# SSE format looks like:
#   event: t1_result
#   data: {"confidence_score": 0.95, ...}
#
#   event: validation_complete
#   data: {"confidence_score": 0.72, ...}
#
#   event: done
#   data: {}

import json
from typing import Iterator

from cos_sdk.models import StreamEvent


def parse_sse_stream(lines: Iterator[str]) -> Iterator[StreamEvent]:
    """Parse an SSE stream into StreamEvent objects.

    Args:
        lines: Iterator of text lines from the SSE response

    Yields:
        StreamEvent objects, one per event in the stream
    """
    event_type = ""
    data_lines = []

    for line in lines:
        line = line.rstrip("\n").rstrip("\r")

        if line.startswith("event: "):
            event_type = line[7:]
        elif line.startswith("data: "):
            data_lines.append(line[6:])
        elif line == "":
            # Empty line = end of event
            if event_type and data_lines:
                raw_data = "\n".join(data_lines)
                try:
                    data = json.loads(raw_data)
                except json.JSONDecodeError:
                    data = {"raw": raw_data}

                yield StreamEvent(event=event_type, data=data)

                # Stop after "done" event
                if event_type == "done":
                    return

            event_type = ""
            data_lines = []
