"""Layout version APIs — Phase 11.3 (versioned layouts)."""
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_MANAGE,
    LAYOUTS_UPDATE,
    LAYOUTS_VIEW,
)
from app.queries.themes import ThemeLayoutQueries
from app.schemas.themes import (
    ExperienceLayoutVersionCreate,
    ExperienceLayoutVersionListResponse,
    ExperienceLayoutVersionRead,
    ExperienceLayoutVersionUpdate,
)
from app.specifications.themes import LAYOUT_VERSION_SORT_FIELDS, LayoutVersionListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

_STATUSES = {"draft", "published", "retired"}


def _list_spec(
    layout_id: UUID | None = Query(default=None),
    status_filter: str | None = Query(default=None, alias="status"),
    sort_by: str = Query(default="version_number"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> LayoutVersionListSpec:
    if sort_by not in LAYOUT_VERSION_SORT_FIELDS:
        sort_by = "version_number"
    return LayoutVersionListSpec(
        layout_id=layout_id,
        status=status_filter if status_filter in _STATUSES else None,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


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


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


@router.get("/{version_id}", response_model=ExperienceLayoutVersionRead)
async def get_layout_version(
    version_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_version(tenant_id, version_id)


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


@router.post("/{version_id}/publish", response_model=ExperienceLayoutVersionRead)
async def publish_layout_version(
    version_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LAYOUTS_MANAGE)),
):
    return await ThemeLayoutCommands(db).publish_layout_version(
        tenant_id, version_id, actor=user
    )


@router.post("/{version_id}/retire", response_model=ExperienceLayoutVersionRead)
async def retire_layout_version(
    version_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LAYOUTS_MANAGE)),
):
    return await ThemeLayoutCommands(db).retire_layout_version(
        tenant_id, version_id, actor=user
    )
