"""Analytics snapshot APIs — Phase 11.10."""
from uuid import UUID

from fastapi import APIRouter, Depends, Query, Response, 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.analytics import AnalyticsCommands
from app.permissions.definitions import (
    ANALYTICS_CREATE,
    ANALYTICS_DELETE,
    ANALYTICS_MANAGE,
    ANALYTICS_UPDATE,
    ANALYTICS_VIEW,
)
from app.queries.analytics import AnalyticsQueries
from app.schemas.analytics import (
    AnalyticsSnapshotListResponse,
    AnalyticsSnapshotRead,
    AnalyticsSnapshotRefresh,
    AnalyticsSnapshotUpdate,
)
from app.specifications.analytics import SNAPSHOT_SORT, AnalyticsSnapshotListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _spec(
    workspace_id: UUID | None = None,
    site_id: UUID | None = None,
    report_id: UUID | None = None,
    status_filter: str | None = Query(None, alias="status"),
    q: str | None = Query(None, max_length=100),
    sort_by: str = "created_at",
    sort_dir: str = Query("desc", pattern="^(?i)(asc|desc)$"),
):
    return AnalyticsSnapshotListSpec(
        workspace_id=workspace_id,
        site_id=site_id,
        report_id=report_id,
        status=status_filter,
        q=q,
        sort_by=sort_by if sort_by in SNAPSHOT_SORT else "created_at",
        sort_dir=sort_dir,
    )


@router.post("/refresh", response_model=AnalyticsSnapshotRead, status_code=201)
async def refresh(
    body: AnalyticsSnapshotRefresh,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(ANALYTICS_MANAGE)),
):
    return await AnalyticsCommands(db).refresh_snapshot(tenant_id, body, actor=user)


@router.get("", response_model=AnalyticsSnapshotListResponse)
async def list_items(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: AnalyticsSnapshotListSpec = Depends(_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(ANALYTICS_VIEW)),
):
    items, total = await AnalyticsQueries(db).list_snapshots(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return AnalyticsSnapshotListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{entity_id}", response_model=AnalyticsSnapshotRead)
async def get(
    entity_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(ANALYTICS_VIEW)),
):
    return await AnalyticsQueries(db).get_snapshot(tenant_id, entity_id)


@router.patch("/{entity_id}", response_model=AnalyticsSnapshotRead)
async def update(
    entity_id: UUID,
    body: AnalyticsSnapshotUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(ANALYTICS_UPDATE)),
):
    return await AnalyticsCommands(db).update_snapshot(tenant_id, entity_id, body, actor=user)


@router.delete("/{entity_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete(
    entity_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(ANALYTICS_DELETE)),
):
    await AnalyticsCommands(db).delete_snapshot(tenant_id, entity_id, actor=user)
    return Response(status_code=204)
