from typing import Iterator


def parse_sse(response) -> Iterator[dict]:
    """Parse Server-Sent Events from a streaming response.

    Yields dicts with keys: event, data, id, retry.
    Stops on [DONE] sentinel.
    """
    buffer = ""

    for chunk in response.iter_content(chunk_size=None, decode_unicode=True):
        if chunk is None:
            continue
        buffer += chunk

        while "\n\n" in buffer:
            event_str, buffer = buffer.split("\n\n", 1)
            event_str = event_str.strip()
            if not event_str:
                continue

            event = {"data": ""}
            for line in event_str.split("\n"):
                if line.startswith("data: "):
                    value = line[6:]
                    if value == "[DONE]":
                        return
                    event["data"] = (
                        event["data"] + "\n" + value if event["data"] else value
                    )
                elif line.startswith("event: "):
                    event["event"] = line[7:]
                elif line.startswith("id: "):
                    event["id"] = line[4:]
                elif line.startswith("retry: "):
                    try:
                        event["retry"] = int(line[7:])
                    except ValueError:
                        pass
                elif line == "data:":
                    event["data"] = event["data"] + "\n" if event["data"] else ""

            if event.get("data") is not None:
                yield event
