"""Service container (dependency injection)."""

from __future__ import annotations

from typing import Any

from app.core.cache import get_cache
from app.core.event_bus import get_event_bus


class ServiceContainer:
    """Simple DI container for shared services."""

    def __init__(self) -> None:
        self._services: dict[str, Any] = {}
        self._initialized = False

    def register(self, name: str, instance: Any) -> None:
        """Register a service instance."""
        self._services[name] = instance

    def get(self, name: str) -> Any:
        """Get a service by name."""
        if name not in self._services:
            raise KeyError(f"Service '{name}' not registered")
        return self._services[name]

    def has(self, name: str) -> bool:
        """Check if a service is registered."""
        return name in self._services

    async def initialize(self) -> None:
        """Initialize core services."""
        if self._initialized:
            return
        self.register("cache", get_cache())
        self.register("event_bus", get_event_bus())
        self._initialized = True


_container = ServiceContainer()


def get_container() -> ServiceContainer:
    """Get the global service container."""
    return _container
