"""Robots shell APIs — Phase 11.7."""
from uuid import UUID
from fastapi import APIRouter, Depends, Query, 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.publishing import PublishingCommands
from app.permissions.definitions import SEO_CREATE, SEO_UPDATE, SEO_VIEW
from app.queries.publishing import PublishingQueries
from app.schemas.publishing import RobotsShellListResponse, RobotsShellRead, RobotsShellUpdate, RobotsShellUpsert
from app.specifications.publishing import ROBOTS_SORT, RobotsShellListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()
def _list_spec(workspace_id: UUID | None = None, site_id: UUID | None = None, status_filter: str | None = Query(default=None, alias="status"),
               q: str | None = Query(default=None, max_length=100), sort_by: str = "created_at",
               sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$")):
    return RobotsShellListSpec(workspace_id=workspace_id, site_id=site_id, status=status_filter, q=q,
        sort_by=sort_by if sort_by in ROBOTS_SORT else "created_at", sort_dir=sort_dir)
@router.post("", response_model=RobotsShellRead, status_code=status.HTTP_201_CREATED)
async def upsert(body: RobotsShellUpsert, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db), user: CurrentUser = Depends(require_permissions(SEO_CREATE))):
    return await PublishingCommands(db).upsert_robots(tenant_id, body, actor=user)
@router.get("", response_model=RobotsShellListResponse)
async def list_items(tenant_id: UUID = Depends(require_tenant), pagination: PaginationParams = Depends(get_pagination), spec: RobotsShellListSpec = Depends(_list_spec), db: AsyncSession = Depends(get_db), _user: CurrentUser = Depends(require_permissions(SEO_VIEW))):
    items, total = await PublishingQueries(db).list_robots(tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec)
    return RobotsShellListResponse(items=items, total=total, page=pagination.page, page_size=pagination.page_size)
@router.get("/{entity_id}", response_model=RobotsShellRead)
async def get(entity_id: UUID, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db), _user: CurrentUser = Depends(require_permissions(SEO_VIEW))):
    return await PublishingQueries(db).get_robots(tenant_id, entity_id)
@router.patch("/{entity_id}", response_model=RobotsShellRead)
async def update(entity_id: UUID, body: RobotsShellUpdate, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db), user: CurrentUser = Depends(require_permissions(SEO_UPDATE))):
    return await PublishingCommands(db).update_robots(tenant_id, entity_id, body, actor=user)
