from enum import Enum
import math
from typing import Any, Optional, Sequence
from modules.message_studio.formatter import MessageFormatter, BoxStyle
from modules.message_studio.unicode_styler import UnicodeStyler


class ProgressBarStyle(str, Enum):
    BLOCKS = "blocks"      # █ and ░ -> [██░░░░░░░░] 20%
    SMOOTH = "smooth"      # ▰ and ▱ -> [▰▰▱▱▱▱▱▱▱▱] 20%
    CIRCLES = "circles"    # ● and ○ -> [●●○○○○○○○○] 20%
    SQUARES = "squares"    # ■ and □ -> [■■□□□□□□□□] 20%
    ASCII = "ascii"        # = and - -> [==--------] 20%


PROGRESS_BAR_CHARS = {
    ProgressBarStyle.BLOCKS: {"filled": "█", "empty": "░"},
    ProgressBarStyle.SMOOTH: {"filled": "▰", "empty": "▱"},
    ProgressBarStyle.CIRCLES: {"filled": "●", "empty": "○"},
    ProgressBarStyle.SQUARES: {"filled": "■", "empty": "□"},
    ProgressBarStyle.ASCII: {"filled": "=", "empty": "-"},
}


class TemplateEngine:
    """
    High-level generator for Telegram template components:
    - Progress bars and multi-step progress headers
    - Complete multi-part stylized message structures
    """

    @classmethod
    def generate_progress_bar(
        cls,
        percent: float | int,
        length: int = 10,
        style: ProgressBarStyle | str = ProgressBarStyle.BLOCKS,
        show_percent: bool = True,
        brackets: bool = True,
        filled_char: Optional[str] = None,
        empty_char: Optional[str] = None,
    ) -> str:
        """
        Generates an aesthetic Unicode progress bar.
        Example: `[██░░░░░░░░] 20%` or `[▰▰▱▱▱▱▱▱▱▱] 20%`
        """
        if isinstance(style, str):
            style = ProgressBarStyle(style)

        char_config = PROGRESS_BAR_CHARS.get(style, PROGRESS_BAR_CHARS[ProgressBarStyle.BLOCKS])
        f_char = filled_char or char_config["filled"]
        e_char = empty_char or char_config["empty"]

        clamped = max(0.0, min(100.0, float(percent)))
        filled_count = int(round((clamped / 100.0) * length))
        empty_count = max(0, length - filled_count)

        bar = f"{f_char * filled_count}{e_char * empty_count}"

        if brackets:
            bar = f"[{bar}]"

        if show_percent:
            int_pct = int(round(clamped))
            return f"{bar} {int_pct}%"

        return bar

    @classmethod
    def format_progress_step(
        cls,
        step: int,
        total_steps: int,
        title: str = "Processing...",
        icon: str = "📦",
        auto_small_caps: bool = True,
    ) -> str:
        """
        Generates step header:
        Example: `📦 sᴛᴇᴘ 1/4 : ᴘʀᴏᴄᴇssɪɴɢ...`
        """
        step_word = UnicodeStyler.to_small_caps("step") if auto_small_caps else "STEP"
        styled_title = UnicodeStyler.to_small_caps(title) if auto_small_caps else title

        return f"{icon} {step_word} {step}/{total_steps} : {styled_title}"


class TelegramMessageBuilder:
    """
    Fluent builder to easily assemble Telegram messages with boxes, separators,
    progress indicators, info items, and callouts.
    """

    def __init__(self):
        self._sections: list[str] = []

    def add_box_header(
        self,
        title: str,
        style: BoxStyle | str = BoxStyle.DOUBLE,
        width: int = 20,
        bordered: bool = False,
        auto_small_caps: bool = True,
    ) -> "TelegramMessageBuilder":
        box = MessageFormatter.build_box(
            title=title,
            style=style,
            width=width,
            bordered=bordered,
            auto_small_caps=auto_small_caps,
        )
        self._sections.append(box)
        return self

    def add_separator(self, preset: str = "invoice") -> "TelegramMessageBuilder":
        sep = MessageFormatter.build_separator(preset=preset)
        self._sections.append(sep)
        return self

    def add_info_block(
        self,
        items: Sequence[tuple[str, Any]] | dict[str, Any],
        symbol: str = "❍",
        key_style: str = "small_caps",
    ) -> "TelegramMessageBuilder":
        block = MessageFormatter.format_info_block(items, symbol=symbol, key_style=key_style)
        self._sections.append(block)
        return self

    def add_progress_bar(
        self,
        percent: float | int,
        length: int = 10,
        style: ProgressBarStyle | str = ProgressBarStyle.BLOCKS,
        step: Optional[int] = None,
        total_steps: Optional[int] = None,
        step_title: str = "Processing...",
    ) -> "TelegramMessageBuilder":
        parts = []
        if step is not None and total_steps is not None:
            parts.append(TemplateEngine.format_progress_step(step, total_steps, title=step_title))
        parts.append(TemplateEngine.generate_progress_bar(percent=percent, length=length, style=style))
        self._sections.append("\n".join(parts))
        return self

    def add_text(self, text: str) -> "TelegramMessageBuilder":
        self._sections.append(text)
        return self

    def build(self, separator: str = "\n\n") -> str:
        return separator.join(s for s in self._sections if s.strip())
