"""Theme version APIs — Phase 11.3 (versioned themes)."""
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 (
    THEMES_CREATE,
    THEMES_MANAGE,
    THEMES_UPDATE,
    THEMES_VIEW,
)
from app.queries.themes import ThemeLayoutQueries
from app.schemas.themes import (
    ExperienceThemeVersionCreate,
    ExperienceThemeVersionListResponse,
    ExperienceThemeVersionRead,
    ExperienceThemeVersionUpdate,
)
from app.specifications.themes import THEME_VERSION_SORT_FIELDS, ThemeVersionListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

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


def _list_spec(
    theme_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)$"),
) -> ThemeVersionListSpec:
    if sort_by not in THEME_VERSION_SORT_FIELDS:
        sort_by = "version_number"
    return ThemeVersionListSpec(
        theme_id=theme_id,
        status=status_filter if status_filter in _STATUSES else None,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post(
    "", response_model=ExperienceThemeVersionRead, status_code=status.HTTP_201_CREATED
)
async def create_theme_version(
    body: ExperienceThemeVersionCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(THEMES_CREATE)),
):
    return await ThemeLayoutCommands(db).create_theme_version(
        tenant_id, body, actor=user
    )


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


@router.get("/{version_id}", response_model=ExperienceThemeVersionRead)
async def get_theme_version(
    version_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(THEMES_VIEW)),
):
    return await ThemeLayoutQueries(db).get_theme_version(tenant_id, version_id)


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


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


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