import uuid
import pytest
from httpx import AsyncClient
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from infrastructure.telegram.service import TelegramApiService
from infrastructure.telegram.webhook import hash_webhook_secret
from modules.bots.models import BotWebhook


@pytest.mark.asyncio
async def test_message_studio_publishing_changes_real_bot_response(
    async_client: AsyncClient,
    db_session: AsyncSession,
):
    TelegramApiService.clear_mocks()

    # 1. Setup mock bot token and register bot with getMe
    mock_token = f"token_studio_{uuid.uuid4().hex[:8]}_test"
    bot_username = f"studio_test_bot_{uuid.uuid4().hex[:6]}"
    TelegramApiService.register_mock_bot(mock_token, bot_username, "Studio Test Bot")

    # 2. Register Tenant & User
    user_email = f"publisher_{uuid.uuid4().hex[:6]}@example.com"
    reg_resp = await async_client.post(
        "/api/v1/auth/register",
        json={"email": user_email, "password": "PasswordA123!", "full_name": "Publisher Boss"},
    )
    assert reg_resp.status_code == 201
    token = reg_resp.json()["data"]["access_token"]

    tenant_resp = await async_client.post(
        "/api/v1/tenants",
        headers={"Authorization": f"Bearer {token}"},
        json={"name": "Publishing Enterprise", "slug": f"pub-{uuid.uuid4().hex[:6]}"},
    )
    assert tenant_resp.status_code == 201
    tenant_id = tenant_resp.json()["data"]["id"]
    headers = {
        "Authorization": f"Bearer {token}",
        "X-Tenant-ID": str(tenant_id),
    }

    # 3. Register Bot via API
    bot_reg_resp = await async_client.post(
        "/api/v1/bots",
        headers=headers,
        json={"token": mock_token, "name": "Studio Live Bot"},
    )
    assert bot_reg_resp.status_code == 201, bot_reg_resp.text
    bot_id = bot_reg_resp.json()["data"]["id"]

    # Retrieve webhook secret for testing simulated updates
    wh_stmt = select(BotWebhook).where(BotWebhook.bot_id == uuid.UUID(bot_id))
    wh_res = await db_session.execute(wh_stmt)
    webhook_row = wh_res.scalar_one()
    # Inject a known secret hash so we can pass X-Telegram-Bot-Api-Secret-Token
    test_secret = "secret-test-token-12345"
    webhook_row.secret_hash = hash_webhook_secret(test_secret)
    await db_session.commit()

    webhook_headers = {
        "X-Telegram-Bot-Api-Secret-Token": test_secret,
    }

    # 4. Trigger incoming /start update BEFORE creating any custom template
    TelegramApiService.clear_sent_messages()
    update_1 = {
        "update_id": 1001,
        "message": {
            "message_id": 1,
            "from": {"id": 888123, "first_name": "Rahul", "username": "rahul_dev", "language_code": "en"},
            "chat": {"id": 888123, "type": "private"},
            "text": "/start",
        },
    }
    wh_resp_1 = await async_client.post(
        f"/webhooks/telegram/{bot_id}",
        headers=webhook_headers,
        json=update_1,
    )
    assert wh_resp_1.status_code == 200

    sent_1 = TelegramApiService.get_sent_messages()
    assert len(sent_1) == 1
    # Should use the default system welcome template
    assert "Welcome" in sent_1[0]["text"]
    assert "Rahul" in sent_1[0]["text"]

    # 5. Create Custom Message in Message Studio as DRAFT
    custom_draft_payload = {
        "message_key": "welcome",
        "title": "VIP Decorative Welcome",
        "message_text": (
            "╔══════════════════╗\n"
            "   💎 <b>ᴘʀᴇᴍɪᴜᴍ ᴍᴇɴᴜ</b>\n"
            "╚══════════════════╝\n\n"
            "✫▰▱▰▱▰▱▰▱▰▱✫\n"
            "❍ ɴᴀᴍᴇ : {first_name}\n"
            "❍ sᴛᴀᴛᴜs : 🟢 ᴀᴄᴛɪᴠᴇ\n"
            "✫▰▱▰▱▰▱▰▱▰▱✫"
        ),
        "parse_mode": "HTML",
        "locale": "en",
        "is_active": True,
        "is_draft": True,  # Draft! Not published yet
        "buttons": [
            {
                "text": "💎 Buy Premium",
                "button_type": "callback_data",
                "action_value": "act:premium",
                "row_position": 0,
                "column_position": 0,
                "sort_order": 0,
            },
            {
                "text": "👤 My Profile",
                "button_type": "callback_data",
                "action_value": "act:profile",
                "row_position": 1,
                "column_position": 0,
                "sort_order": 0,
            },
            {
                "text": "🌐 Website",
                "button_type": "url",
                "action_value": "https://example.com",
                "row_position": 1,
                "column_position": 1,
                "sort_order": 1,
            },
        ],
    }

    create_resp = await async_client.post(
        f"/api/v1/bots/{bot_id}/messages",
        headers=headers,
        json=custom_draft_payload,
    )
    assert create_resp.status_code == 201, create_resp.text
    template_data = create_resp.json()["data"]
    template_id = template_data["id"]
    assert template_data["is_draft"] is True

    # 6. Incoming /start update while template is DRAFT -> still returns default!
    TelegramApiService.clear_sent_messages()
    update_2 = {
        "update_id": 1002,
        "message": {
            "message_id": 2,
            "from": {"id": 888123, "first_name": "Rahul", "username": "rahul_dev", "language_code": "en"},
            "chat": {"id": 888123, "type": "private"},
            "text": "/start",
        },
    }
    wh_resp_2 = await async_client.post(
        f"/webhooks/telegram/{bot_id}",
        headers=webhook_headers,
        json=update_2,
    )
    assert wh_resp_2.status_code == 200
    sent_2 = TelegramApiService.get_sent_messages()
    assert len(sent_2) == 1
    # Must NOT have decorative box yet
    assert "╔══════════════════╗" not in sent_2[0]["text"]

    # 7. PUBLISH the template!
    pub_resp = await async_client.post(
        f"/api/v1/bots/{bot_id}/messages/{template_id}/publish",
        headers=headers,
    )
    assert pub_resp.status_code == 200
    assert pub_resp.json()["data"]["is_draft"] is False

    # 8. Incoming /start update AFTER PUBLISH -> Real bot response is CHANGED!
    TelegramApiService.clear_sent_messages()
    update_3 = {
        "update_id": 1003,
        "message": {
            "message_id": 3,
            "from": {"id": 888123, "first_name": "Rahul", "username": "rahul_dev", "language_code": "en"},
            "chat": {"id": 888123, "type": "private"},
            "text": "/start",
        },
    }
    wh_resp_3 = await async_client.post(
        f"/webhooks/telegram/{bot_id}",
        headers=webhook_headers,
        json=update_3,
    )
    assert wh_resp_3.status_code == 200
    sent_3 = TelegramApiService.get_sent_messages()
    assert len(sent_3) == 1
    bot_msg = sent_3[0]

    # Verify the real bot output has the exact decorative styling and variable interpolation!
    assert "╔══════════════════╗" in bot_msg["text"]
    assert "💎 <b>ᴘʀᴇᴍɪᴜᴍ ᴍᴇɴᴜ</b>" in bot_msg["text"]
    assert "✫▰▱▰▱▰▱▰▱▰▱✫" in bot_msg["text"]
    assert "❍ ɴᴀᴍᴇ : Rahul" in bot_msg["text"]
    assert "❍ sᴛᴀᴛᴜs : 🟢 ᴀᴄᴛɪᴠᴇ" in bot_msg["text"]

    # Verify inline keyboard layout
    kb = bot_msg["reply_markup"]["inline_keyboard"]
    assert len(kb) == 2  # 2 rows
    assert len(kb[0]) == 1  # 1 button in row 0
    assert kb[0][0]["text"] == "💎 Buy Premium"
    assert len(kb[1]) == 2  # 2 buttons in row 1
    assert kb[1][0]["text"] == "👤 My Profile"
    assert kb[1][1]["text"] == "🌐 Website"
    assert kb[1][1]["url"] == "https://example.com"

    # 9. Update template to Version 2 with Progress Bar
    v2_text = (
        "📦 sᴛᴇᴘ 1/4 : ᴘʀᴏᴄᴇssɪɴɢ...\n"
        "[████░░░░░░] 40%\n\n"
        "Hello {first_name}, your order is underway!"
    )
    patch_resp = await async_client.patch(
        f"/api/v1/bots/{bot_id}/messages/{template_id}",
        headers=headers,
        json={"message_text": v2_text, "is_draft": False},
    )
    assert patch_resp.status_code == 200
    assert patch_resp.json()["data"]["current_version"] == 2

    # Publish Version 2
    await async_client.post(
        f"/api/v1/bots/{bot_id}/messages/{template_id}/publish",
        headers=headers,
    )

    # 10. Incoming /start update now renders Version 2!
    TelegramApiService.clear_sent_messages()
    update_4 = {
        "update_id": 1004,
        "message": {
            "message_id": 4,
            "from": {"id": 888123, "first_name": "Rahul", "username": "rahul_dev", "language_code": "en"},
            "chat": {"id": 888123, "type": "private"},
            "text": "/start",
        },
    }
    wh_resp_4 = await async_client.post(
        f"/webhooks/telegram/{bot_id}",
        headers=webhook_headers,
        json=update_4,
    )
    assert wh_resp_4.status_code == 200
    sent_4 = TelegramApiService.get_sent_messages()
    assert len(sent_4) == 1
    assert "[████░░░░░░] 40%" in sent_4[0]["text"]
    assert "Hello Rahul, your order is underway!" in sent_4[0]["text"]

    # 11. Rollback to Version 1
    roll_resp = await async_client.post(
        f"/api/v1/bots/{bot_id}/messages/{template_id}/rollback",
        headers=headers,
        json={"version": 1},
    )
    assert roll_resp.status_code == 200
    assert roll_resp.json()["data"]["current_version"] == 3

    # Publish rolled-back version
    await async_client.post(
        f"/api/v1/bots/{bot_id}/messages/{template_id}/publish",
        headers=headers,
    )

    # 12. Incoming /start update renders Version 1 restored!
    TelegramApiService.clear_sent_messages()
    update_5 = {
        "update_id": 1005,
        "message": {
            "message_id": 5,
            "from": {"id": 888123, "first_name": "Rahul", "username": "rahul_dev", "language_code": "en"},
            "chat": {"id": 888123, "type": "private"},
            "text": "/start",
        },
    }
    wh_resp_5 = await async_client.post(
        f"/webhooks/telegram/{bot_id}",
        headers=webhook_headers,
        json=update_5,
    )
    assert wh_resp_5.status_code == 200
    sent_5 = TelegramApiService.get_sent_messages()
    assert len(sent_5) == 1
    assert "╔══════════════════╗" in sent_5[0]["text"]
    assert "💎 <b>ᴘʀᴇᴍɪᴜᴍ ᴍᴇɴᴜ</b>" in sent_5[0]["text"]
