"""Tracking session APIs — Phase 10.7."""
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.tracking import TrackingCommands
from app.models.types import TrackingSessionStatus
from app.permissions.definitions import (
    TRACKING_POINTS_MANAGE,
    TRACKING_POINTS_VIEW,
    TRACKING_SESSIONS_CREATE,
    TRACKING_SESSIONS_UPDATE,
    TRACKING_SESSIONS_VIEW,
)
from app.queries.tracking import TrackingQueries
from app.schemas.tracking import (
    TrackingPointCreate,
    TrackingPointRead,
    TrackingSessionCreate,
    TrackingSessionListResponse,
    TrackingSessionRead,
    TrackingSessionUpdate,
)
from app.specifications.tracking import TrackingSessionListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    status_filter: TrackingSessionStatus | None = Query(default=None, alias="status"),
    dispatch_job_id: UUID | None = Query(default=None),
    driver_id: UUID | None = Query(default=None),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> TrackingSessionListSpec:
    return TrackingSessionListSpec(
        status=status_filter,
        dispatch_job_id=dispatch_job_id,
        driver_id=driver_id,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post("/sessions", response_model=TrackingSessionRead, status_code=status.HTTP_201_CREATED)
async def start_session(
    body: TrackingSessionCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TRACKING_SESSIONS_CREATE)),
):
    return await TrackingCommands(db).start_session(tenant_id, body, actor=user)


@router.get("/sessions", response_model=TrackingSessionListResponse)
async def list_sessions(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: TrackingSessionListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(TRACKING_SESSIONS_VIEW)),
):
    items, total = await TrackingQueries(db).list_sessions(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return TrackingSessionListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/sessions/{session_id}", response_model=TrackingSessionRead)
async def get_session(
    session_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(TRACKING_SESSIONS_VIEW)),
):
    return await TrackingQueries(db).get_session(tenant_id, session_id)


@router.patch("/sessions/{session_id}", response_model=TrackingSessionRead)
async def update_session(
    session_id: UUID,
    body: TrackingSessionUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TRACKING_SESSIONS_UPDATE)),
):
    return await TrackingCommands(db).update_session(
        tenant_id, session_id, body, actor=user
    )


@router.post(
    "/sessions/{session_id}/points",
    response_model=TrackingPointRead,
    status_code=status.HTTP_201_CREATED,
)
async def record_point(
    session_id: UUID,
    body: TrackingPointCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TRACKING_POINTS_MANAGE)),
):
    return await TrackingCommands(db).record_point(
        tenant_id, session_id, body, actor=user
    )


@router.get("/sessions/{session_id}/points", response_model=list[TrackingPointRead])
async def list_points(
    session_id: UUID,
    limit: int = Query(default=500, ge=1, le=2000),
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(TRACKING_POINTS_VIEW)),
):
    return await TrackingQueries(db).list_points(tenant_id, session_id, limit=limit)
