"""JsonSink -- the raw event stream on stdout, one JSON object per line.

Every event is serialized with the canonical single-line form and flushed
immediately, so a caller (or CI) reading the pipe sees each event as soon
as it happens.
"""

from __future__ import annotations

import sys
from contextlib import suppress
from typing import IO

from spens.events import Event


class JsonSink:
    def __init__(self, stream: IO[str] | None = None) -> None:
        self.stream = stream if stream is not None else sys.stdout

    def on_event(self, event: Event) -> None:
        self.stream.write(event.to_line() + "\n")
        self.stream.flush()

    def close(self) -> None:
        with suppress(Exception):  # noqa: BLE001 -- DEVNULL etc. accept flush anyway
            self.stream.flush()
