import logging
from typing import Optional

from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel

from api.auth import optional_jwt_auth
from qdrant_client_wrapper import qdrant_wrapper, ALL_DEFAULT_COLLECTIONS

logger = logging.getLogger("rag-service.api.collections")

router = APIRouter(prefix="/api/v1/collections")


# ---- Request / Response models --------------------------------------------

class CreateCollectionRequest(BaseModel):
    name: str
    vector_size: int = 1536


class CollectionInfoResponse(BaseModel):
    name: str
    vectors_count: Optional[int] = None
    points_count: Optional[int] = None
    status: Optional[str] = None
    vector_size: Optional[int] = None


# ---- Endpoints ------------------------------------------------------------

@router.post("", status_code=201)
async def create_collection(body: CreateCollectionRequest, request: Request):
    """Create a new Qdrant collection."""
    optional_jwt_auth(request)
    try:
        created = await qdrant_wrapper.create_collection(body.name, body.vector_size)
        return {
            "collection": body.name,
            "vector_size": body.vector_size,
            "created": created,
        }
    except Exception as exc:
        logger.error("Failed to create collection '%s': %s", body.name, exc)
        raise HTTPException(status_code=500, detail=str(exc))


@router.get("")
async def list_collections(request: Request):
    """List all Qdrant collections."""
    optional_jwt_auth(request)
    try:
        result = qdrant_wrapper.client.get_collections()
        names = [c.name for c in result.collections]
        return {"collections": names, "count": len(names)}
    except Exception as exc:
        logger.error("Failed to list collections: %s", exc)
        raise HTTPException(status_code=500, detail=str(exc))


@router.get("/defaults")
async def list_default_collections(request: Request):
    """Return the pre-configured default collections and their dimensions."""
    optional_jwt_auth(request)
    return {"defaults": ALL_DEFAULT_COLLECTIONS}


@router.get("/{collection_name}")
async def get_collection_info(collection_name: str, request: Request):
    """Get stats for a single collection."""
    optional_jwt_auth(request)
    try:
        info = await qdrant_wrapper.get_collection_info(collection_name)
        return info
    except Exception as exc:
        logger.error("Failed to get collection info for '%s': %s", collection_name, exc)
        raise HTTPException(status_code=404, detail=f"Collection '{collection_name}' not found or error: {exc}")
