from typing import Optional

from ....types.api.data_store.store import GetFilesAndFoldersResponse
from ..._request_handler import AsyncRequestHandler
from .base_store import BaseStore


class AsyncStore(BaseStore):
    """Async Store client for browsing files and folders."""

    def __init__(self, request_handler: AsyncRequestHandler):
        super().__init__(request_handler)

    async def get_files_and_folders(
        self,
        store_connector_id: str,
        project_id: str,
        folder_id: Optional[str] = None,
        page_number: Optional[int] = None,
        page_size: Optional[int] = None,
        sort_by: Optional[str] = None,
        sort_order: Optional[str] = None,
        filter_by: Optional[str] = None,
        filter_value: Optional[str] = None,
        correlation_id: Optional[str] = None,
    ) -> GetFilesAndFoldersResponse:
        """
        Retrieve files and folders from a store connector in the Airia data store.

        This method retrieves information about files and folders in the specified
        store connector, with optional navigation into specific folders and support
        for pagination, sorting, and filtering.

        Args:
            store_connector_id: The unique identifier of the store connector (GUID format)
            project_id: The unique identifier of the project (GUID format)
            folder_id: Optional folder ID to browse within a specific folder (GUID format).
                If not provided, retrieves items from the root level.
            page_number: Page number for pagination (1-indexed)
            page_size: Number of items per page
            sort_by: Field to sort by (e.g., "lastSyncAt", "name")
            sort_order: Sort order ("ASC" or "DESC")
            filter_by: Field to filter by
            filter_value: Value to filter by
            correlation_id: Optional correlation ID for request tracing

        Returns:
            GetFilesAndFoldersResponse: List of files and folders with metadata and total count

        Raises:
            AiriaAPIError: If the API request fails, including cases where:
                - The store_connector_id doesn't exist (404)
                - The project_id doesn't exist (404)
                - The folder_id is invalid (404)
                - Authentication fails (401)
                - Access is forbidden (403)
                - Server errors (5xx)
            ValueError: If required parameters are missing or invalid

        Example:
            ```python
            from airia import AiriaAsyncClient

            async with AiriaAsyncClient(api_key="your_api_key") as client:
                # Get files and folders from root level
                response = await client.data_store.store.get_files_and_folders(
                    store_connector_id="02b2ef8b-8bff-42c3-9ddb-e325c893176e",
                    project_id="0196162b-1553-71b2-8ebf-44594717936e"
                )

                # Browse a specific folder with pagination and sorting
                response = await client.data_store.store.get_files_and_folders(
                    store_connector_id="02b2ef8b-8bff-42c3-9ddb-e325c893176e",
                    project_id="0196162b-1553-71b2-8ebf-44594717936e",
                    folder_id="3292db69-f365-4bb6-a2b6-a017a187fb77",
                    page_number=1,
                    page_size=50,
                    sort_by="lastSyncAt",
                    sort_order="DESC"
                )

                # Access the results
                if response.files_and_folders:
                    for item in response.files_and_folders:
                        print(f"{item.name} ({item.type})")
                        if item.type == "folder":
                            print(f"  Contains {item.file_count} files, {item.folder_count} folders")

                print(f"Total items: {response.total_count}")
            ```

        Note:
            The response includes:
            - files_and_folders: List of file and folder objects with metadata
            - total_count: Total number of items (useful for pagination)
        """
        request_data = self._pre_get_files_and_folders(
            store_connector_id=store_connector_id,
            project_id=project_id,
            folder_id=folder_id,
            page_number=page_number,
            page_size=page_size,
            sort_by=sort_by,
            sort_order=sort_order,
            filter_by=filter_by,
            filter_value=filter_value,
            correlation_id=correlation_id,
        )

        response = await self._request_handler.make_request(
            "GET", request_data, return_json=True
        )

        return GetFilesAndFoldersResponse(**response)
