"""Layout APIs — Phase 11.3."""
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_MANAGE,
    LAYOUTS_UPDATE,
    LAYOUTS_VIEW,
)
from app.queries.themes import ThemeLayoutQueries
from app.schemas.themes import (
    ExperienceLayoutCreate,
    ExperienceLayoutListResponse,
    ExperienceLayoutRead,
    ExperienceLayoutUpdate,
)
from app.specifications.themes import LAYOUT_SORT_FIELDS, LayoutListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

_STATUSES = {"draft", "active", "deprecated", "archived"}
_DIRECTIONS = {"rtl", "ltr", "both"}


_KINDS = {"page_shell", "app_shell", "sidebar", "split", "custom"}


def _list_spec(
    workspace_id: UUID | None = Query(default=None),
    status_filter: str | None = Query(default=None, alias="status"),
    direction_mode: str | None = Query(default=None),
    kind: str | None = Query(default=None),
    q: str | None = Query(default=None, max_length=100),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> LayoutListSpec:
    if sort_by not in LAYOUT_SORT_FIELDS:
        sort_by = "created_at"
    return LayoutListSpec(
        workspace_id=workspace_id,
        status=status_filter if status_filter in _STATUSES else None,
        direction_mode=direction_mode if direction_mode in _DIRECTIONS else None,
        kind=kind if kind in _KINDS else None,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


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


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


@router.get("/{layout_id}", response_model=ExperienceLayoutRead)
async def get_layout(
    layout_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_layout(tenant_id, layout_id)


@router.patch("/{layout_id}", response_model=ExperienceLayoutRead)
async def update_layout(
    layout_id: UUID,
    body: ExperienceLayoutUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LAYOUTS_UPDATE)),
):
    return await ThemeLayoutCommands(db).update_layout(
        tenant_id, layout_id, body, actor=user
    )


@router.post("/{layout_id}/activate", response_model=ExperienceLayoutRead)
async def activate_layout(
    layout_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LAYOUTS_MANAGE)),
):
    return await ThemeLayoutCommands(db).activate_layout(
        tenant_id, layout_id, actor=user
    )


@router.post("/{layout_id}/deprecate", response_model=ExperienceLayoutRead)
async def deprecate_layout(
    layout_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LAYOUTS_MANAGE)),
):
    return await ThemeLayoutCommands(db).deprecate_layout(
        tenant_id, layout_id, actor=user
    )


@router.post("/{layout_id}/archive", response_model=ExperienceLayoutRead)
async def archive_layout(
    layout_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LAYOUTS_MANAGE)),
):
    return await ThemeLayoutCommands(db).archive_layout(
        tenant_id, layout_id, actor=user
    )


@router.post("/{layout_id}/delete", response_model=ExperienceLayoutRead)
async def soft_delete_layout(
    layout_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LAYOUTS_DELETE)),
):
    return await ThemeLayoutCommands(db).soft_delete_layout(
        tenant_id, layout_id, actor=user
    )
