import logging

from telebot import logger as telebot_logger
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, CallbackQuery

from config import ADMINS_LIST

LOG_LEVELS = {
    "🔴 ERROR": logging.ERROR,
    "🟠 WARNING": logging.WARNING,
    "🟢 INFO": logging.INFO,
    "🔵 DEBUG": logging.DEBUG
}

def set_log_level(level: int):
    # Устанавливаем уровень для telebot и связанных библиотек
    telebot_logger.setLevel(level)
    for handler in telebot_logger.handlers:
        handler.setLevel(level)

    logging.getLogger("pyzabbix").setLevel(level)
    logging.getLogger("requests").setLevel(level)
    # logging.getLogger("urllib3").setLevel(level)

    # import http.client
    # if level == logging.DEBUG:
    #     http.client.HTTPConnection.debuglevel = 1
    # else:
    #     http.client.HTTPConnection.debuglevel = 0


def register_handlers(bot, app, state_manager):
    @bot.message_handler(commands=['debug'], func=lambda message: message.chat.id in ADMINS_LIST)
    def debug_handler(message: Message):
        chat_id = message.chat.id
        markup = InlineKeyboardMarkup(row_width=1)
        buttons = [InlineKeyboardButton(text=level, callback_data=f"setlog_{level}") for level in LOG_LEVELS]
        cancel_button = InlineKeyboardButton(text="Отмена", callback_data="cancel_input")
        markup.add(*buttons)
        markup.add(cancel_button)
        bot.send_message(chat_id, "Выберите уровень логирования", reply_markup=markup)

    @bot.callback_query_handler(func=lambda call: call.data.startswith("setlog_"))
    def handle_log_level_callback(call: CallbackQuery):
        level_text = call.data.replace("setlog_", "")
        chat_id = call.message.chat.id
        message_id = call.message.message_id

        if level_text in LOG_LEVELS:
            level = LOG_LEVELS[level_text]
            set_log_level(level)
            bot.answer_callback_query(call.id, f"✅ Уровень логирования установлен: {level_text}")
            bot.delete_message(chat_id, message_id)
            bot.send_message(chat_id, f"📋 Логгер переведён в режим: {level_text}")
        else:
            bot.answer_callback_query(call.id, "❌ Неизвестный уровень логирования")
