"""
Tag API router for ClaudeTools.

This module defines all REST API endpoints for managing tags, including
CRUD operations with proper authentication, validation, and error handling.
"""

from uuid import UUID

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from api.database import get_db
from api.middleware.auth import get_current_user
from api.schemas.tag import (
    TagCreate,
    TagResponse,
    TagUpdate,
)
from api.services import tag_service

# Create router with prefix and tags
router = APIRouter()


@router.get(
    "",
    response_model=dict,
    summary="List all tags",
    description="Retrieve a paginated list of all tags with optional filtering",
    status_code=status.HTTP_200_OK,
)
def list_tags(
    skip: int = Query(
        default=0,
        ge=0,
        description="Number of records to skip for pagination"
    ),
    limit: int = Query(
        default=100,
        ge=1,
        le=1000,
        description="Maximum number of records to return (max 1000)"
    ),
    category: str = Query(
        default=None,
        description="Filter by category (technology, client, infrastructure, problem_type, action, service)"
    ),
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """
    List all tags with pagination.

    - **skip**: Number of tags to skip (default: 0)
    - **limit**: Maximum number of tags to return (default: 100, max: 1000)
    - **category**: Filter by category (optional)

    Returns a list of tags with pagination metadata.

    **Example Request:**
    ```
    GET /api/tags?skip=0&limit=50&category=technology
    Authorization: Bearer <token>
    ```

    **Example Response:**
    ```json
    {
        "total": 15,
        "skip": 0,
        "limit": 50,
        "tags": [
            {
                "id": "123e4567-e89b-12d3-a456-426614174000",
                "name": "Windows",
                "category": "technology",
                "description": "Microsoft Windows operating system",
                "usage_count": 42,
                "created_at": "2024-01-15T10:30:00Z",
                "updated_at": "2024-01-15T10:30:00Z"
            }
        ]
    }
    ```
    """
    try:
        if category:
            tags, total = tag_service.get_tags_by_category(db, category, skip, limit)
        else:
            tags, total = tag_service.get_tags(db, skip, limit)

        return {
            "total": total,
            "skip": skip,
            "limit": limit,
            "tags": [TagResponse.model_validate(tag) for tag in tags]
        }

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to retrieve tags: {str(e)}"
        )


