import logging
import sys

LOG_FORMAT = "\x1b[30;1m%(asctime)s\x1b[0m \x1b[34;1m%(levelname)s\x1b[0m \x1b[35m%(name)s\x1b[0m %(message)s"
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
RESET = "\033[0m"

LEVEL_COLORS = {
	logging.DEBUG: GREEN,
	logging.INFO: BLUE,
	logging.WARNING: YELLOW,
	logging.ERROR: RED,
	logging.CRITICAL: RED,
}

class Formatter(logging.Formatter):
	def __init__(self, fmt, datefmt=None, style="%"):
		super().__init__(fmt, datefmt, style)

	def format(self, record: logging.LogRecord):
		record.levelname = LEVEL_COLORS.get(record.levelno, "") + record.levelname.ljust(8) + RESET
			
		return super().format(record)

class MuteLoggersFilter(logging.Filter):
	def __init__(self, *names: str):
		self.names = set(names)

		super().__init__()

	def filter(self, record):
		return record.name not in self.names

def setup_logging(level: int=logging.INFO, levels: dict[str, int | bool]=dict()):
	logging.captureWarnings(True)

	handler = logging.StreamHandler(sys.stdout)
	handler.setFormatter(Formatter(fmt=LOG_FORMAT, datefmt=DATE_FORMAT))
	
	root = logging.getLogger()
	root.setLevel(level)

	muted_loggers = []

	levels |= {
		"asyncio": False,
		"aiosqlite": False,
		"watchfiles.main": False
	}

	for name, level in levels.items():
		if level == False: # noqa E712
			muted_loggers.append(name)
		else:
			logging.getLogger(name).setLevel(level)

	handler.addFilter(MuteLoggersFilter(*muted_loggers))

	root.handlers.clear()
	root.addHandler(handler)

	logging.getLogger("tgtilities")

get_logger = logging.getLogger