# app/src/telegram/live/active_screen.py

from __future__ import annotations

from dataclasses import dataclass

from aiogram import Bot
from aiogram.types import Message

from src.telegram.live.runner import LiveScreenRunner, ScreenRegistry
from src.trading.auto.runner import AutoTradeRunner
from src.trading.debug.runner import DebugTradeRunner


@dataclass(slots=True)
class ActiveScreen:
    screen: str
    chat_id: int
    message_id: int


class ActiveScreenManager:
    _screens: dict[int, ActiveScreen] = {}

    @classmethod
    async def prepare_new_screen(
        cls,
        *,
        screen: str,
        bot: Bot,
        chat_id: int,
        keep_message_id: int | None = None,
    ) -> None:
        previous = cls._screens.get(chat_id)

        await AutoTradeRunner.detach_screen(
            delete_message=True,
            bot=bot,
            chat_id=chat_id,
            keep_message_id=keep_message_id,
        )

        await DebugTradeRunner.detach_screen(
            delete_message=True,
            bot=bot,
            chat_id=chat_id,
            keep_message_id=keep_message_id,
        )

        await LiveScreenRunner.delete_chat_screens(
            bot=bot,
            chat_id=chat_id,
            keep_message_id=keep_message_id,
        )

        await ScreenRegistry.delete_chat_screens(
            bot=bot,
            chat_id=chat_id,
            keep_message_id=keep_message_id,
        )

        if previous is not None:
            if keep_message_id is None or previous.message_id != keep_message_id:
                try:
                    await bot.delete_message(
                        chat_id=previous.chat_id,
                        message_id=previous.message_id,
                    )
                except Exception:
                    pass

        cls._screens.pop(chat_id, None)

    @classmethod
    def register(
        cls,
        *,
        screen: str,
        message: Message,
    ) -> None:
        cls._screens[message.chat.id] = ActiveScreen(
            screen=screen,
            chat_id=message.chat.id,
            message_id=message.message_id,
        )

    @classmethod
    def unregister(
        cls,
        *,
        chat_id: int,
        message_id: int,
    ) -> None:
        current = cls._screens.get(chat_id)

        if current is None:
            return

        if current.message_id == message_id:
            cls._screens.pop(chat_id, None)