#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Главный модуль запуска телеграм-бота для управления Synology NAS
"""

import os
import signal
import sys
import asyncio
import logging
from telegram.ext import (
    Application,
    CommandHandler,
    CallbackQueryHandler,
    MessageHandler,
    filters
)

from src.config.config import TELEGRAM_TOKEN
from src.handlers.help_handlers import (
    start_command,
    help_command
)
from src.handlers.command_handlers import (
    status_command,
    power_command,
    power_callback
)
from src.handlers.extended_handlers import (
    storage_command,
    shares_command,
    system_command,
    load_command,
    security_command,
    check_api_command
)
from src.handlers.advanced_handlers import (
    processes_command,
    network_command,
    temperature_command,
    schedule_command,
    browse_command,
    search_command,
    updates_command,
    backup_command,
    quickreboot_command,
    reboot_command,
    sleep_command,
    wakeup_command,
    quota_command,
    schedule_callback,
    browse_callback,
    power_callback
)
from src.utils.logger import setup_logging

async def shutdown(application: Application) -> None:
    """Корректное завершение работы бота"""
    logger = logging.getLogger(__name__)
    logger.info("Stopping Synology Power Control Bot...")
    
    # Останавливаем прием обновлений
    await application.stop()
    logger.info("Bot stopped successfully")

def signal_handler(sig, frame, application=None):
    """Обработчик сигналов для корректного завершения"""
    logger = logging.getLogger(__name__)
    logger.info(f"Received signal {sig}, shutting down gracefully")
    
    if application:
        # Создаем и запускаем задачу завершения в event loop
        loop = asyncio.get_event_loop()
        if loop.is_running():
            loop.create_task(shutdown(application))
        else:
            loop.run_until_complete(shutdown(application))
    
    sys.exit(0)

def main() -> None:
    """Основная функция запуска бота"""
    # Настройка логирования
    setup_logging()
    logger = logging.getLogger(__name__)
    
    # Проверка наличия токена
    if not TELEGRAM_TOKEN:
        logger.error("Telegram token is not set! Please configure TELEGRAM_TOKEN in .env file.")
        return
    
    # Создание и настройка приложения бота
    logger.info("Starting Synology Power Control Bot")
    application = Application.builder().token(TELEGRAM_TOKEN).build()
    
    # Регистрация обработчиков команд
    application.add_handler(CommandHandler("start", start_command))
    application.add_handler(CommandHandler("help", help_command))
    application.add_handler(CommandHandler("status", status_command))
    application.add_handler(CommandHandler("power", power_command))
    
    # Регистрация расширенных обработчиков команд
    application.add_handler(CommandHandler("storage", storage_command))
    application.add_handler(CommandHandler("shares", shares_command))
    application.add_handler(CommandHandler("system", system_command))
    application.add_handler(CommandHandler("load", load_command))
    application.add_handler(CommandHandler("security", security_command))
    application.add_handler(CommandHandler("checkapi", check_api_command))
    
    # Регистрация продвинутых обработчиков команд
    application.add_handler(CommandHandler("processes", processes_command))
    application.add_handler(CommandHandler("network", network_command))
    application.add_handler(CommandHandler("temperature", temperature_command))
    application.add_handler(CommandHandler("schedule", schedule_command))
    application.add_handler(CommandHandler("browse", browse_command))
    application.add_handler(CommandHandler("search", search_command))
    application.add_handler(CommandHandler("updates", updates_command))
    application.add_handler(CommandHandler("backup", backup_command))
    application.add_handler(CommandHandler("quickreboot", quickreboot_command))
    application.add_handler(CommandHandler("wakeup", wakeup_command))
    application.add_handler(CommandHandler("quota", quota_command))
    
    # Регистрация обработчика callback-запросов
    application.add_handler(CallbackQueryHandler(power_callback))
    application.add_handler(CallbackQueryHandler(schedule_callback, pattern="^schedule_"))
    application.add_handler(CallbackQueryHandler(browse_callback, pattern="^browse_"))
    
    # Настройка обработчиков сигналов для корректного завершения
    signal.signal(signal.SIGINT, lambda sig, frame: signal_handler(sig, frame, application))
    signal.signal(signal.SIGTERM, lambda sig, frame: signal_handler(sig, frame, application))
    
    # Запуск бота
    logger.info("Bot started. Press Ctrl+C to stop.")
    application.run_polling(allowed_updates=["message", "callback_query"])
    
if __name__ == "__main__":
    main()
