from enum import Enum
from typing import Any, Optional, Sequence
from modules.message_studio.unicode_styler import UnicodeStyler, TextStyle


class BoxStyle(str, Enum):
    DOUBLE = "double"
    SINGLE = "single"
    ROUNDED = "rounded"
    HEAVY = "heavy"
    ASCII = "ascii"


BOX_BORDER_CHARS = {
    BoxStyle.DOUBLE: {
        "tl": "╔", "tr": "╗", "bl": "╚", "br": "╝",
        "h": "═", "v": "║",
    },
    BoxStyle.SINGLE: {
        "tl": "┌", "tr": "┐", "bl": "└", "br": "┘",
        "h": "─", "v": "│",
    },
    BoxStyle.ROUNDED: {
        "tl": "╭", "tr": "╮", "bl": "╰", "br": "╯",
        "h": "─", "v": "│",
    },
    BoxStyle.HEAVY: {
        "tl": "┏", "tr": "┓", "bl": "┗", "br": "┛",
        "h": "━", "v": "┃",
    },
    BoxStyle.ASCII: {
        "tl": "+", "tr": "+", "bl": "+", "br": "+",
        "h": "-", "v": "|",
    },
}

SEPARATOR_PRESETS = {
    "invoice": "✫▰▱▰▱▰▱▰▱▰▱✫",
    "diamonds": "⬥───⬥───⬥───⬥",
    "stars": "★━━━━━━━━★",
    "dots": "•┈┈┈••✦••┈┈┈•",
    "double_line": "══════════════════",
    "single_line": "──────────────────",
    "bars": "▰▰▰▰▰▰▰▰▰▰",
    "blocks": "██████████████████",
    "arrows": "»»————- -————««",
}


class MessageFormatter:
    """
    Constructs Telegram-optimized decorative elements:
    - Header boxes (open banner or full framed)
    - Stylized separators
    - Bulleted info tables with small-caps keys
    """

    @classmethod
    def build_box(
        cls,
        title: str,
        style: BoxStyle | str = BoxStyle.DOUBLE,
        width: int = 20,
        bordered: bool = False,
        auto_small_caps: bool = True,
    ) -> str:
        """
        Generates a stylized box header.
        If bordered=False:
            ╔══════════════════╗
                💎 ᴘʀᴇᴍɪᴜᴍ ᴍᴇɴᴜ
            ╚══════════════════╝
        If bordered=True:
            ╔══════════════════╗
            ║  💎 ᴘʀᴇᴍɪᴜᴍ ᴍᴇɴᴜ  ║
            ╚══════════════════╝
        """
        if isinstance(style, str):
            style = BoxStyle(style)

        chars = BOX_BORDER_CHARS.get(style, BOX_BORDER_CHARS[BoxStyle.DOUBLE])

        # Style inner text if requested
        formatted_title = UnicodeStyler.to_small_caps(title) if auto_small_caps else title

        # Ensure width is at least longer than title + 4
        title_visual_len = len(formatted_title)
        effective_width = max(width, title_visual_len + 4)

        bar_len = effective_width - 2
        top_line = f"{chars['tl']}{chars['h'] * bar_len}{chars['tr']}"
        bottom_line = f"{chars['bl']}{chars['h'] * bar_len}{chars['br']}"

        if bordered:
            pad_total = bar_len - title_visual_len
            pad_left = pad_total // 2
            pad_right = pad_total - pad_left
            middle_line = f"{chars['v']}{' ' * pad_left}{formatted_title}{' ' * pad_right}{chars['v']}"
        else:
            # Banner style with clean indentation
            middle_line = f"   {formatted_title}"

        return f"{top_line}\n{middle_line}\n{bottom_line}"

    @classmethod
    def build_separator(
        cls,
        preset: str = "invoice",
        length: int = 10,
        custom_char: Optional[str] = None,
    ) -> str:
        """
        Returns a decorative separator line.
        """
        if preset in SEPARATOR_PRESETS:
            return SEPARATOR_PRESETS[preset]

        if custom_char:
            return custom_char * length

        # Default fallback
        return SEPARATOR_PRESETS["invoice"]

    @classmethod
    def format_info_item(
        cls,
        key: str,
        value: Any,
        symbol: str = "❍",
        key_style: Optional[str] = "small_caps",
        separator: str = " : ",
    ) -> str:
        """
        Formats a single key-value line.
        Example: `❍ ɴᴀᴍᴇ : {first_name}` or `❍ sᴛᴀᴛᴜs : 🟢 ᴀᴄᴛɪᴠᴇ`
        """
        if key_style == "small_caps":
            styled_key = UnicodeStyler.to_small_caps(str(key))
        elif key_style:
            styled_key = UnicodeStyler.style_text(str(key), key_style)
        else:
            styled_key = str(key)

        return f"{symbol} {styled_key}{separator}{value}"

    @classmethod
    def format_info_block(
        cls,
        items: Sequence[tuple[str, Any]] | dict[str, Any],
        symbol: str = "❍",
        key_style: Optional[str] = "small_caps",
        separator: str = " : ",
    ) -> str:
        """
        Formats a block of key-value pairs into a clean vertical list.
        """
        lines = []
        if isinstance(items, dict):
            iterable = items.items()
        else:
            iterable = items

        for k, v in iterable:
            lines.append(cls.format_info_item(k, v, symbol=symbol, key_style=key_style, separator=separator))

        return "\n".join(lines)
