import pytest
from modules.message_studio.renderer import TemplateRenderer, DEFAULT_SYSTEM_TEMPLATES


def test_variable_interpolation():
    template = "Hello {first_name}! Your username is @{username} and balance is ₹{balance} on {plan_name} plan."
    vars_dict = {
        "first_name": "Aarav",
        "username": "aarav_bot",
        "balance": "1499",
        "plan_name": "Pro VIP",
    }
    rendered = TemplateRenderer.interpolate_text(template, vars_dict)
    assert rendered == "Hello Aarav! Your username is @aarav_bot and balance is ₹1499 on Pro VIP plan."


def test_missing_variables_fallback():
    template = "Welcome {first_name}! Token balance: {balance}"
    rendered = TemplateRenderer.interpolate_text(template, {})
    # Falls back to standard defaults
    assert rendered == "Welcome User! Token balance: 0"


def test_keyboard_matrix_ordering():
    buttons = [
        {"text": "Row 1 Col 0", "button_type": "callback_data", "action_value": "act:1", "row_position": 1, "column_position": 0, "sort_order": 0},
        {"text": "Row 0 Col 1", "button_type": "callback_data", "action_value": "act:0_1", "row_position": 0, "column_position": 1, "sort_order": 1},
        {"text": "Row 0 Col 0", "button_type": "callback_data", "action_value": "act:0_0", "row_position": 0, "column_position": 0, "sort_order": 0},
        {"text": "Row 1 Col 1", "button_type": "callback_data", "action_value": "act:2", "row_position": 1, "column_position": 1, "sort_order": 0},
    ]
    matrix = TemplateRenderer.build_keyboard_matrix(buttons)

    # Must produce 2 rows
    assert len(matrix) == 2
    # Row 0 has 2 buttons in correct order
    assert matrix[0][0]["text"] == "Row 0 Col 0"
    assert matrix[0][1]["text"] == "Row 0 Col 1"
    # Row 1 has 2 buttons
    assert matrix[1][0]["text"] == "Row 1 Col 0"
    assert matrix[1][1]["text"] == "Row 1 Col 1"


def test_aiogram_keyboard_generation():
    buttons = [
        {"text": "💎 Buy Premium", "button_type": "callback_data", "action_value": "buy_prem", "row_position": 0, "column_position": 0, "sort_order": 0},
        {"text": "🌐 Website", "button_type": "url", "action_value": "https://example.com", "row_position": 1, "column_position": 0, "sort_order": 0},
    ]
    kb = TemplateRenderer.to_aiogram_keyboard(buttons)
    assert kb is not None
    assert len(kb.inline_keyboard) == 2
    assert kb.inline_keyboard[0][0].text == "💎 Buy Premium"
    assert kb.inline_keyboard[0][0].callback_data == "buy_prem"
    assert kb.inline_keyboard[1][0].text == "🌐 Website"
    assert kb.inline_keyboard[1][0].url == "https://example.com"


def test_default_system_templates():
    assert "welcome" in DEFAULT_SYSTEM_TEMPLATES
    assert "help" in DEFAULT_SYSTEM_TEMPLATES
    assert "profile" in DEFAULT_SYSTEM_TEMPLATES

    welcome = DEFAULT_SYSTEM_TEMPLATES["welcome"]
    assert "Buy Premium" in welcome["buttons"][0]["text"]
