"""Template catalog APIs — Phase 11.4."""
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.templates import TemplateCommands
from app.permissions.definitions import (
    TEMPLATES_CREATE,
    TEMPLATES_DELETE,
    TEMPLATES_MANAGE,
    TEMPLATES_UPDATE,
    TEMPLATES_VIEW,
)
from app.queries.templates import TemplateQueries
from app.schemas.templates import (
    ExperienceTemplateCreate,
    ExperienceTemplateListResponse,
    ExperienceTemplateRead,
    ExperienceTemplateUpdate,
)
from app.specifications.templates import TEMPLATE_SORT_FIELDS, TemplateListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

_STATUSES = {"draft", "active", "deprecated", "archived"}


def _list_spec(
    workspace_id: UUID | None = Query(default=None),
    status_filter: str | None = Query(default=None, alias="status"),
    page_type: str | None = Query(default=None, max_length=50),
    is_starter_pack: bool | None = Query(default=None),
    category: str | None = Query(default=None, max_length=100),
    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)$"),
) -> TemplateListSpec:
    if sort_by not in TEMPLATE_SORT_FIELDS:
        sort_by = "created_at"
    return TemplateListSpec(
        workspace_id=workspace_id,
        status=status_filter if status_filter in _STATUSES else None,
        page_type=page_type,
        is_starter_pack=is_starter_pack,
        category=category,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post(
    "", response_model=ExperienceTemplateRead, status_code=status.HTTP_201_CREATED
)
async def create_template(
    body: ExperienceTemplateCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TEMPLATES_CREATE)),
):
    return await TemplateCommands(db).create_template(tenant_id, body, actor=user)


@router.get("", response_model=ExperienceTemplateListResponse)
async def list_templates(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: TemplateListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(TEMPLATES_VIEW)),
):
    items, total = await TemplateQueries(db).list_templates(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return ExperienceTemplateListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{template_id}", response_model=ExperienceTemplateRead)
async def get_template(
    template_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(TEMPLATES_VIEW)),
):
    return await TemplateQueries(db).get_template(tenant_id, template_id)


@router.patch("/{template_id}", response_model=ExperienceTemplateRead)
async def update_template(
    template_id: UUID,
    body: ExperienceTemplateUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TEMPLATES_UPDATE)),
):
    return await TemplateCommands(db).update_template(
        tenant_id, template_id, body, actor=user
    )


@router.post("/{template_id}/activate", response_model=ExperienceTemplateRead)
async def activate_template(
    template_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TEMPLATES_MANAGE)),
):
    return await TemplateCommands(db).activate_template(
        tenant_id, template_id, actor=user
    )


@router.post("/{template_id}/deprecate", response_model=ExperienceTemplateRead)
async def deprecate_template(
    template_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TEMPLATES_MANAGE)),
):
    return await TemplateCommands(db).deprecate_template(
        tenant_id, template_id, actor=user
    )


@router.post("/{template_id}/archive", response_model=ExperienceTemplateRead)
async def archive_template(
    template_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TEMPLATES_MANAGE)),
):
    return await TemplateCommands(db).archive_template(
        tenant_id, template_id, actor=user
    )


@router.post("/{template_id}/delete", response_model=ExperienceTemplateRead)
async def soft_delete_template(
    template_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TEMPLATES_DELETE)),
):
    return await TemplateCommands(db).soft_delete_template(
        tenant_id, template_id, actor=user
    )
