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_synthesizer_api_full_flow(
    async_client: AsyncClient, db_session: AsyncSession
):
    # 1. Setup Tenant
    user_email = f"synth_user_{uuid.uuid4().hex[:6]}@example.com"
    reg_resp = await async_client.post(
        "/api/v1/auth/register",
        json={"email": user_email, "password": "Password123!", "full_name": "AI Bot Builder User"},
    )
    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": "Synthesizer Tenant", "slug": f"synth-corp-{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": tenant_id,
    }

    # 2. Synthesize Bot via Natural Language Prompt
    user_prompt = "Mujhe ek Telegram AI customer support bot chahiye ticket escalate karne ke liye aur Hindi/English bol sake."
    synth_resp = await async_client.post(
        "/api/v1/bot-builder/ai-synthesize",
        headers=headers,
        json={"prompt": user_prompt, "channel": "telegram"},
    )
    assert synth_resp.status_code == 200
    proposal = synth_resp.json()["data"]
    proposal_id = proposal["proposal_id"]
    assert proposal["matched_template_id"] == "bot_customer_support"
    assert len(proposal["workflow_nodes"]) >= 3
    assert "Customer Support" in proposal["bot_name"]

    # 3. Create a Bot and 1-Click Deploy the Synthesized Proposal
    test_bot = Bot(
        tenant_id=uuid.UUID(tenant_id),
        name="Synthesized Support Bot",
        username=f"synth_bot_{uuid.uuid4().hex[:6]}",
        status="active",
        default_locale="en",
    )
    db_session.add(test_bot)
    await db_session.commit()

    deploy_resp = await async_client.post(
        "/api/v1/bot-builder/deploy",
        headers=headers,
        json={
            "proposal_id": proposal_id,
            "bot_id": str(test_bot.id),
            "custom_name": "My Live AI Support Concierge",
        },
    )
    assert deploy_resp.status_code == 201
    deployed = deploy_resp.json()["data"]
    assert deployed["name"] == "My Live AI Support Concierge"
    assert deployed["template_id"] == "bot_customer_support"
    assert deployed["status"] == "deployed"
    assert deployed["bot_id"] == str(test_bot.id)

    # 4. Verify instance is present in Tenant's marketplace instances
    instances_resp = await async_client.get("/api/v1/marketplace/instances", headers=headers)
    assert instances_resp.status_code == 200
    instances = instances_resp.json()["data"]
    assert any(i["name"] == "My Live AI Support Concierge" for i in instances)
