"""Site locale binding APIs — Phase 11.5."""
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.localization import LocalizationCommands
from app.permissions.definitions import (
    LOCALES_CREATE,
    LOCALES_DELETE,
    LOCALES_UPDATE,
    LOCALES_VIEW,
)
from app.queries.localization import LocalizationQueries
from app.schemas.localization import (
    SiteLocaleBindingCreate,
    SiteLocaleBindingListResponse,
    SiteLocaleBindingRead,
    SiteLocaleBindingUpdate,
)
from app.specifications.localization import (
    SITE_LOCALE_BINDING_SORT_FIELDS,
    SiteLocaleBindingListSpec,
)
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

_DIRECTIONS = {"rtl", "ltr"}


def _list_spec(
    workspace_id: UUID | None = Query(default=None),
    site_id: UUID | None = Query(default=None),
    locale_profile_id: UUID | None = Query(default=None),
    locale_code: str | None = Query(default=None, max_length=16),
    text_direction: str | None = Query(default=None, max_length=3),
    is_default: bool | None = Query(default=None),
    is_active: bool | None = Query(default=None),
    q: str | None = Query(default=None, max_length=100),
    sort_by: str = Query(default="sort_order"),
    sort_dir: str = Query(default="asc", pattern="^(?i)(asc|desc)$"),
) -> SiteLocaleBindingListSpec:
    if sort_by not in SITE_LOCALE_BINDING_SORT_FIELDS:
        sort_by = "sort_order"
    return SiteLocaleBindingListSpec(
        workspace_id=workspace_id,
        site_id=site_id,
        locale_profile_id=locale_profile_id,
        locale_code=locale_code,
        text_direction=text_direction if text_direction in _DIRECTIONS else None,
        is_default=is_default,
        is_active=is_active,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post(
    "", response_model=SiteLocaleBindingRead, status_code=status.HTTP_201_CREATED
)
async def create_site_locale_binding(
    body: SiteLocaleBindingCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOCALES_CREATE)),
):
    return await LocalizationCommands(db).create_site_locale_binding(
        tenant_id, body, actor=user
    )


@router.get("", response_model=SiteLocaleBindingListResponse)
async def list_site_locale_bindings(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: SiteLocaleBindingListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOCALES_VIEW)),
):
    items, total = await LocalizationQueries(db).list_site_locale_bindings(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return SiteLocaleBindingListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{binding_id}", response_model=SiteLocaleBindingRead)
async def get_site_locale_binding(
    binding_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOCALES_VIEW)),
):
    return await LocalizationQueries(db).get_site_locale_binding(tenant_id, binding_id)


@router.patch("/{binding_id}", response_model=SiteLocaleBindingRead)
async def update_site_locale_binding(
    binding_id: UUID,
    body: SiteLocaleBindingUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOCALES_UPDATE)),
):
    return await LocalizationCommands(db).update_site_locale_binding(
        tenant_id, binding_id, body, actor=user
    )


@router.delete("/{binding_id}", response_model=SiteLocaleBindingRead)
async def delete_site_locale_binding(
    binding_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOCALES_DELETE)),
):
    return await LocalizationCommands(db).soft_delete_site_locale_binding(
        tenant_id, binding_id, actor=user
    )
