"""Attachments API client for V1."""

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from concentriq.client import ConcentriqClient


class Attachments:
    """Client for Attachment resources (/api/attachments).

    Attachments are arbitrary files associated with resources (ImageSets, Folders, etc.).
    Each attachment includes a signed URL for downloading (24-hour expiry).
    """

    def __init__(self, client: "ConcentriqClient"):
        """Initialize with client instance.

        Args:
            client: The ConcentriqClient instance
        """
        self._client = client
        self._base_path = "/api/attachments"

    def list(
        self,
        folder_id: int | None = None,
        image_set_id: int | None = None,
        attachment_id: int | None = None,
        storage_key: str | None = None,
    ) -> list[dict[str, Any]]:
        """List all attachments with optional filters.

        Args:
            folder_id: Filter by folder ID
            image_set_id: Filter by image set ID
            attachment_id: Filter by attachment ID
            storage_key: Filter by storage key

        Returns:
            List of attachment data with signed URLs

        Raises:
            AuthenticationError: If not authenticated
        """
        filters: dict[str, Any] = {}
        if folder_id is not None:
            filters["folderId"] = [folder_id]
        if image_set_id is not None:
            filters["imageSetId"] = [image_set_id]
        if attachment_id is not None:
            filters["attachmentId"] = [attachment_id]
        if storage_key is not None:
            filters["storageKey"] = [storage_key]

        params = {}
        if filters:
            import json

            params["filters"] = json.dumps(filters)

        response = self._client._request("GET", self._base_path, params=params)
        data = response.json()
        return data.get("data", {}).get("attachments", [])

    def create(self, data: dict[str, Any]) -> dict[str, Any]:
        """Create a new attachment (get upload credentials).

        Args:
            data: Attachment data
                - name: Filename (required)
                - resourceType: Type of resource (required, e.g., "imageSets", "folders")
                - resourceId: ID of the resource (required)

        Returns:
            Dictionary with attachmentId and storageKey for S3 upload

        Raises:
            AuthenticationError: If not authenticated
            ValidationError: If parameters are invalid or file extension not allowed
            NotFoundError: If resource doesn't exist

        Note:
            Requires canManageMetadataValues permission on the resource.
            After creating the attachment, use the storageKey to upload the file to S3.
        """
        response = self._client._request("POST", self._base_path, json=data)
        result = response.json()
        return result.get("data", {})

    def delete(self, id: int) -> dict[str, Any]:
        """Delete an attachment.

        Args:
            id: Attachment ID

        Returns:
            Success message dictionary

        Raises:
            AuthenticationError: If not authenticated
            NotFoundError: If attachment doesn't exist

        Note:
            Requires canManageMetadataValues permission on the resource.
            This operation requires a reason for change (audit trail).
        """
        response = self._client._request("DELETE", f"{self._base_path}/{id}")
        result = response.json()
        return result.get("data", {})
