import uuid
import pytest
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession


@pytest.mark.asyncio
async def test_plugins_module_full_lifecycle(
    async_client: AsyncClient,
    db_session: AsyncSession,
):
    # 1. Register User and Create Tenant
    email = f"plugin_user_{uuid.uuid4().hex[:6]}@example.com"
    reg_resp = await async_client.post(
        "/api/v1/auth/register",
        json={"email": email, "password": "Password123!", "full_name": "Plugin Architect"},
    )
    assert reg_resp.status_code == 201
    token = reg_resp.json()["data"]["access_token"]
    headers = {
        "Authorization": f"Bearer {token}",
    }

    tenant_resp = await async_client.post(
        "/api/v1/tenants",
        headers=headers,
        json={"name": "Plugins Extensibility Inc", "slug": f"plugins-{uuid.uuid4().hex[:6]}"},
    )
    assert tenant_resp.status_code == 201
    tenant_id = tenant_resp.json()["data"]["id"]
    headers["X-Tenant-ID"] = tenant_id

    # 2. List Available Plugins Catalog
    cat_resp = await async_client.get("/api/v1/plugins")
    assert cat_resp.status_code == 200
    catalog = cat_resp.json()["data"]
    assert len(catalog) >= 4
    plugin_ids = [p["id"] for p in catalog]
    assert "welcome_captcha" in plugin_ids
    assert "crypto_price_tracker" in plugin_ids
    assert "sentiment_analyzer" in plugin_ids
    assert "auto_support_router" in plugin_ids

    crypto_plugin = next(p for p in catalog if p["id"] == "crypto_price_tracker")
    assert crypto_plugin["is_official"] is True
    assert "messages:write" in crypto_plugin["required_permissions"]

    # 3. List Installed Plugins initially (should be empty)
    inst_resp = await async_client.get("/api/v1/plugins/installed", headers=headers)
    assert inst_resp.status_code == 200
    assert len(inst_resp.json()["data"]) == 0

    # 4. Activate Plugin for Tenant
    act_resp = await async_client.post(
        "/api/v1/plugins/activate",
        headers=headers,
        json={
            "plugin_id": "crypto_price_tracker",
            "config": {
                "default_currency": "USD",
                "custom_symbols": ["BTC", "ETH", "TON"],
            },
        },
    )
    assert act_resp.status_code == 201
    act_data = act_resp.json()["data"]
    tenant_plugin_id = act_data["id"]
    assert act_data["plugin_id"] == "crypto_price_tracker"
    assert act_data["is_enabled"] is True
    assert act_data["config"]["default_currency"] == "USD"
    assert "messages:write" in act_data["granted_permissions"]

    # 5. Duplicate Activation returns 409 Conflict
    dup_resp = await async_client.post(
        "/api/v1/plugins/activate",
        headers=headers,
        json={"plugin_id": "crypto_price_tracker"},
    )
    assert dup_resp.status_code == 409

    # 6. Verify Installed Plugins List
    inst_resp2 = await async_client.get("/api/v1/plugins/installed", headers=headers)
    assert inst_resp2.status_code == 200
    assert len(inst_resp2.json()["data"]) == 1
    assert inst_resp2.json()["data"][0]["id"] == tenant_plugin_id

    # 7. Execute Sandboxed Plugin Hook (on_command)
    exec_resp = await async_client.post(
        f"/api/v1/plugins/{tenant_plugin_id}/execute",
        headers=headers,
        json={
            "hook_name": "on_command",
            "payload": {
                "command": "price",
                "args": ["BTC"],
            },
        },
    )
    assert exec_resp.status_code == 200
    exec_data = exec_resp.json()["data"]
    assert exec_data["success"] is True
    assert exec_data["hook_name"] == "on_command"
    assert "symbol" in exec_data["output"]
    assert exec_data["output"]["symbol"] == "BTC"
    assert "price_usd" in exec_data["output"]
    assert "formatted" in exec_data["output"]

    # 8. Update Plugin Configuration and Toggle Enabled Status
    update_resp = await async_client.patch(
        f"/api/v1/plugins/{tenant_plugin_id}",
        headers=headers,
        json={
            "is_enabled": False,
            "config": {"default_currency": "EUR"},
        },
    )
    assert update_resp.status_code == 200
    up_data = update_resp.json()["data"]
    assert up_data["is_enabled"] is False
    assert up_data["config"]["default_currency"] == "EUR"

    # 9. Executing Hook on Disabled Plugin returns 422 Validation Error
    exec_disabled_resp = await async_client.post(
        f"/api/v1/plugins/{tenant_plugin_id}/execute",
        headers=headers,
        json={
            "hook_name": "on_command",
            "payload": {"command": "price", "args": ["ETH"]},
        },
    )
    assert exec_disabled_resp.status_code == 422
    assert "disabled" in exec_disabled_resp.json()["message"]

    # 10. Deactivate & Remove Plugin
    del_resp = await async_client.delete(f"/api/v1/plugins/{tenant_plugin_id}", headers=headers)
    assert del_resp.status_code == 200

    # Verify Installed List is empty
    inst_resp3 = await async_client.get("/api/v1/plugins/installed", headers=headers)
    assert inst_resp3.status_code == 200
    assert len(inst_resp3.json()["data"]) == 0