@router.get(
    "/{tag_id}",
    response_model=TagResponse,
    summary="Get tag by ID",
    description="Retrieve a single tag by its unique identifier",
    status_code=status.HTTP_200_OK,
    responses={
        200: {
            "description": "Tag found and returned",
            "model": TagResponse,
        },
        404: {
            "description": "Tag not found",
            "content": {
                "application/json": {
                    "example": {"detail": "Tag with ID 123e4567-e89b-12d3-a456-426614174000 not found"}
                }
            },
        },
    },
)
def get_tag(
    tag_id: UUID,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Get a specific tag by ID.

    - **tag_id**: UUID of the tag to retrieve

    Returns the complete tag details.

    **Example Request:**
    ```
    GET /api/tags/123e4567-e89b-12d3-a456-426614174000
    Authorization: Bearer <token>
    ```

    **Example Response:**
    ```json
    {
        "id": "123e4567-e89b-12d3-a456-426614174000",
        "name": "Windows",
        "category": "technology",
        "description": "Microsoft Windows operating system",
        "usage_count": 42,
        "created_at": "2024-01-15T10:30:00Z",
        "updated_at": "2024-01-15T10:30:00Z"
    }
    ```
    """
    tag = tag_service.get_tag_by_id(db, tag_id)
    return TagResponse.model_validate(tag)


@router.post(
    "",
    response_model=TagResponse,
    summary="Create new tag",
    description="Create a new tag with the provided details",
    status_code=status.HTTP_201_CREATED,
    responses={
        201: {
            "description": "Tag created successfully",
            "model": TagResponse,
        },
        409: {
            "description": "Tag with name already exists",
            "content": {
                "application/json": {
                    "example": {"detail": "Tag with name 'Windows' already exists"}
                }
            },
        },
        422: {
            "description": "Validation error",
            "content": {
                "application/json": {
                    "example": {
                        "detail": [
                            {
                                "loc": ["body", "name"],
                                "msg": "field required",
                                "type": "value_error.missing"
                            }
                        ]
                    }
                }
            },
        },
    },
)
def create_tag(
    tag_data: TagCreate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Create a new tag.

    Requires a valid JWT token with appropriate permissions.

    **Example Request:**
    ```json
    POST /api/tags
    Authorization: Bearer <token>
    Content-Type: application/json

    {
        "name": "Windows",
        "category": "technology",
        "description": "Microsoft Windows operating system"
    }
    ```

    **Example Response:**
    ```json
    {
        "id": "123e4567-e89b-12d3-a456-426614174000",
        "name": "Windows",
        "category": "technology",
        "description": "Microsoft Windows operating system",
        "usage_count": 0,
        "created_at": "2024-01-15T10:30:00Z",
        "updated_at": "2024-01-15T10:30:00Z"
    }
    ```
    """
    tag = tag_service.create_tag(db, tag_data)
    return TagResponse.model_validate(tag)


@router.put(
    "/{tag_id}",
    response_model=TagResponse,
    summary="Update tag",
    description="Update an existing tag's details",
    status_code=status.HTTP_200_OK,
    responses={
        200: {
            "description": "Tag updated successfully",
            "model": TagResponse,
        },
        404: {
            "description": "Tag not found",
            "content": {
                "application/json": {
                    "example": {"detail": "Tag with ID 123e4567-e89b-12d3-a456-426614174000 not found"}
                }
            },
        },
        409: {
            "description": "Conflict with existing tag",
            "content": {
                "application/json": {
                    "example": {"detail": "Tag with name 'Windows' already exists"}
                }
            },
        },
    },
)
def update_tag(
    tag_id: UUID,
    tag_data: TagUpdate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Update an existing tag.

    - **tag_id**: UUID of the tag to update

    Only provided fields will be updated. All fields are optional.

    **Example Request:**
    ```json
    PUT /api/tags/123e4567-e89b-12d3-a456-426614174000
    Authorization: Bearer <token>
    Content-Type: application/json

    {
        "description": "Updated description for Windows",
        "category": "infrastructure"
    }
    ```

    **Example Response:**
    ```json
    {
        "id": "123e4567-e89b-12d3-a456-426614174000",
        "name": "Windows",
        "category": "infrastructure",
        "description": "Updated description for Windows",
        "usage_count": 42,
        "created_at": "2024-01-15T10:30:00Z",
        "updated_at": "2024-01-15T14:20:00Z"
    }
    ```
    """
    tag = tag_service.update_tag(db, tag_id, tag_data)
    return TagResponse.model_validate(tag)


@router.delete(
    "/{tag_id}",
    response_model=dict,
    summary="Delete tag",
    description="Delete a tag by its ID",
    status_code=status.HTTP_200_OK,
    responses={
        200: {
            "description": "Tag deleted successfully",
            "content": {
                "application/json": {
                    "example": {
                        "message": "Tag deleted successfully",
                        "tag_id": "123e4567-e89b-12d3-a456-426614174000"
                    }
                }
            },
        },
        404: {
            "description": "Tag not found",
            "content": {
                "application/json": {
                    "example": {"detail": "Tag with ID 123e4567-e89b-12d3-a456-426614174000 not found"}
                }
            },
        },
    },
)
def delete_tag(
    tag_id: UUID,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Delete a tag.

    - **tag_id**: UUID of the tag to delete

    This is a permanent operation and cannot be undone.

    **Example Request:**
    ```
    DELETE /api/tags/123e4567-e89b-12d3-a456-426614174000
    Authorization: Bearer <token>
    ```

    **Example Response:**
    ```json
    {
        "message": "Tag deleted successfully",
        "tag_id": "123e4567-e89b-12d3-a456-426614174000"
    }
    ```
    """
    return tag_service.delete_tag(db, tag_id)
