"""AI content dispatch APIs — Phase 11.10."""
from uuid import UUID

from fastapi import APIRouter, Depends, Query, Response, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_pagination, require_tenant
from app.api.permissions import require_permissions
from app.commands.ai_hooks import AiHooksCommands
from app.permissions.definitions import (
    AI_HOOKS_CREATE,
    AI_HOOKS_DELETE,
    AI_HOOKS_MANAGE,
    AI_HOOKS_UPDATE,
    AI_HOOKS_VIEW,
)
from app.queries.ai_hooks import AiHooksQueries
from app.schemas.ai_hooks import (
    AiContentDispatchCreate,
    AiContentDispatchListResponse,
    AiContentDispatchRead,
    AiContentDispatchUpdate,
)
from app.specifications.ai_hooks import DISPATCH_SORT, AiContentDispatchListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _spec(
    workspace_id: UUID | None = None,
    site_id: UUID | None = None,
    page_id: UUID | None = None,
    registration_id: UUID | None = None,
    status_filter: str | None = Query(None, alias="status"),
    q: str | None = Query(None, max_length=100),
    sort_by: str = "created_at",
    sort_dir: str = Query("desc", pattern="^(?i)(asc|desc)$"),
):
    return AiContentDispatchListSpec(
        workspace_id=workspace_id,
        site_id=site_id,
        page_id=page_id,
        registration_id=registration_id,
        status=status_filter,
        q=q,
        sort_by=sort_by if sort_by in DISPATCH_SORT else "created_at",
        sort_dir=sort_dir,
    )


@router.post("", response_model=AiContentDispatchRead, status_code=201)
async def create(
    body: AiContentDispatchCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(AI_HOOKS_CREATE)),
):
    return await AiHooksCommands(db).create_dispatch(tenant_id, body, actor=user)


@router.get("", response_model=AiContentDispatchListResponse)
async def list_items(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: AiContentDispatchListSpec = Depends(_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(AI_HOOKS_VIEW)),
):
    items, total = await AiHooksQueries(db).list_dispatches(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return AiContentDispatchListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{entity_id}", response_model=AiContentDispatchRead)
async def get(
    entity_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(AI_HOOKS_VIEW)),
):
    return await AiHooksQueries(db).get_dispatch(tenant_id, entity_id)


@router.patch("/{entity_id}", response_model=AiContentDispatchRead)
async def update(
    entity_id: UUID,
    body: AiContentDispatchUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(AI_HOOKS_UPDATE)),
):
    return await AiHooksCommands(db).update_dispatch(tenant_id, entity_id, body, actor=user)


@router.post("/{entity_id}/generate", response_model=AiContentDispatchRead)
async def generate(
    entity_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(AI_HOOKS_MANAGE)),
):
    return await AiHooksCommands(db).generate_dispatch(tenant_id, entity_id, actor=user)


@router.delete("/{entity_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete(
    entity_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(AI_HOOKS_DELETE)),
):
    await AiHooksCommands(db).delete_dispatch(tenant_id, entity_id, actor=user)
    return Response(status_code=204)
