# remottxrea/bot/command_registry.py

from .handlers.add_account import AddAccountHandler
from .handlers.change_name import ChangeNameHandler
from .handlers.change_photo import ChangePhotoHandler
from .handlers.join_leave import JoinLeaveHandler
from .handlers.list_account import AccountOverviewHandler
from .handlers.start import Start

from ..runner.multi_session_runner import MultiSessionRunner


class CommandRegistry:

    def __init__(self):

        self.runner = MultiSessionRunner()

        # handlers
        self.add_account = AddAccountHandler()
        self.change_name = ChangeNameHandler(self.runner)
        self.change_photo = ChangePhotoHandler(self.runner)
        self.join_leave = JoinLeaveHandler(self.runner)
        self.list_accounts = AccountOverviewHandler(self.runner)
        self.start_bot = Start()

        # command map
        self.command_map = {
            "start": self.start_bot,
            "addaccount": self.add_account,
            "listacc": self.list_accounts,
            "changefname": self.change_name,
            "changename": self.change_name,
            "changephoto": self.change_photo,
            "join": self.join_leave,
            "leave": self.join_leave,
        }

    # --------------------------------------------------
    def resolve(self, message):

        if not message or not message.text:
            return None

        text = message.text.strip()
        user_id = message.from_user.id

        # ============================================
        # 1️⃣ If user is in addaccount state → route to it
        # ============================================
        if user_id in self.add_account.states:
            return self.add_account

        # ============================================
        # 2️⃣ Otherwise try to resolve command
        # ============================================
        command = text.split(" ", 1)[0].lower()

        if command.startswith("/"):
            command = command[1:]

        if "@" in command:
            command = command.split("@", 1)[0]

        return self.command_map.get(command)