"""Page layout binding APIs — Phase 11.3 (versioned bindings)."""
from __future__ import annotations

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.themes import ThemeLayoutCommands
from app.permissions.definitions import LAYOUTS_CREATE, LAYOUTS_DELETE, LAYOUTS_VIEW
from app.queries.themes import ThemeLayoutQueries
from app.schemas.themes import (
    PageLayoutBindingCreate,
    PageLayoutBindingListResponse,
    PageLayoutBindingRead,
)
from app.specifications.themes import (
    PAGE_LAYOUT_BINDING_SORT_FIELDS,
    PageLayoutBindingListSpec,
)
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    page_id: UUID | None = Query(default=None),
    layout_id: UUID | None = Query(default=None),
    site_id: UUID | None = Query(default=None),
    workspace_id: UUID | None = Query(default=None),
    is_active: bool | None = Query(default=None),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> PageLayoutBindingListSpec:
    if sort_by not in PAGE_LAYOUT_BINDING_SORT_FIELDS:
        sort_by = "created_at"
    return PageLayoutBindingListSpec(
        page_id=page_id,
        layout_id=layout_id,
        site_id=site_id,
        workspace_id=workspace_id,
        is_active=is_active,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post(
    "",
    response_model=PageLayoutBindingRead,
    status_code=status.HTTP_201_CREATED,
)
async def assign_page_layout(
    body: PageLayoutBindingCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LAYOUTS_CREATE)),
):
    return await ThemeLayoutCommands(db).assign_page_layout(tenant_id, body, actor=user)


@router.get("", response_model=PageLayoutBindingListResponse)
async def list_page_layout_bindings(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: PageLayoutBindingListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LAYOUTS_VIEW)),
):
    items, total = await ThemeLayoutQueries(db).list_page_layout_bindings(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return PageLayoutBindingListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{binding_id}", response_model=PageLayoutBindingRead)
async def get_page_layout_binding(
    binding_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LAYOUTS_VIEW)),
):
    return await ThemeLayoutQueries(db).get_page_layout_binding(tenant_id, binding_id)


@router.post("/{binding_id}/unassign", response_model=PageLayoutBindingRead)
async def unassign_page_layout(
    binding_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LAYOUTS_DELETE)),
):
    return await ThemeLayoutCommands(db).unassign_page_layout(
        tenant_id, binding_id, actor=user
    )
