import html.parser
import re
from typing import Optional
from core.exceptions import ValidationError

TELEGRAM_MAX_TEXT_LENGTH = 4096
TELEGRAM_MAX_CAPTION_LENGTH = 1024
TELEGRAM_MAX_CALLBACK_BYTES = 64

# Tags supported by Telegram HTML Parser
ALLOWED_HTML_TAGS = {
    "b", "strong", "i", "em", "u", "ins", "s", "strike", "del",
    "tg-spoiler", "span", "a", "code", "pre", "tg-emoji", "blockquote",
}


class _TelegramHTMLValidator(html.parser.HTMLParser):
    def __init__(self):
        super().__init__()
        self.tag_stack: list[str] = []
        self.errors: list[str] = []

    def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]):
        lower_tag = tag.lower()
        if lower_tag not in ALLOWED_HTML_TAGS:
            self.errors.append(f"Disallowed HTML tag '<{tag}>' for Telegram.")
            return

        # Specific attribute checks
        if lower_tag == "a":
            href_found = any(k == "href" and v for k, v in attrs)
            if not href_found:
                self.errors.append("Tag '<a>' is missing 'href' attribute.")
        elif lower_tag == "tg-emoji":
            emoji_id_found = any(k in ("emoji-id", "id") and v for k, v in attrs)
            if not emoji_id_found:
                self.errors.append("Tag '<tg-emoji>' is missing 'emoji-id' attribute.")

        self.tag_stack.append(lower_tag)

    def handle_endtag(self, tag: str):
        lower_tag = tag.lower()
        if not self.tag_stack:
            self.errors.append(f"Unexpected closing tag '</{tag}>' without matching opening tag.")
            return

        expected = self.tag_stack.pop()
        if expected != lower_tag:
            self.errors.append(
                f"Mismatched HTML tags: expected '</{expected}>', but got '</{tag}>'."
            )


class MessageValidator:
    """
    Validates Telegram message length, HTML syntax balance, and button constraints.
    """

    @classmethod
    def validate_length(cls, text: str, media_type: str = "none") -> None:
        """
        Validates text length against Telegram API limits:
        - 4096 chars for text-only messages
        - 1024 chars for media captions (photo, video, document, animation)
        """
        limit = (
            TELEGRAM_MAX_CAPTION_LENGTH
            if media_type and media_type != "none"
            else TELEGRAM_MAX_TEXT_LENGTH
        )
        current_len = len(text)
        if current_len > limit:
            raise ValidationError(
                f"Message length ({current_len} chars) exceeds Telegram limit of {limit} characters for media_type='{media_type}'"
            )

    @classmethod
    def validate_html(cls, html_text: str) -> None:
        """
        Validates that Telegram HTML tags are allowed, correctly formed, and balanced.
        """
        if not html_text:
            return

        parser = _TelegramHTMLValidator()
        try:
            parser.feed(html_text)
            parser.close()
        except Exception as e:
            raise ValidationError(f"Invalid HTML structure: {str(e)}")

        if parser.errors:
            raise ValidationError(f"Telegram HTML validation failed: {'; '.join(parser.errors)}")

        if parser.tag_stack:
            unclosed = ", ".join(f"<{t}>" for t in reversed(parser.tag_stack))
            raise ValidationError(f"Unclosed HTML tags detected: {unclosed}")

    @classmethod
    def validate_callback_data(cls, callback_data: str) -> None:
        """
        Ensures callback data does not exceed 64 UTF-8 bytes.
        """
        byte_len = len(callback_data.encode("utf-8"))
        if byte_len > TELEGRAM_MAX_CALLBACK_BYTES:
            raise ValidationError(
                f"Callback data exceeds 64-byte Telegram limit: got {byte_len} bytes ('{callback_data}')"
            )
