from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Dict, Optional

from core.logger import log_error, log_info


@dataclass(frozen=True)
class Event:
    name: str
    side: str
    attrs: Dict[str, Any]


class TelemetryManager:
    """Thin event logger with a consistent schema.

    This does NOT replace core.logger; it standardizes event naming and fields so
    troubleshooting doesn't depend on ad-hoc log messages.

    Fields are rendered as key=value pairs to keep the existing plain-text log format.
    """

    _instance: Optional["TelemetryManager"] = None

    @classmethod
    def get(cls) -> "TelemetryManager":
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    def event(self, name: str, **attrs: Any) -> None:
        log_info(self._format(name, attrs))

    def error(self, name: str, error: Exception | str, **attrs: Any) -> None:
        err_str = error if isinstance(error, str) else f"{type(error).__name__}: {error}"
        attrs = dict(attrs)
        attrs.setdefault("error", err_str)
        log_error(self._format(name, attrs))

    def _format(self, name: str, attrs: Dict[str, Any]) -> str:
        parts = [f"EVENT: {name}"]
        for k, v in attrs.items():
            if v is None:
                continue
            parts.append(f"{k}={v}")
        return " | ".join(parts)
