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_marketplace_api_full_lifecycle_and_tenant_isolation(
    async_client: AsyncClient, db_session: AsyncSession
):
    # 1. Setup Tenant A & User A
    user_a_email = f"market_user_{uuid.uuid4().hex[:6]}@example.com"
    reg_resp_a = await async_client.post(
        "/api/v1/auth/register",
        json={"email": user_a_email, "password": "Password123!", "full_name": "Marketplace Admin"},
    )
    assert reg_resp_a.status_code == 201
    token_a = reg_resp_a.json()["data"]["access_token"]

    tenant_resp_a = await async_client.post(
        "/api/v1/tenants",
        headers={"Authorization": f"Bearer {token_a}"},
        json={"name": "Marketplace Cloud Tenant", "slug": f"cloud-{uuid.uuid4().hex[:6]}"},
    )
    assert tenant_resp_a.status_code == 201
    tenant_a_id = tenant_resp_a.json()["data"]["id"]
    headers_a = {
        "Authorization": f"Bearer {token_a}",
        "X-Tenant-ID": tenant_a_id,
    }

    # 2. Test GET /api/v1/marketplace/categories
    cat_resp = await async_client.get("/api/v1/marketplace/categories", headers=headers_a)
    assert cat_resp.status_code == 200
    categories = cat_resp.json()["data"]
    assert len(categories) == 6
    all_cat = next(c for c in categories if c["slug"] == "all")
    assert all_cat["count"] == 25
    biz_cat = next(c for c in categories if c["slug"] == "business")
    assert biz_cat["count"] == 6

    # 3. Test GET /api/v1/marketplace/templates
    all_tmpl_resp = await async_client.get("/api/v1/marketplace/templates", headers=headers_a)
    assert all_tmpl_resp.status_code == 200
    templates = all_tmpl_resp.json()["data"]
    assert len(templates) == 25

    # 4. Filter by category
    ai_tmpl_resp = await async_client.get(
        "/api/v1/marketplace/templates?category=ai_specialist", headers=headers_a
    )
    assert ai_tmpl_resp.status_code == 200
    ai_templates = ai_tmpl_resp.json()["data"]
    assert len(ai_templates) == 6

    # 5. Search by keyword
    search_resp = await async_client.get(
        "/api/v1/marketplace/templates?search=ecommerce", headers=headers_a
    )
    assert search_resp.status_code == 200
    search_results = search_resp.json()["data"]
    assert len(search_results) >= 1
    assert search_results[0]["id"] == "bot_ecommerce_concierge"

    # 6. Get template detail
    detail_resp = await async_client.get(
        "/api/v1/marketplace/templates/bot_ecommerce_concierge", headers=headers_a
    )
    assert detail_resp.status_code == 200
    detail = detail_resp.json()["data"]
    assert detail["name"] == "E-Commerce & Digital Store Concierge"
    assert "store_name" in detail["config_schema"]
    assert "shopify.products.search" in detail["mcp_tools"]

    # 7. List reusable modules
    mod_resp = await async_client.get("/api/v1/marketplace/modules", headers=headers_a)
    assert mod_resp.status_code == 200
    modules = mod_resp.json()["data"]
    assert len(modules) == 8

    # 8. Install template for Tenant A
    install_resp = await async_client.post(
        "/api/v1/marketplace/install",
        headers=headers_a,
        json={
            "template_id": "bot_ecommerce_concierge",
            "name": "My Luxury Boutique Bot",
            "custom_config": {
                "store_name": "Astraea Luxury Vault",
                "currency": "INR",
                "shipping_fee": 150,
            },
        },
    )
    assert install_resp.status_code == 201
    instance_a = install_resp.json()["data"]
    instance_id = instance_a["id"]
    assert instance_a["name"] == "My Luxury Boutique Bot"
    assert instance_a["status"] == "configured"
    assert instance_a["custom_config"]["store_name"] == "Astraea Luxury Vault"
    assert instance_a["custom_config"]["shipping_fee"] == 150

    # 9. List tenant instances
    inst_list_resp = await async_client.get("/api/v1/marketplace/instances", headers=headers_a)
    assert inst_list_resp.status_code == 200
    instances = inst_list_resp.json()["data"]
    assert len(instances) >= 1
    assert any(i["id"] == instance_id for i in instances)

    # 10. Update instance config
    update_resp = await async_client.put(
        f"/api/v1/marketplace/instances/{instance_id}/config",
        headers=headers_a,
        json={
            "name": "Renamed Luxury Boutique Bot",
            "custom_config": {"shipping_fee": 200},
        },
    )
    assert update_resp.status_code == 200
    updated_inst = update_resp.json()["data"]
    assert updated_inst["name"] == "Renamed Luxury Boutique Bot"
    assert updated_inst["custom_config"]["shipping_fee"] == 200
    assert updated_inst["custom_config"]["store_name"] == "Astraea Luxury Vault"

    # 11. Create a Bot for Tenant A and Deploy the instance to this Bot
    test_bot = Bot(
        tenant_id=uuid.UUID(tenant_a_id),
        name="Shop Helper Bot",
        username=f"shop_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(
        f"/api/v1/marketplace/instances/{instance_id}/deploy",
        headers=headers_a,
        json={"bot_id": str(test_bot.id)},
    )
    assert deploy_resp.status_code == 200
    deployed_inst = deploy_resp.json()["data"]
    assert deployed_inst["status"] == "deployed"
    assert deployed_inst["bot_id"] == str(test_bot.id)
    assert deployed_inst["last_deployed_at"] is not None

    # 12. Strict Tenant Isolation (Tenant B must NOT access Tenant A's installed instance)
    user_b_email = f"market_user_b_{uuid.uuid4().hex[:6]}@example.com"
    reg_resp_b = await async_client.post(
        "/api/v1/auth/register",
        json={"email": user_b_email, "password": "PasswordB123!", "full_name": "Tenant B User"},
    )
    token_b = reg_resp_b.json()["data"]["access_token"]
    tenant_resp_b = await async_client.post(
        "/api/v1/tenants",
        headers={"Authorization": f"Bearer {token_b}"},
        json={"name": "Tenant B Corp", "slug": f"corp-b-{uuid.uuid4().hex[:6]}"},
    )
    tenant_b_id = tenant_resp_b.json()["data"]["id"]
    headers_b = {
        "Authorization": f"Bearer {token_b}",
        "X-Tenant-ID": tenant_b_id,
    }

    # Tenant B tries to access Tenant A's instance -> 404 Not Found (isolated)
    idor_resp = await async_client.get(
        f"/api/v1/marketplace/instances/{instance_id}", headers=headers_b
    )
    assert idor_resp.status_code == 404

    # 13. Uninstall instance
    del_resp = await async_client.delete(
        f"/api/v1/marketplace/instances/{instance_id}", headers=headers_a
    )
    assert del_resp.status_code == 200
    assert del_resp.json()["data"]["uninstalled"] is True

    # Confirm it's gone
    get_after_del = await async_client.get(
        f"/api/v1/marketplace/instances/{instance_id}", headers=headers_a
    )
    assert get_after_del.status_code == 404
