"""
Daily.co transport adapter for screenshare bot.

Wraps Pipecat's DailyTransport to implement the BaseTransport interface.
"""

import asyncio
import logging
from typing import Optional, Any
from PIL import Image

from pipecat.transports.daily.transport import DailyTransport, DailyParams

from .base import BaseTransport

logger = logging.getLogger(__name__)


class DailyTransportAdapter(BaseTransport):
    """
    Adapter that wraps Pipecat's DailyTransport implementation.

    Provides the BaseTransport interface while delegating to the proven
    DailyTransport implementation used by the existing bot.
    """

    def __init__(
        self,
        room_url: str,
        meeting_token: Optional[str],
        bot_name: str,
        camera_out_width: int = 1280,
        camera_out_height: int = 720,
        **kwargs: Any  # Accept extra params for compatibility with factory
    ) -> None:
        """
        Initialize Daily.co transport adapter.

        Args:
            room_url: Daily.co room URL
            meeting_token: Optional meeting token for private rooms
            bot_name: Bot display name
            camera_out_width: Video width (default 1280)
            camera_out_height: Video height (default 720)
            **kwargs: Additional Daily-specific parameters (audio_out_enabled, etc.)
        """
        self.room_url = room_url
        self.meeting_token = meeting_token
        self.bot_name = bot_name

        # Extract Daily-specific params from kwargs with defaults
        audio_out_enabled = kwargs.get('audio_out_enabled', False)
        audio_in_enabled = kwargs.get('audio_in_enabled', False)
        camera_out_enabled = kwargs.get('camera_out_enabled', True)
        vad_enabled = kwargs.get('vad_enabled', False)
        transcription_enabled = kwargs.get('transcription_enabled', False)

        # Create DailyParams with configuration
        daily_params = DailyParams(
            audio_out_enabled=audio_out_enabled,
            audio_in_enabled=audio_in_enabled,
            camera_out_enabled=camera_out_enabled,
            camera_out_width=camera_out_width,
            camera_out_height=camera_out_height,
            vad_enabled=vad_enabled,
            transcription_enabled=transcription_enabled
        )

        # Initialize wrapped DailyTransport
        self._transport = DailyTransport(
            self.room_url,
            self.meeting_token,
            self.bot_name,
            daily_params
        )

        logger.info(f"DailyTransportAdapter initialized for room: {room_url}")

    async def join_room(self) -> None:
        """
        Connect to Daily.co room.

        The DailyTransport connects automatically during initialization,
        so we just wait for the connection to establish.
        """
        logger.info("Waiting for Daily.co room connection...")
        await asyncio.sleep(2)  # Match existing bot behavior
        logger.info("Daily.co room joined successfully")

    async def send_image(self, image: Image.Image) -> None:
        """
        Send video frame to Daily.co room.

        Args:
            image: PIL Image in RGB or RGBA format

        Raises:
            Exception: If frame send fails
        """
        await self._transport.send_image(image)  # type: ignore[arg-type]

    async def cleanup(self) -> None:
        """
        Disconnect from Daily.co room and release resources.

        Safe to call multiple times.
        """
        if self._transport:
            logger.info("Cleaning up Daily.co transport...")
            await self._transport.cleanup()
            logger.info("Daily.co transport cleaned up successfully")
