"""Component version APIs — Phase 11.2."""
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.components import ComponentCommands
from app.permissions.definitions import (
    COMPONENTS_CREATE,
    COMPONENTS_MANAGE,
    COMPONENTS_UPDATE,
    COMPONENTS_VIEW,
)
from app.queries.components import ComponentQueries
from app.schemas.components import (
    ExperienceComponentVersionCreate,
    ExperienceComponentVersionListResponse,
    ExperienceComponentVersionRead,
    ExperienceComponentVersionUpdate,
)
from app.specifications.components import VERSION_SORT_FIELDS, ComponentVersionListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

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


def _list_spec(
    component_id: UUID | None = Query(default=None),
    status_filter: str | None = Query(default=None, alias="status"),
    q: str | None = Query(default=None, max_length=100),
    sort_by: str = Query(default="version_number"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> ComponentVersionListSpec:
    if sort_by not in VERSION_SORT_FIELDS:
        sort_by = "version_number"
    status_value = status_filter if status_filter in _VERSION_STATUSES else None
    return ComponentVersionListSpec(
        component_id=component_id,
        status=status_value,  # type: ignore[arg-type]
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post(
    "",
    response_model=ExperienceComponentVersionRead,
    status_code=status.HTTP_201_CREATED,
)
async def create_version(
    body: ExperienceComponentVersionCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(COMPONENTS_CREATE)),
):
    return await ComponentCommands(db).create_version(tenant_id, body, actor=user)


@router.get("", response_model=ExperienceComponentVersionListResponse)
async def list_versions(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: ComponentVersionListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(COMPONENTS_VIEW)),
):
    items, total = await ComponentQueries(db).list_versions(
        tenant_id,
        offset=pagination.offset,
        limit=pagination.page_size,
        spec=spec,
    )
    return ExperienceComponentVersionListResponse(
        items=items,
        total=total,
        page=pagination.page,
        page_size=pagination.page_size,
    )


@router.get("/{version_id}", response_model=ExperienceComponentVersionRead)
async def get_version(
    version_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(COMPONENTS_VIEW)),
):
    return await ComponentQueries(db).get_version(tenant_id, version_id)


@router.patch("/{version_id}", response_model=ExperienceComponentVersionRead)
async def update_version(
    version_id: UUID,
    body: ExperienceComponentVersionUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(COMPONENTS_UPDATE)),
):
    return await ComponentCommands(db).update_version(
        tenant_id, version_id, body, actor=user
    )


@router.post("/{version_id}/publish", response_model=ExperienceComponentVersionRead)
async def publish_version(
    version_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(COMPONENTS_MANAGE)),
):
    return await ComponentCommands(db).publish_version(
        tenant_id, version_id, actor=user
    )


@router.post("/{version_id}/retire", response_model=ExperienceComponentVersionRead)
async def retire_version(
    version_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(COMPONENTS_MANAGE)),
):
    return await ComponentCommands(db).retire_version(
        tenant_id, version_id, actor=user
    )
