"""Console transport for local log output."""

from __future__ import annotations

import json
import sys
from typing import TextIO

from vedatrace.models import LogRecord


class ConsoleTransport:
    """Simple line-oriented console transport.

    Use ``enabled=config.console_enabled`` when constructing from config.
    """

    def __init__(self, stream: TextIO | None = None, *, enabled: bool = True) -> None:
        self._stream = sys.stderr if stream is None else stream
        self._enabled = enabled

    def emit(self, records: list[LogRecord]) -> None:
        """Write records to console, one line per record."""

        if not self._enabled:
            return

        for record in records:
            metadata_str = (
                f" {json.dumps(record.metadata, sort_keys=True)}"
                if record.metadata
                else ""
            )
            line = (
                f"{record.timestamp} [{record.level.value}] "
                f"{record.service}: {record.message}{metadata_str}"
            )
            self._stream.write(f"{line}\n")
        self._stream.flush()

    def close(self) -> None:
        """No-op close for interface compatibility."""

        return None
