"""Localization content 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 (
    ExperienceLocalizationListResponse,
    ExperienceLocalizationRead,
    ExperienceLocalizationUpdate,
    ExperienceLocalizationUpsert,
)
from app.specifications.localization import (
    LOCALIZATION_SORT_FIELDS,
    LocalizationListSpec,
)
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

_STATUSES = {"draft", "active", "archived"}
_TARGETS = {
    "site",
    "page",
    "component_placement",
    "template",
    "theme",
    "layout",
    "media_ref",
}
_DIRECTIONS = {"rtl", "ltr"}


def _list_spec(
    workspace_id: UUID | None = Query(default=None),
    target_type: str | None = Query(default=None, max_length=50),
    target_id: UUID | None = Query(default=None),
    locale: str | None = Query(default=None, max_length=16),
    text_direction: str | None = Query(default=None, max_length=3),
    status_filter: str | None = Query(default=None, alias="status"),
    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)$"),
) -> LocalizationListSpec:
    if sort_by not in LOCALIZATION_SORT_FIELDS:
        sort_by = "created_at"
    return LocalizationListSpec(
        workspace_id=workspace_id,
        target_type=target_type if target_type in _TARGETS else None,
        target_id=target_id,
        locale=locale,
        text_direction=text_direction if text_direction in _DIRECTIONS else None,
        status=status_filter if status_filter in _STATUSES else None,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


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


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


@router.get("/{localization_id}", response_model=ExperienceLocalizationRead)
async def get_localization(
    localization_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_localization(tenant_id, localization_id)


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


@router.delete("/{localization_id}", response_model=ExperienceLocalizationRead)
async def delete_localization(
    localization_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_localization(
        tenant_id, localization_id, actor=user
    )
