"""AI content hook API tests — Phase 11.10."""
import pytest

from app.tests.conftest import TENANT_A, TENANT_B, tenant_headers


async def _workspace(client, code="ai-hooks"):
    response = await client.post(
        "/api/v1/workspaces",
        json={"code": code, "name": "AI Hooks", "status": "active"},
        headers=tenant_headers(TENANT_A),
    )
    assert response.status_code == 201, response.text
    return response.json()


@pytest.mark.asyncio
async def test_ai_hook_dispatch_generate_happy_path(client):
    caps = (await client.get("/capabilities")).json()
    assert caps["features"]["ai_content"] is True

    ws = await _workspace(client)
    headers = tenant_headers(TENANT_A)

    registration = await client.post(
        "/api/v1/ai-content-hook-registrations",
        json={
            "workspace_id": ws["id"],
            "code": "page-copy-1",
            "name": "Page Copy Hook",
            "task_kind": "page_copy",
            "status": "active",
        },
        headers=headers,
    )
    assert registration.status_code == 201, registration.text
    reg_id = registration.json()["id"]

    dispatch = await client.post(
        "/api/v1/ai-content-dispatches",
        json={
            "registration_id": reg_id,
            "workspace_id": ws["id"],
            "task": "generate_landing_copy",
            "context_ref": "page:landing:1",
            "payload_json": {"locale": "fa"},
        },
        headers=headers,
    )
    assert dispatch.status_code == 201, dispatch.text
    generated = await client.post(
        f"/api/v1/ai-content-dispatches/{dispatch.json()['id']}/generate",
        headers=headers,
    )
    assert generated.status_code == 200, generated.text
    body = generated.json()
    assert body["status"] == "generated"
    assert body["generated_content_ref"].startswith("ai:content:")


@pytest.mark.asyncio
async def test_forbidden_ai_keys_rejected(client):
    ws = await _workspace(client, "forbidden-ai")
    headers = tenant_headers(TENANT_A)

    response = await client.post(
        "/api/v1/ai-content-hook-registrations",
        json={
            "workspace_id": ws["id"],
            "code": "bad-hook",
            "name": "Bad Hook",
            "task_kind": "custom",
            "status": "draft",
            "config_json": {"model_id": "gpt-4"},
        },
        headers=headers,
    )
    assert response.status_code == 422, response.text


@pytest.mark.asyncio
async def test_suspended_registration_generate_fails(client):
    ws = await _workspace(client, "suspended-ai")
    headers = tenant_headers(TENANT_A)

    registration = await client.post(
        "/api/v1/ai-content-hook-registrations",
        json={
            "workspace_id": ws["id"],
            "code": "suspended-hook",
            "name": "Suspended Hook",
            "task_kind": "seo_meta",
            "status": "suspended",
        },
        headers=headers,
    )
    assert registration.status_code == 201, registration.text
    reg_id = registration.json()["id"]

    dispatch = await client.post(
        "/api/v1/ai-content-dispatches",
        json={
            "registration_id": reg_id,
            "workspace_id": ws["id"],
            "task": "generate_seo",
        },
        headers=headers,
    )
    assert dispatch.status_code == 201, dispatch.text
    generated = await client.post(
        f"/api/v1/ai-content-dispatches/{dispatch.json()['id']}/generate",
        headers=headers,
    )
    assert generated.status_code == 409, generated.text


@pytest.mark.asyncio
async def test_ai_hooks_tenant_isolation(client):
    ws = await _workspace(client, "iso-ai")
    headers = tenant_headers(TENANT_A)

    registration = await client.post(
        "/api/v1/ai-content-hook-registrations",
        json={
            "workspace_id": ws["id"],
            "code": "iso-hook",
            "name": "Iso Hook",
            "task_kind": "custom",
            "status": "active",
        },
        headers=headers,
    )
    assert registration.status_code == 201
    reg_id = registration.json()["id"]

    other = await client.get(
        f"/api/v1/ai-content-hook-registrations/{reg_id}",
        headers=tenant_headers(TENANT_B),
    )
    assert other.status_code == 404
