import asyncio
import logging

logger = logging.getLogger(__name__)


class ServiceManager:
    def __init__(self):
        self._services = {}

    def register(self, service) -> None:
        self._services[service.name] = service
        logger.info(f"Registered service: {service.name}")

    def get_service(self, name: str):
        return self._services.get(name)

    def list_services(self) -> list[dict]:
        return [
            {
                "name": svc.name,
                "status": svc.status,
                "interval_seconds": svc.interval_seconds,
                "last_run": svc.last_run,
                "next_run": svc.next_run,
                "uptime": svc.uptime,
                "log_buffer": list(svc.log_buffer),
            }
            for svc in self._services.values()
        ]

    async def start_all(self) -> None:
        for name, svc in self._services.items():
            await svc.start()
            logger.info(f"Started service: {name}")

    async def stop_all(self) -> None:
        tasks = []
        for name, svc in self._services.items():
            tasks.append(svc.stop())
            logger.info(f"Stopping service: {name}")
        if tasks:
            await asyncio.gather(*tasks, return_exceptions=True)
        logger.info("All services stopped")


service_manager = ServiceManager()
