from enum import Enum
import re
from typing import Optional


class TextStyle(str, Enum):
    SMALL_CAPS = "small_caps"
    SANS_BOLD = "sans_bold"
    SERIF_BOLD = "serif_bold"
    SANS_ITALIC = "sans_italic"
    MONOSPACE = "monospace"
    DOUBLE_STRUCK = "double_struck"


# Small Caps mapping (Latin letters A-Z and a-z map to Unicode Small Capitals)
SMALL_CAPS_MAP: dict[str, str] = {
    "a": "ᴀ", "b": "ʙ", "c": "ᴄ", "d": "ᴅ", "e": "ᴇ",
    "f": "ғ", "g": "ɢ", "h": "ʜ", "i": "ɪ", "j": "ᴊ",
    "k": "ᴋ", "l": "ʟ", "m": "ᴍ", "n": "ɴ", "o": "ᴏ",
    "p": "ᴘ", "q": "ǫ", "r": "ʀ", "s": "s", "t": "ᴛ",
    "u": "ᴜ", "v": "ᴠ", "w": "ᴡ", "x": "x", "y": "ʏ", "z": "ᴢ",
    "A": "ᴀ", "B": "ʙ", "C": "ᴄ", "D": "ᴅ", "E": "ᴇ",
    "F": "ғ", "G": "ɢ", "H": "ʜ", "I": "ɪ", "J": "ᴊ",
    "K": "ᴋ", "L": "ʟ", "M": "ᴍ", "N": "ɴ", "O": "ᴏ",
    "P": "ᴘ", "Q": "ǫ", "R": "ʀ", "S": "s", "T": "ᴛ",
    "U": "ᴜ", "V": "ᴠ", "W": "ᴡ", "X": "x", "Y": "ʏ", "Z": "ᴢ",
}

# Mathematical Sans-Serif Bold mapping
SANS_BOLD_MAP: dict[str, str] = {
    chr(ord("A") + i): chr(0x1D5D4 + i) for i in range(26)
}
SANS_BOLD_MAP.update({
    chr(ord("a") + i): chr(0x1D5EE + i) for i in range(26)
})
SANS_BOLD_MAP.update({
    chr(ord("0") + i): chr(0x1D7EC + i) for i in range(10)
})

# Mathematical Serif Bold mapping
SERIF_BOLD_MAP: dict[str, str] = {
    chr(ord("A") + i): chr(0x1D400 + i) for i in range(26)
}
SERIF_BOLD_MAP.update({
    chr(ord("a") + i): chr(0x1D41A + i) for i in range(26)
})
SERIF_BOLD_MAP.update({
    chr(ord("0") + i): chr(0x1D7CE + i) for i in range(10)
})

# Mathematical Sans-Serif Italic mapping
SANS_ITALIC_MAP: dict[str, str] = {
    chr(ord("A") + i): chr(0x1D608 + i) for i in range(26)
}
SANS_ITALIC_MAP.update({
    chr(ord("a") + i): chr(0x1D622 + i) for i in range(26)
})

# Mathematical Monospace mapping
MONOSPACE_MAP: dict[str, str] = {
    chr(ord("A") + i): chr(0x1D670 + i) for i in range(26)
}
MONOSPACE_MAP.update({
    chr(ord("a") + i): chr(0x1D68A + i) for i in range(26)
})
MONOSPACE_MAP.update({
    chr(ord("0") + i): chr(0x1D7F6 + i) for i in range(10)
})

# Double-Struck (Blackboard bold)
DOUBLE_STRUCK_MAP: dict[str, str] = {
    "C": "\u2102", "H": "\u210D", "N": "\u2115", "P": "\u2119",
    "Q": "\u211A", "R": "\u211D", "Z": "\u2124",
}
for i in range(26):
    char = chr(ord("A") + i)
    if char not in DOUBLE_STRUCK_MAP:
        DOUBLE_STRUCK_MAP[char] = chr(0x1D538 + i)
