"""Theme 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 (
    THEMES_CREATE,
    THEMES_DELETE,
    THEMES_MANAGE,
    THEMES_UPDATE,
    THEMES_VIEW,
)
from app.queries.themes import ThemeLayoutQueries
from app.schemas.themes import (
    ExperienceThemeCreate,
    ExperienceThemeListResponse,
    ExperienceThemeRead,
    ExperienceThemeUpdate,
)
from app.specifications.themes import THEME_SORT_FIELDS, ThemeListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

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


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),
    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)$"),
) -> ThemeListSpec:
    if sort_by not in THEME_SORT_FIELDS:
        sort_by = "created_at"
    return ThemeListSpec(
        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,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


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


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


@router.get("/{theme_id}", response_model=ExperienceThemeRead)
async def get_theme(
    theme_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(tenant_id, theme_id)


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


@router.post("/{theme_id}/activate", response_model=ExperienceThemeRead)
async def activate_theme(
    theme_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(THEMES_MANAGE)),
):
    return await ThemeLayoutCommands(db).activate_theme(tenant_id, theme_id, actor=user)


@router.post("/{theme_id}/deprecate", response_model=ExperienceThemeRead)
async def deprecate_theme(
    theme_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(THEMES_MANAGE)),
):
    return await ThemeLayoutCommands(db).deprecate_theme(
        tenant_id, theme_id, actor=user
    )


@router.post("/{theme_id}/archive", response_model=ExperienceThemeRead)
async def archive_theme(
    theme_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(THEMES_MANAGE)),
):
    return await ThemeLayoutCommands(db).archive_theme(tenant_id, theme_id, actor=user)


@router.post("/{theme_id}/delete", response_model=ExperienceThemeRead)
async def soft_delete_theme(
    theme_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(THEMES_DELETE)),
):
    return await ThemeLayoutCommands(db).soft_delete_theme(
        tenant_id, theme_id, actor=user
    )
