"""Entry point for the Dory sidecar."""

import asyncio
import logging
import os
import signal
import sys

from dory.sidecar.server import SidecarServer, SidecarConfig


def setup_logging() -> None:
    """Configure logging for the sidecar."""
    log_level = os.getenv("DORY_LOG_LEVEL", "INFO").upper()
    log_format = os.getenv("DORY_LOG_FORMAT", "text")

    if log_format == "json":
        import json

        class JsonFormatter(logging.Formatter):
            def format(self, record):
                return json.dumps({
                    "timestamp": self.formatTime(record),
                    "level": record.levelname,
                    "logger": record.name,
                    "message": record.getMessage(),
                })

        formatter = JsonFormatter()
    else:
        formatter = logging.Formatter(
            "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
        )

    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(formatter)

    root_logger = logging.getLogger()
    root_logger.addHandler(handler)
    root_logger.setLevel(getattr(logging, log_level, logging.INFO))


def run_sidecar() -> None:
    """Run the sidecar server (CLI entry point)."""
    setup_logging()
    logger = logging.getLogger("dory.sidecar")

    config = SidecarConfig.from_env()
    server = SidecarServer(config)

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    # Handle shutdown signals
    def handle_signal(sig):
        logger.info(f"Received signal {sig}, shutting down...")
        for task in asyncio.all_tasks(loop):
            task.cancel()

    for sig in (signal.SIGTERM, signal.SIGINT):
        loop.add_signal_handler(sig, lambda s=sig: handle_signal(s))

    try:
        loop.run_until_complete(server.run_forever())
    except asyncio.CancelledError:
        pass
    finally:
        loop.run_until_complete(server.stop())
        loop.close()

    logger.info("Sidecar shutdown complete")


if __name__ == "__main__":
    run_sidecar()
