"""
Admin Document Lock Routes

FastAPI endpoints for annotation lock management.
"""

from typing import Annotated
from uuid import UUID

from fastapi import APIRouter, HTTPException, Query

from backend.web.core.auth import AdminTokenDep, DocumentRepoDep
from backend.web.schemas.admin import (
    AnnotationLockRequest,
    AnnotationLockResponse,
)
from backend.web.schemas.common import ErrorResponse


def _validate_uuid(value: str, name: str = "ID") -> None:
    """Validate UUID format."""
    try:
        UUID(value)
    except ValueError:
        raise HTTPException(
            status_code=400,
            detail=f"Invalid {name} format. Must be a valid UUID.",
        )


def create_locks_router() -> APIRouter:
    """Create annotation locks router."""
    router = APIRouter(prefix="/admin/documents", tags=["Admin Locks"])

    @router.post(
        "/{document_id}/lock",
        response_model=AnnotationLockResponse,
        responses={
            401: {"model": ErrorResponse, "description": "Invalid token"},
            404: {"model": ErrorResponse, "description": "Document not found"},
            409: {"model": ErrorResponse, "description": "Document already locked"},
        },
        summary="Acquire annotation lock",
        description="Acquire a lock on a document to prevent concurrent annotation edits.",
    )
    async def acquire_lock(
        document_id: str,
        admin_token: AdminTokenDep,
        docs: DocumentRepoDep,
        request: AnnotationLockRequest = AnnotationLockRequest(),
    ) -> AnnotationLockResponse:
        """Acquire annotation lock for a document."""
        _validate_uuid(document_id, "document_id")

        # Verify ownership
        document = docs.get_by_token(document_id, admin_token)
        if document is None:
            raise HTTPException(
                status_code=404,
                detail="Document not found or does not belong to this token",
            )

        # Attempt to acquire lock
        updated_doc = docs.acquire_annotation_lock(
            document_id=document_id,
            admin_token=admin_token,
            duration_seconds=request.duration_seconds,
        )

        if updated_doc is None:
            raise HTTPException(
                status_code=409,
                detail="Document is already locked. Please try again later.",
            )

        return AnnotationLockResponse(
            document_id=document_id,
            locked=True,
            lock_expires_at=updated_doc.annotation_lock_until,
            message=f"Lock acquired for {request.duration_seconds} seconds",
        )

    @router.delete(
        "/{document_id}/lock",
        response_model=AnnotationLockResponse,
        responses={
            401: {"model": ErrorResponse, "description": "Invalid token"},
            404: {"model": ErrorResponse, "description": "Document not found"},
        },
        summary="Release annotation lock",
        description="Release the annotation lock on a document.",
    )
    async def release_lock(
        document_id: str,
        admin_token: AdminTokenDep,
        docs: DocumentRepoDep,
        force: Annotated[
            bool,
            Query(description="Force release (admin override)"),
        ] = False,
    ) -> AnnotationLockResponse:
        """Release annotation lock for a document."""
        _validate_uuid(document_id, "document_id")

        # Verify ownership
        document = docs.get_by_token(document_id, admin_token)
        if document is None:
            raise HTTPException(
                status_code=404,
                detail="Document not found or does not belong to this token",
            )

        # Release lock
        updated_doc = docs.release_annotation_lock(
            document_id=document_id,
            admin_token=admin_token,
            force=force,
        )

        if updated_doc is None:
            raise HTTPException(
                status_code=404,
                detail="Failed to release lock",
            )

        return AnnotationLockResponse(
            document_id=document_id,
            locked=False,
            lock_expires_at=None,
            message="Lock released successfully",
        )

    @router.patch(
        "/{document_id}/lock",
        response_model=AnnotationLockResponse,
        responses={
            401: {"model": ErrorResponse, "description": "Invalid token"},
            404: {"model": ErrorResponse, "description": "Document not found"},
            409: {"model": ErrorResponse, "description": "Lock expired or doesn't exist"},
        },
        summary="Extend annotation lock",
        description="Extend an existing annotation lock.",
    )
    async def extend_lock(
        document_id: str,
        admin_token: AdminTokenDep,
        docs: DocumentRepoDep,
        request: AnnotationLockRequest = AnnotationLockRequest(),
    ) -> AnnotationLockResponse:
        """Extend annotation lock for a document."""
        _validate_uuid(document_id, "document_id")

        # Verify ownership
        document = docs.get_by_token(document_id, admin_token)
        if document is None:
            raise HTTPException(
                status_code=404,
                detail="Document not found or does not belong to this token",
            )

        # Attempt to extend lock
        updated_doc = docs.extend_annotation_lock(
            document_id=document_id,
            admin_token=admin_token,
            additional_seconds=request.duration_seconds,
        )

        if updated_doc is None:
            raise HTTPException(
                status_code=409,
                detail="Lock doesn't exist or has expired. Please acquire a new lock.",
            )

        return AnnotationLockResponse(
            document_id=document_id,
            locked=True,
            lock_expires_at=updated_doc.annotation_lock_until,
            message=f"Lock extended by {request.duration_seconds} seconds",
        )

    return router
