import logging
import signal
import sys
import threading

LOGGER = logging.getLogger("amc.server")


def configure_logging():
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s %(message)s",
        stream=sys.stdout,
        force=True,
    )


def install_signal_handlers(server):
    """Log termination signals and shut down cleanly."""

    def _handle(signum, _frame):
        LOGGER.warning("Received signal %s, shutting down AMC server", signum)
        # shutdown() blocks until serve_forever loop wakes; call from a helper thread.
        threading.Thread(target=server.shutdown, daemon=True).start()

    for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
        try:
            signal.signal(sig, _handle)
        except (ValueError, OSError, RuntimeError):
            # Some environments may restrict signal registration.
            continue
