import uuid
import pytest
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession
from modules.bots.models import Bot


@pytest.mark.asyncio
async def test_bot_message_studio_lifecycle(async_client: AsyncClient, db_session: AsyncSession):
    # 1. Setup User A & Tenant A
    user_a_email = f"user_studio_{uuid.uuid4().hex[:6]}@example.com"
    resp_a = await async_client.post(
        "/api/v1/auth/register",
        json={"email": user_a_email, "password": "PasswordA123!", "full_name": "Studio Master"},
    )
    token_a = resp_a.json()["data"]["access_token"]

    tenant_resp = await async_client.post(
        "/api/v1/tenants",
        headers={"Authorization": f"Bearer {token_a}"},
        json={"name": "Studio Tenant", "slug": f"studio-{uuid.uuid4().hex[:6]}"},
    )
    tenant_id = tenant_resp.json()["data"]["id"]
    headers_a = {
        "Authorization": f"Bearer {token_a}",
        "X-Tenant-ID": str(tenant_id),
    }

    # 2. Insert Bot A & Bot B into database for Tenant A
    bot_a = Bot(
        tenant_id=uuid.UUID(tenant_id),
        name="Business Bot A",
        username=f"biz_bot_a_{uuid.uuid4().hex[:6]}",
        status="active",
        default_locale="en",
    )
    bot_b = Bot(
        tenant_id=uuid.UUID(tenant_id),
        name="Business Bot B",
        username=f"biz_bot_b_{uuid.uuid4().hex[:6]}",
        status="active",
        default_locale="en",
    )
    db_session.add(bot_a)
    db_session.add(bot_b)
    await db_session.commit()
    await db_session.refresh(bot_a)
    await db_session.refresh(bot_b)

    bot_a_id = str(bot_a.id)
    bot_b_id = str(bot_b.id)

    # 3. Create a Message Template with Buttons
    create_payload = {
        "message_key": "welcome",
        "title": "Main Welcome Screen",
        "message_text": "🙏 Welcome, {first_name}!\n\nWelcome to our VIP club. Choose below:",
        "parse_mode": "HTML",
        "media_type": "none",
        "locale": "en",
        "is_active": True,
        "is_draft": False,
        "buttons": [
            {
                "text": "💎 Buy Premium",
                "button_type": "callback_data",
                "action_value": "act:buy_premium",
                "row_position": 0,
                "column_position": 0,
                "sort_order": 0,
            },
            {
                "text": "👤 My Account",
                "button_type": "callback_data",
                "action_value": "act:account",
                "row_position": 1,
                "column_position": 0,
                "sort_order": 0,
            },
            {
                "text": "📞 Support",
                "button_type": "callback_data",
                "action_value": "act:support",
                "row_position": 1,
                "column_position": 1,
                "sort_order": 1,
            },
        ],
    }

    post_resp = await async_client.post(
        f"/api/v1/bots/{bot_a_id}/messages",
        headers=headers_a,
        json=create_payload,
    )
    assert post_resp.status_code == 201, post_resp.text
    data = post_resp.json()["data"]
    template_id = data["id"]
    assert data["message_key"] == "welcome"
    assert len(data["buttons"]) == 3
    assert data["current_version"] == 1

    # 4. Preview Template with Variables
    preview_resp = await async_client.post(
        f"/api/v1/bots/{bot_a_id}/messages/{template_id}/preview",
        headers=headers_a,
        json={"variables": {"first_name": "Karan"}},
    )
    assert preview_resp.status_code == 200
    p_data = preview_resp.json()["data"]
    assert "Welcome, Karan!" in p_data["rendered_text"]
    assert len(p_data["keyboard"]) == 2  # 2 rows

    # 5. Update Template (creates Version 2)
    update_payload = {
        "title": "Updated Welcome Screen",
        "message_text": "🔥 Hello {first_name}! Welcome to the Updated Experience.",
        "buttons": [
            {
                "text": "🚀 Get Started",
                "button_type": "callback_data",
                "action_value": "act:start",
                "row_position": 0,
                "column_position": 0,
                "sort_order": 0,
            }
        ],
    }
    patch_resp = await async_client.patch(
        f"/api/v1/bots/{bot_a_id}/messages/{template_id}",
        headers=headers_a,
        json=update_payload,
    )
    assert patch_resp.status_code == 200
    patched_data = patch_resp.json()["data"]
    assert patched_data["current_version"] == 2
    assert len(patched_data["buttons"]) == 1

    # 6. Check Versions List
    vers_resp = await async_client.get(
        f"/api/v1/bots/{bot_a_id}/messages/{template_id}/versions",
        headers=headers_a,
    )
    assert vers_resp.status_code == 200
    v_list = vers_resp.json()["data"]
    assert len(v_list) == 2
    assert v_list[0]["version"] == 2
    assert v_list[1]["version"] == 1

    # 7. Rollback to Version 1
    roll_resp = await async_client.post(
        f"/api/v1/bots/{bot_a_id}/messages/{template_id}/rollback",
        headers=headers_a,
        json={"version": 1},
    )
    assert roll_resp.status_code == 200
    rolled_data = roll_resp.json()["data"]
    assert "VIP club" in rolled_data["message_text"]
    assert len(rolled_data["buttons"]) == 3
    assert rolled_data["current_version"] == 3

    # 8. Duplicate Template to Bot B
    dup_resp = await async_client.post(
        f"/api/v1/bots/{bot_a_id}/messages/{template_id}/duplicate",
        headers=headers_a,
        json={"target_bot_id": bot_b_id},
    )
    assert dup_resp.status_code == 201
    dup_data = dup_resp.json()["data"]
    assert dup_data["bot_id"] == bot_b_id
    assert dup_data["message_key"] == "welcome"
    assert len(dup_data["buttons"]) == 3

    # 9. Tenant Isolation Check: User B from Tenant B cannot access Bot A's messages
    user_b_email = f"user_b_{uuid.uuid4().hex[:6]}@example.com"
    resp_b = await async_client.post(
        "/api/v1/auth/register",
        json={"email": user_b_email, "password": "PasswordB123!", "full_name": "Hacker Beta"},
    )
    token_b = resp_b.json()["data"]["access_token"]
    tenant_b_resp = await async_client.post(
        "/api/v1/tenants",
        headers={"Authorization": f"Bearer {token_b}"},
        json={"name": "Tenant B", "slug": f"tenant-b-{uuid.uuid4().hex[:6]}"},
    )
    tenant_b_id = tenant_b_resp.json()["data"]["id"]
    headers_b = {
        "Authorization": f"Bearer {token_b}",
        "X-Tenant-ID": str(tenant_b_id),
    }

    # User B tries to read Bot A's template -> must fail (404 not found under Tenant B or 403)
    b_denied = await async_client.get(
        f"/api/v1/bots/{bot_a_id}/messages/{template_id}",
        headers=headers_b,
    )
    assert b_denied.status_code in (403, 404)

    # 10. Export Bot A's Templates
    export_resp = await async_client.get(
        f"/api/v1/bots/{bot_a_id}/messages/export",
        headers=headers_a,
    )
    assert export_resp.status_code == 200
    export_data = export_resp.json()["data"]
    assert export_data["bot_id"] == bot_a_id
    assert len(export_data["templates"]) >= 1
    assert export_data["templates"][0]["message_key"] == "welcome"

    # User B cannot export Bot A's templates
    export_denied = await async_client.get(
        f"/api/v1/bots/{bot_a_id}/messages/export",
        headers=headers_b,
    )
    assert export_denied.status_code in (403, 404)

    # 11. Import Templates into Bot B
    import_payload = {
        "overwrite": True,
        "templates": [
            {
                "message_key": "invoice_alert",
                "title": "Payment Invoice",
                "message_text": "╔══════════════════╗\n💳 <b>PAYMENT INVOICE</b>\n╚══════════════════╝\n\nAmount: {amount}",
                "parse_mode": "HTML",
                "media_type": "none",
                "locale": "en",
                "is_active": True,
                "buttons": [
                    {
                        "text": "💳 Pay Now",
                        "button_type": "url",
                        "action_value": "https://pay.example.com",
                        "row_position": 0,
                        "column_position": 0,
                        "sort_order": 0,
                    }
                ],
            }
        ],
    }
    import_resp = await async_client.post(
        f"/api/v1/bots/{bot_b_id}/messages/import",
        headers=headers_a,
        json=import_payload,
    )
    assert import_resp.status_code == 200
    imported_list = import_resp.json()["data"]
    assert len(imported_list) == 1
    assert imported_list[0]["message_key"] == "invoice_alert"

    # 12. Bot-specific Styling Get & Update
    styling_get = await async_client.get(
        f"/api/v1/bots/{bot_a_id}/messages/styling",
        headers=headers_a,
    )
    assert styling_get.status_code == 200
    assert styling_get.json()["data"]["header_style"] == "double"

    update_styling_payload = {
        "header_style": "rounded",
        "separator_preset": "stars",
        "font_style": "small_caps",
        "bullet_symbol": "⬥",
        "progress_style": "smooth",
        "custom_symbols": ["✫", "❍", "⬥", "💎"],
    }
    styling_put = await async_client.put(
        f"/api/v1/bots/{bot_a_id}/messages/styling",
        headers=headers_a,
        json=update_styling_payload,
    )
    assert styling_put.status_code == 200
    updated_styling = styling_put.json()["data"]
    assert updated_styling["header_style"] == "rounded"
    assert updated_styling["separator_preset"] == "stars"
    assert updated_styling["bullet_symbol"] == "⬥"

    # User B cannot update Bot A's styling
    styling_denied = await async_client.put(
        f"/api/v1/bots/{bot_a_id}/messages/styling",
        headers=headers_b,
        json=update_styling_payload,
    )
    assert styling_denied.status_code in (403, 404)

