from typing import Any, Sequence
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
from core.exceptions import ValidationError
from modules.message_studio.models import BotMessageButton
from modules.message_studio.schemas import ButtonSchema


class ButtonGridBuilder:
    """
    Constructs, validates, and formats Telegram inline keyboards into row/column matrices.
    """

    MAX_CALLBACK_BYTES = 64
    ALLOWED_BUTTON_TYPES = {"callback_data", "url", "web_app", "switch_inline_query"}

    def __init__(self):
        self._buttons: list[ButtonSchema] = []

    def add_button(
        self,
        text: str,
        button_type: str,
        action_value: str,
        row_position: int = 0,
        column_position: int = 0,
        sort_order: int = 0,
    ) -> "ButtonGridBuilder":
        if button_type not in self.ALLOWED_BUTTON_TYPES:
            raise ValidationError(f"Invalid button type '{button_type}'. Allowed: {self.ALLOWED_BUTTON_TYPES}")

        if button_type == "callback_data":
            byte_len = len(action_value.encode("utf-8"))
            if byte_len > self.MAX_CALLBACK_BYTES:
                raise ValidationError(
                    f"Callback data exceeds Telegram 64-byte limit: got {byte_len} bytes ('{action_value}')"
                )

        if button_type in ("url", "web_app"):
            if not (action_value.startswith("http://") or action_value.startswith("https://") or action_value.startswith("tg://")):
                raise ValidationError(f"URL or Web App must start with http://, https://, or tg://")

        self._buttons.append(
            ButtonSchema(
                text=text,
                button_type=button_type,  # type: ignore[arg-type]
                action_value=action_value,
                row_position=row_position,
                column_position=column_position,
                sort_order=sort_order,
            )
        )
        return self

    def add_callback_button(self, text: str, callback_data: str, row: int = 0, col: int = 0) -> "ButtonGridBuilder":
        return self.add_button(text, "callback_data", callback_data, row_position=row, column_position=col)

    def add_url_button(self, text: str, url: str, row: int = 0, col: int = 0) -> "ButtonGridBuilder":
        return self.add_button(text, "url", url, row_position=row, column_position=col)

    def to_schemas(self) -> list[ButtonSchema]:
        return list(self._buttons)

    @classmethod
    def build_matrix(
        cls,
        buttons: Sequence[BotMessageButton | ButtonSchema | dict[str, Any]],
    ) -> list[list[dict[str, str]]]:
        """
        Organizes a flat sequence of buttons into a 2D grid ordered by row_position, column_position, sort_order.
        """
        rows: dict[int, list[tuple[int, int, dict[str, str]]]] = {}

        for btn in buttons:
            if isinstance(btn, (BotMessageButton, ButtonSchema)):
                b_text = btn.text
                b_type = btn.button_type
                b_val = btn.action_value
                r_pos = btn.row_position
                c_pos = btn.column_position
                s_order = btn.sort_order
            else:
                b_text = btn.get("text", "")
                b_type = btn.get("button_type", "callback_data")
                b_val = btn.get("action_value", "")
                r_pos = btn.get("row_position", 0)
                c_pos = btn.get("column_position", 0)
                s_order = btn.get("sort_order", 0)

            if r_pos not in rows:
                rows[r_pos] = []

            btn_dict = {
                "text": b_text,
                "button_type": b_type,
                "action_value": b_val,
            }
            rows[r_pos].append((c_pos, s_order, btn_dict))

        # Sort rows by row_position, then within each row sort by column_position and sort_order
        sorted_matrix: list[list[dict[str, str]]] = []
        for r in sorted(rows.keys()):
            row_items = sorted(rows[r], key=lambda x: (x[0], x[1]))
            sorted_matrix.append([item[2] for item in row_items])

        return sorted_matrix

    @classmethod
    def to_aiogram(
        cls,
        buttons: Sequence[BotMessageButton | ButtonSchema | dict[str, Any]],
    ) -> InlineKeyboardMarkup | None:
        """Converts buttons to Aiogram InlineKeyboardMarkup."""
        matrix = cls.build_matrix(buttons)
        if not matrix:
            return None

        keyboard_rows: list[list[InlineKeyboardButton]] = []
        for row in matrix:
            aiogram_row: list[InlineKeyboardButton] = []
            for b in row:
                b_text = b["text"]
                b_type = b["button_type"]
                b_val = b["action_value"]

                if b_type == "url":
                    btn = InlineKeyboardButton(text=b_text, url=b_val)
                elif b_type == "web_app":
                    btn = InlineKeyboardButton(text=b_text, web_app=WebAppInfo(url=b_val))
                elif b_type == "switch_inline_query":
                    btn = InlineKeyboardButton(text=b_text, switch_inline_query_current_chat=b_val)
                else:
                    btn = InlineKeyboardButton(text=b_text, callback_data=b_val)
                aiogram_row.append(btn)
            keyboard_rows.append(aiogram_row)

        return InlineKeyboardMarkup(inline_keyboard=keyboard_rows)
