import os
import warnings
import logging

from . import defines


def setup_logging(level=defines.logging_level) -> logging.Logger:
    os.environ["TORCH_CPP_LOG_LEVEL"] = "ERROR"
    warnings.filterwarnings(
        "ignore", message="Overriding a previously registered kernel"
    )
    warnings.filterwarnings("ignore", message="Warning only once for all operators")
    warnings.filterwarnings("ignore", message=".*Couldn't find ffmpeg or avconv.*")
    warnings.filterwarnings("ignore", message="'force_all_finite' was renamed to")
    warnings.filterwarnings("ignore", message="n_jobs value 1 overridden")
    warnings.filterwarnings("ignore", message=".*websocket.*is deprecated")

    numeric_level = getattr(logging, level.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError(f"Invalid log level: {level}")

    logging.basicConfig(
        level=numeric_level,
        format="%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
        force=True,
    )

    # Now reduce verbosity for FastAPI, Uvicorn, Starlette
    for noisy_logger in (
        "uvicorn",
        "uvicorn.error",
        "uvicorn.access",
        "fastapi",
        "starlette",
    ):
        # for noisy_logger in ("starlette"):
        logging.getLogger(noisy_logger).setLevel(logging.WARNING)

    logger = logging.getLogger(__name__)

    return logger
