"""Template instantiation 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_VIEW
from app.queries.templates import TemplateQueries
from app.schemas.templates import (
    TemplateInstantiateRequest,
    TemplateInstantiateResponse,
    TemplateInstantiationListResponse,
    TemplateInstantiationRead,
)
from app.specifications.templates import INSTANTIATION_SORT_FIELDS, InstantiationListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

_STATUSES = {"pending", "completed", "failed"}


def _list_spec(
    template_id: UUID | None = Query(default=None),
    site_id: UUID | None = Query(default=None),
    page_id: UUID | None = Query(default=None),
    workspace_id: UUID | None = Query(default=None),
    status_filter: str | None = Query(default=None, alias="status"),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> InstantiationListSpec:
    if sort_by not in INSTANTIATION_SORT_FIELDS:
        sort_by = "created_at"
    return InstantiationListSpec(
        template_id=template_id,
        site_id=site_id,
        page_id=page_id,
        workspace_id=workspace_id,
        status=status_filter if status_filter in _STATUSES else None,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post(
    "",
    response_model=TemplateInstantiateResponse,
    status_code=status.HTTP_201_CREATED,
)
async def instantiate_template(
    body: TemplateInstantiateRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TEMPLATES_CREATE)),
):
    record, page = await TemplateCommands(db).instantiate(
        tenant_id, body, actor=user
    )
    return TemplateInstantiateResponse(
        instantiation=record,
        page_id=page.id if page is not None else record.page_id,
    )


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


@router.get("/{instantiation_id}", response_model=TemplateInstantiationRead)
async def get_instantiation(
    instantiation_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_instantiation(tenant_id, instantiation_id)
