"""Storage resource for the Cerebe SDK."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from .._response import APIResponse

if TYPE_CHECKING:
    from .._client import AsyncCerebe, Cerebe


class StorageResource:
    """Sync file storage operations."""

    def __init__(self, client: Cerebe) -> None:
        self._client = client

    def upload(
        self,
        content: str,
        filename: str,
        content_type: str,
        *,
        user_id: str | None = None,
        session_id: str | None = None,
        purpose: str = "general",
    ) -> APIResponse[Any]:
        """Upload a file (base64-encoded content)."""
        return self._client.request(
            "POST",
            "/api/v1/storage/upload-base64",
            json={
                "content": content,
                "filename": filename,
                "content_type": content_type,
                "user_id": user_id,
                "session_id": session_id,
                "purpose": purpose,
            },
        )

    def get(self, upload_id: str) -> APIResponse[Any]:
        """Get file metadata by upload ID."""
        return self._client.request("GET", f"/api/v1/storage/{upload_id}/metadata")

    def get_url(self, upload_id: str, *, expiry_seconds: int | None = None) -> APIResponse[Any]:
        """Get an ephemeral download URL."""
        params: dict[str, str] = {}
        if expiry_seconds is not None:
            params["expiry_seconds"] = str(expiry_seconds)
        return self._client.request(
            "GET", f"/api/v1/storage/{upload_id}/ephemeral-url", params=params or None
        )

    def file_url(self, file_id: str, *, expiry_seconds: int | None = None) -> APIResponse[Any]:
        """Get an ephemeral download URL by file ID."""
        params: dict[str, str] = {}
        if expiry_seconds is not None:
            params["expiry_seconds"] = str(expiry_seconds)
        return self._client.request(
            "GET", f"/api/v1/storage/file/{file_id}/ephemeral-url", params=params or None
        )

    def check_hash(self, content_hash: str) -> APIResponse[Any]:
        """Check if a file exists by hash (deduplication)."""
        return self._client.request(
            "POST",
            "/api/v1/storage/check-hash",
            json={"content_hash": content_hash},
        )

    def presigned_upload(
        self,
        file_name: str,
        file_type: str,
        file_size: int,
        content_hash: str,
        tenant_id: str,
        *,
        user_id: str | None = None,
        purpose: str | None = None,
    ) -> APIResponse[Any]:
        """Get a presigned URL for direct file upload."""
        body: dict[str, Any] = {
            "file_name": file_name,
            "file_type": file_type,
            "file_size": file_size,
            "content_hash": content_hash,
            "tenant_id": tenant_id,
        }
        if user_id:
            body["user_id"] = user_id
        if purpose:
            body["purpose"] = purpose
        return self._client.request("POST", "/api/v1/storage/presigned-upload", json=body)

    def analyze_content(
        self,
        upload_id: str,
        *,
        context: str | None = None,
    ) -> APIResponse[Any]:
        """Analyze uploaded file content type and properties."""
        params: dict[str, str] = {"upload_id": upload_id}
        if context:
            params["context"] = context
        return self._client.request("POST", "/api/v1/storage/analyze-content", params=params)

    def extract(
        self,
        url: str,
        *,
        processing: list[str] | None = None,
        session_id: str | None = None,
    ) -> APIResponse[Any]:
        """Extract content from a URL."""
        body: dict[str, Any] = {"url": url}
        if processing:
            body["processing"] = processing
        if session_id:
            body["session_id"] = session_id
        return self._client.request("POST", "/api/v1/storage/extract", json=body)


class AsyncStorageResource:
    """Async file storage operations."""

    def __init__(self, client: AsyncCerebe) -> None:
        self._client = client

    async def upload(
        self,
        content: str,
        filename: str,
        content_type: str,
        *,
        user_id: str | None = None,
        session_id: str | None = None,
        purpose: str = "general",
    ) -> APIResponse[Any]:
        """Upload a file (base64-encoded content)."""
        return await self._client.request(
            "POST",
            "/api/v1/storage/upload-base64",
            json={
                "content": content,
                "filename": filename,
                "content_type": content_type,
                "user_id": user_id,
                "session_id": session_id,
                "purpose": purpose,
            },
        )

    async def get(self, upload_id: str) -> APIResponse[Any]:
        """Get file metadata by upload ID."""
        return await self._client.request("GET", f"/api/v1/storage/{upload_id}/metadata")

    async def get_url(self, upload_id: str, *, expiry_seconds: int | None = None) -> APIResponse[Any]:
        """Get an ephemeral download URL."""
        params: dict[str, str] = {}
        if expiry_seconds is not None:
            params["expiry_seconds"] = str(expiry_seconds)
        return await self._client.request(
            "GET", f"/api/v1/storage/{upload_id}/ephemeral-url", params=params or None
        )

    async def file_url(self, file_id: str, *, expiry_seconds: int | None = None) -> APIResponse[Any]:
        """Get an ephemeral download URL by file ID."""
        params: dict[str, str] = {}
        if expiry_seconds is not None:
            params["expiry_seconds"] = str(expiry_seconds)
        return await self._client.request(
            "GET", f"/api/v1/storage/file/{file_id}/ephemeral-url", params=params or None
        )

    async def check_hash(self, content_hash: str) -> APIResponse[Any]:
        """Check if a file exists by hash (deduplication)."""
        return await self._client.request(
            "POST",
            "/api/v1/storage/check-hash",
            json={"content_hash": content_hash},
        )

    async def presigned_upload(
        self,
        file_name: str,
        file_type: str,
        file_size: int,
        content_hash: str,
        tenant_id: str,
        *,
        user_id: str | None = None,
        purpose: str | None = None,
    ) -> APIResponse[Any]:
        """Get a presigned URL for direct file upload."""
        body: dict[str, Any] = {
            "file_name": file_name,
            "file_type": file_type,
            "file_size": file_size,
            "content_hash": content_hash,
            "tenant_id": tenant_id,
        }
        if user_id:
            body["user_id"] = user_id
        if purpose:
            body["purpose"] = purpose
        return await self._client.request("POST", "/api/v1/storage/presigned-upload", json=body)

    async def analyze_content(
        self,
        upload_id: str,
        *,
        context: str | None = None,
    ) -> APIResponse[Any]:
        """Analyze uploaded file content type and properties."""
        params: dict[str, str] = {"upload_id": upload_id}
        if context:
            params["context"] = context
        return await self._client.request("POST", "/api/v1/storage/analyze-content", params=params)

    async def extract(
        self,
        url: str,
        *,
        processing: list[str] | None = None,
        session_id: str | None = None,
    ) -> APIResponse[Any]:
        """Extract content from a URL."""
        body: dict[str, Any] = {"url": url}
        if processing:
            body["processing"] = processing
        if session_id:
            body["session_id"] = session_id
        return await self._client.request("POST", "/api/v1/storage/extract", json=body)
