from __future__ import annotations

import json
from typing import Any, Iterator


def format_sse_event(event: str, data: dict[str, Any]) -> str:
    """SSE 单条 event（chat-llm-design §6.3）。"""
    payload = json.dumps(data, ensure_ascii=False)
    return f"event: {event}\ndata: {payload}\n\n"


def sse_trace(lines: list[str]) -> str:
    return format_sse_event("trace", {"lines": lines})


def sse_delta(text: str) -> str:
    return format_sse_event("delta", {"text": text})


def sse_citation(atom_id: str, concept: str, snippet: str) -> str:
    return format_sse_event("citation", {"atom_id": atom_id, "concept": concept, "snippet": snippet})


def sse_error(code: str, message: str, *, recoverable: bool = True) -> str:
    return format_sse_event("error", {"code": code, "message": message, "recoverable": recoverable})


def sse_done(payload: dict[str, Any]) -> str:
    return format_sse_event("done", payload)


def stream_events(events: Iterator[tuple[str, dict[str, Any]]]) -> Iterator[str]:
    for event, data in events:
        yield format_sse_event(event, data)