for i in range(26):
    char = chr(ord("a") + i)
    DOUBLE_STRUCK_MAP[char] = chr(0x1D552 + i)
for i in range(10):
    char = chr(ord("0") + i)
    DOUBLE_STRUCK_MAP[char] = chr(0x1D7D8 + i)

STYLE_TABLES: dict[TextStyle, dict[str, str]] = {
    TextStyle.SMALL_CAPS: SMALL_CAPS_MAP,
    TextStyle.SANS_BOLD: SANS_BOLD_MAP,
    TextStyle.SERIF_BOLD: SERIF_BOLD_MAP,
    TextStyle.SANS_ITALIC: SANS_ITALIC_MAP,
    TextStyle.MONOSPACE: MONOSPACE_MAP,
    TextStyle.DOUBLE_STRUCK: DOUBLE_STRUCK_MAP,
}

# Catalog of decorative Unicode symbols for bot designs
UNICODE_SYMBOLS: dict[str, list[str]] = {
    "stars": ["✫", "★", "✦", "✧", "✬", "✭", "✮", "✯"],
    "bullets": ["❍", "⬥", "●", "○", "◉", "⦿", "•", "▪", "▫", "◆", "◇"],
    "bars": ["▰", "▱", "█", "░", "▒", "▓", "▌", "▐", "■", "□"],
    "arrows": ["👇", "👉", "►", "◄", "▲", "▼", "»", "«", "➔", "➜"],
    "indicators": ["🟢", "🔴", "🟡", "🔵", "⚪", "⚫", "✔", "✖", "⚡"],
    "commerce": ["💎", "💳", "👑", "📦", "🏷️", "💰", "🧾", "🚀", "🎁", "🔥"],
}


class UnicodeStyler:
    """
    Converts plain text into decorative Unicode font representations.
    Protects HTML tags and template variables from being mutated during transformation.
    """

    @classmethod
    def to_small_caps(
        cls,
        text: str,
        preserve_tags: bool = True,
        preserve_variables: bool = True,
    ) -> str:
        return cls.style_text(
            text,
            style=TextStyle.SMALL_CAPS,
            preserve_tags=preserve_tags,
            preserve_variables=preserve_variables,
        )

    @classmethod
    def style_text(
        cls,
        text: str,
        style: TextStyle | str,
        preserve_tags: bool = True,
        preserve_variables: bool = True,
    ) -> str:
        if isinstance(style, str):
            style = TextStyle(style)

        char_map = STYLE_TABLES.get(style)
        if not char_map:
            return text

        if not preserve_tags and not preserve_variables:
            return "".join(char_map.get(ch, ch) for ch in text)

        # Build regex to identify protected tokens:
        # 1. HTML tags: <[^>]+>
        # 2. Template variables: \{[a-zA-Z0-9_]+\}
        patterns = []
        if preserve_tags:
            patterns.append(r"<[^>]+>")
        if preserve_variables:
            patterns.append(r"\{[a-zA-Z0-9_]+\}")

        combined_pattern = re.compile("|".join(patterns))

        last_end = 0
        output_parts: list[str] = []

        for match in combined_pattern.finditer(text):
            start, end = match.span()
            # Transform text before the protected token
            if start > last_end:
                unprotected = text[last_end:start]
                output_parts.append("".join(char_map.get(ch, ch) for ch in unprotected))
            # Append protected token untouched
            output_parts.append(match.group(0))
            last_end = end

        # Transform remaining text
        if last_end < len(text):
            unprotected = text[last_end:]
            output_parts.append("".join(char_map.get(ch, ch) for ch in unprotected))

        return "".join(output_parts)

    @classmethod
    def get_available_styles(cls) -> list[str]:
        return [s.value for s in TextStyle]

    @classmethod
    def get_symbol_catalog(cls) -> dict[str, list[str]]:
        return UNICODE_SYMBOLS
