import logging
import sys
import threading


def configure_logging(debug: bool = False, level: str = "INFO", log_file: str | None = None):
    numeric_level = getattr(logging, level.upper(), logging.INFO)
    if debug and numeric_level > logging.DEBUG:
        numeric_level = logging.DEBUG

    handlers: list[logging.Handler] = [logging.StreamHandler(sys.stdout)]
    if log_file:
        handlers.append(logging.FileHandler(log_file))

    logging.basicConfig(
        level=numeric_level,
        format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
        handlers=handlers,
        force=True,
    )

    def log_uncaught_exception(exc_type, exc_value, exc_traceback):
        logging.getLogger("stillCenter").exception(
            "Unhandled exception",
            exc_info=(exc_type, exc_value, exc_traceback),
        )

    def log_thread_exception(args: threading.ExceptHookArgs):
        logging.getLogger("stillCenter").exception(
            "Unhandled thread exception",
            exc_info=(args.exc_type, args.exc_value, args.exc_traceback),
        )

    sys.excepthook = log_uncaught_exception
    threading.excepthook = log_thread_exception
