import pytest
from core.exceptions import ValidationError
from modules.message_studio.validators import MessageValidator
from modules.message_studio.presets_manager import PresetManager


def test_html_validator_valid():
    valid_html = "<b>Hello</b> <i>World</i> <code>code</code> <a href=\"https://t.me\">link</a>"
    MessageValidator.validate_html(valid_html)

    emoji_html = "<tg-emoji emoji-id=\"5368324170671202286\">🐸</tg-emoji>"
    MessageValidator.validate_html(emoji_html)


def test_html_validator_invalid_tags():
    with pytest.raises(ValidationError, match="Disallowed HTML tag '<script>'"):
        MessageValidator.validate_html("<script>alert(1)</script>")

    with pytest.raises(ValidationError, match="Disallowed HTML tag '<div>'"):
        MessageValidator.validate_html("<div>Text</div>")


def test_html_validator_unclosed_tags():
    with pytest.raises(ValidationError, match="Unclosed HTML tags"):
        MessageValidator.validate_html("<b>Bold and <i>italic")

    with pytest.raises(ValidationError, match="Mismatched HTML tags"):
        MessageValidator.validate_html("<b>Bold and <i>italic</b>")


def test_message_length_validator():
    # 4096 chars ok for text
    ok_text = "A" * 4000
    MessageValidator.validate_length(ok_text, media_type="none")

    # >4096 chars fails for text
    too_long = "A" * 4097
    with pytest.raises(ValidationError, match="exceeds Telegram limit of 4096"):
        MessageValidator.validate_length(too_long, media_type="none")

    # >1024 chars fails for photo caption
    too_long_caption = "A" * 1025
    with pytest.raises(ValidationError, match="exceeds Telegram limit of 1024"):
        MessageValidator.validate_length(too_long_caption, media_type="photo")


def test_callback_data_validator():
    MessageValidator.validate_callback_data("action:buy_premium")

    too_long_callback = "A" * 65
    with pytest.raises(ValidationError, match="exceeds 64-byte"):
        MessageValidator.validate_callback_data(too_long_callback)


def test_preset_manager_loads_all_presets():
    presets = PresetManager.list_presets()
    assert len(presets) >= 6

    preset_keys = {p.key for p in presets}
    assert "premium_box" in preset_keys
    assert "payment_invoice" in preset_keys
    assert "progress_bar" in preset_keys
    assert "success" in preset_keys
    assert "error" in preset_keys
    assert "welcome" in preset_keys

    invoice = PresetManager.get_preset("payment_invoice")
    assert "💳 ᴘᴀʏᴍᴇɴᴛ ɪɴᴠᴏɪᴄᴇ" in invoice.message_text
    assert "✫▰▱▰▱▰▱▰▱▰▱✫" in invoice.message_text
    assert len(invoice.buttons) >= 4
