import logging
from fastapi import APIRouter, HTTPException, Depends, UploadFile, File, status

from mini_videorag.temporal.api.schemas.storage import (
    StorageObjectResponse,
    StorageListResponse,
    StorageUrlResponse,
)
from mini_videorag.temporal.api.services import StorageService
from mini_videorag.temporal.api.dependencies import get_storage_service

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/storage", tags=["Storage"])


@router.post(
    "/upload",
    summary="Upload video to storage",
    description="""
    Upload a video file to MinIO/S3 storage.""",
)
async def upload_file(
    file: UploadFile = File(..., description="Video file to upload"),
    key: str = File(..., description="Storage key (e.g., 'videos/myvideo.mp4')"),
    service: StorageService = Depends(get_storage_service),
):
    """Upload a file to storage."""
    try:
        content = await file.read()
        result = await service.upload_file(key, content)
        return result
    except Exception as e:
        logger.error(f"Failed to upload file: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to upload file: {str(e)}",
        ) from e


@router.get(
    "/objects",
    response_model=StorageListResponse,
    summary="List storage objects",
    description="""
    List objects in storage (MinIO/S3). Useful for finding uploaded videos.""",
)
async def list_storage_objects(
    prefix: str = "",
    service: StorageService = Depends(get_storage_service),
):
    """List objects in storage."""
    try:
        objects = service.list_objects(prefix=prefix)
        return StorageListResponse(
            objects=[StorageObjectResponse(**obj) for obj in objects],
            count=len(objects),
            prefix=prefix,
        )
    except Exception as e:
        logger.error(f"Failed to list storage objects: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to list storage objects: {str(e)}",
        ) from e


@router.get(
    "/url/{key:path}",
    response_model=StorageUrlResponse,
    summary="Get presigned URL for object",
    description="""
    Get a presigned URL for accessing a storage object.""",
)
async def get_storage_url(
    key: str,
    expires_in: int = 3600,
    service: StorageService = Depends(get_storage_service),
):
    """Get presigned URL for a storage object."""
    try:
        result = service.get_presigned_url(key, expires_in)
        return StorageUrlResponse(**result)
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e),
        ) from e
    except Exception as e:
        logger.error(f"Failed to get storage URL: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to get storage URL: {str(e)}",
        ) from e
