"""Recording management for browser sessions."""

from typing import Any, Dict, List, Optional, TYPE_CHECKING

from ._models import RecordingItem, RecordingStartOptions
from ._types import RecordingStatus

if TYPE_CHECKING:
    from ._http import HTTPClient, AsyncHTTPClient


class Recording:
    """Recording manager for browser sessions.

    Provides methods to start, stop, and manage screen recordings.
    """

    def __init__(
        self,
        container_id: str,
        http_client: "HTTPClient",
    ):
        """Initialize recording manager.

        Args:
            container_id: The container ID
            http_client: HTTP client for API calls
        """
        self._container_id = container_id
        self._http_client = http_client

    def start(
        self,
        output_dir: Optional[str] = None,
        auto_upload: bool = False,
        framerate: int = 30,
        max_duration: Optional[int] = None,
        format: str = "mp4",
        resolution: Optional[str] = None,
        audio: bool = False,
        quality: str = "medium",
    ) -> RecordingItem:
        """Start a new screen recording session.

        Args:
            output_dir: Custom output directory for the recording file
            auto_upload: Automatically upload the recording to CDN when finished
            framerate: Frame rate for the recording (default: 30)
            max_duration: Maximum recording duration in milliseconds
            format: Video format for the recording (default: 'mp4')
            resolution: Resolution in format 'WIDTHxHEIGHT' (e.g., '1920x1080')
            audio: Whether to include audio in the recording (default: False)
            quality: Recording quality preset (default: 'medium')

        Returns:
            RecordingItem: Recording information
        """
        path = f"/v1/containers/{self._container_id}/recordings/start"

        request_body: Dict[str, Any] = {
            "format": format,
            "framerate": framerate,
            "audio": audio,
            "quality": quality,
        }

        if resolution:
            request_body["resolution"] = resolution
        if output_dir:
            request_body["output_dir"] = output_dir
        if auto_upload is not None:
            request_body["autoUpload"] = auto_upload
        if max_duration is not None:
            # Convert milliseconds to seconds for the API
            request_body["maxDuration"] = max_duration // 1000

        response = self._http_client.post(path, json_data=request_body)

        # Note: _handle_response already extracts 'data' if present, or returns the full response
        # So we can directly use 'response' here
        return RecordingItem.model_validate(response)

    def stop(self, recording_id: str) -> RecordingItem:
        """Stop an active recording session.

        Args:
            recording_id: The ID of the recording to stop

        Returns:
            RecordingItem: Updated recording information
        """
        path = f"/v1/containers/{self._container_id}/recordings/{recording_id}/stop"

        response = self._http_client.put(path)
        return RecordingItem.model_validate(response)

    def get(self, recording_id: str) -> RecordingItem:
        """Get information about a specific recording.

        Args:
            recording_id: The ID of the recording

        Returns:
            RecordingItem: Recording information
        """
        path = f"/v1/containers/{self._container_id}/recordings/{recording_id}/info"

        response = self._http_client.get(path)
        return RecordingItem.model_validate(response)

    def get_all(self, status: Optional[RecordingStatus] = None) -> List[RecordingItem]:
        """Get all recordings for this container.

        Args:
            status: Optional status filter

        Returns:
            List[RecordingItem]: List of recordings
        """
        path = f"/v1/containers/{self._container_id}/recordings"

        params = {}
        if status:
            params["status"] = status

        response = self._http_client.get(path, params=params)
        recordings = response.get("recordings", [])
        return [RecordingItem.model_validate(r) for r in recordings]


class AsyncRecording:
    """Async recording manager for browser sessions.

    Provides async methods to start, stop, and manage screen recordings.
    """

    def __init__(
        self,
        container_id: str,
        http_client: "AsyncHTTPClient",
    ):
        """Initialize async recording manager.

        Args:
            container_id: The container ID
            http_client: Async HTTP client for API calls
        """
        self._container_id = container_id
        self._http_client = http_client

    async def start(
        self,
        output_dir: Optional[str] = None,
        auto_upload: bool = False,
        framerate: int = 30,
        max_duration: Optional[int] = None,
        format: str = "mp4",
        resolution: Optional[str] = None,
        audio: bool = False,
        quality: str = "medium",
    ) -> RecordingItem:
        """Start a new screen recording session.

        Args:
            output_dir: Custom output directory for the recording file
            auto_upload: Automatically upload the recording to CDN when finished
            framerate: Frame rate for the recording (default: 30)
            max_duration: Maximum recording duration in milliseconds
            format: Video format for the recording (default: 'mp4')
            resolution: Resolution in format 'WIDTHxHEIGHT' (e.g., '1920x1080')
            audio: Whether to include audio in the recording (default: False)
            quality: Recording quality preset (default: 'medium')

        Returns:
            RecordingItem: Recording information
        """
        path = f"/v1/containers/{self._container_id}/recordings/start"

        request_body: Dict[str, Any] = {
            "format": format,
            "framerate": framerate,
            "audio": audio,
            "quality": quality,
        }

        if resolution:
            request_body["resolution"] = resolution
        if output_dir:
            request_body["output_dir"] = output_dir
        if auto_upload is not None:
            request_body["autoUpload"] = auto_upload
        if max_duration is not None:
            # Convert milliseconds to seconds for the API
            request_body["maxDuration"] = max_duration // 1000

        response = await self._http_client.post(path, json_data=request_body)
        return RecordingItem.model_validate(response)

    async def stop(self, recording_id: str) -> RecordingItem:
        """Stop an active recording session.

        Args:
            recording_id: The ID of the recording to stop

        Returns:
            RecordingItem: Updated recording information
        """
        path = f"/v1/containers/{self._container_id}/recordings/{recording_id}/stop"

        response = await self._http_client.put(path)
        return RecordingItem.model_validate(response)

    async def get(self, recording_id: str) -> RecordingItem:
        """Get information about a specific recording.

        Args:
            recording_id: The ID of the recording

        Returns:
            RecordingItem: Recording information
        """
        path = f"/v1/containers/{self._container_id}/recordings/{recording_id}/info"

        response = await self._http_client.get(path)
        return RecordingItem.model_validate(response)

    async def get_all(
        self, status: Optional[RecordingStatus] = None
    ) -> List[RecordingItem]:
        """Get all recordings for this container.

        Args:
            status: Optional status filter

        Returns:
            List[RecordingItem]: List of recordings
        """
        path = f"/v1/containers/{self._container_id}/recordings"

        params = {}
        if status:
            params["status"] = status

        response = await self._http_client.get(path, params=params)
        recordings = response.get("recordings", [])
        return [RecordingItem.model_validate(r) for r in recordings]
