"""
LiveKit transport adapter for screenshare bot.

Implements screen share video streaming using the LiveKit Python SDK.
"""

import asyncio
import logging
import os
from typing import Optional, Any
from urllib.parse import urlparse
from PIL import Image

from livekit import rtc
from livekit.api import AccessToken, VideoGrants

from .base import BaseTransport

logger = logging.getLogger(__name__)


class LiveKitTransportAdapter(BaseTransport):
    """
    LiveKit transport implementation for screen sharing.

    Publishes video frames as a screen share track using the LiveKit Python SDK.
    Matches Daily.co behavior: 10 FPS, 1280x720 resolution.
    """

    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  # Ignore Daily-specific params
    ) -> None:
        """
        Initialize LiveKit transport adapter.

        Args:
            room_url: LiveKit WebSocket URL (wss://...) or room name
            meeting_token: Optional pre-generated access token
            bot_name: Bot participant name
            camera_out_width: Video width (default 1280)
            camera_out_height: Video height (default 720)
            **kwargs: Ignored (for compatibility with Daily params)
        """
        self.room_url = room_url
        self.meeting_token = meeting_token
        self.bot_name = bot_name
        self.width = camera_out_width
        self.height = camera_out_height

        # LiveKit components (initialized in join_room)
        self._room: Optional[rtc.Room] = None
        self._video_source: Optional[rtc.VideoSource] = None
        self._video_track: Optional[rtc.LocalVideoTrack] = None

        # Extract room name from URL or use as-is
        self.room_name = self._extract_room_name(room_url)

        logger.info(f"LiveKitTransportAdapter initialized for room: {self.room_name}")

    def _extract_room_name(self, url: str) -> str:
        """
        Extract room name from LiveKit URL.

        Args:
            url: WebSocket URL (wss://host/room) or simple room name

        Returns:
            Room name string
        """
        if url.startswith('wss://') or url.startswith('ws://'):
            # Extract from path: wss://host.livekit.cloud/room-name -> room-name
            parsed = urlparse(url)
            room = parsed.path.strip('/')
            return room if room else 'default-room'
        else:
            # Assume it's already a room name
            return url

    def _generate_token(self) -> str:
        """
        Generate LiveKit access token if not provided.

        Uses LIVEKIT_API_KEY and LIVEKIT_API_SECRET environment variables.

        Returns:
            JWT access token

        Raises:
            ValueError: If credentials not found
        """
        if self.meeting_token:
            return self.meeting_token

        api_key = os.getenv('LIVEKIT_API_KEY')
        api_secret = os.getenv('LIVEKIT_API_SECRET')

        if not api_key or not api_secret:
            raise ValueError(
                "Either provide meeting_token or set LIVEKIT_API_KEY "
                "and LIVEKIT_API_SECRET environment variables"
            )

        # Create access token with video publishing permissions
        token = AccessToken(api_key, api_secret)
        token.with_identity(self.bot_name)
        token.with_grants(VideoGrants(
            room_join=True,
            room=self.room_name,
            can_publish=True,
            can_subscribe=True
        ))

        return token.to_jwt()

    async def join_room(self) -> None:
        """
        Connect to LiveKit room and set up video track.

        Raises:
            Exception: If connection or track setup fails
        """
        try:
            logger.info(f"Connecting to LiveKit room: {self.room_name}")

            # Create room instance
            self._room = rtc.Room()

            # Generate or use provided token
            token = self._generate_token()

            # Get LiveKit URL from environment if not in room_url
            livekit_url = os.getenv('LIVEKIT_URL', self.room_url)
            if not livekit_url.startswith('ws'):
                raise ValueError(
                    f"Invalid LiveKit URL: {livekit_url}. "
                    "Must start with wss:// or ws://"
                )

            # Connect to room
            await self._room.connect(livekit_url, token)
            logger.info(f"Connected to LiveKit room: {self.room_name}")

            # Create video source for screen dimensions
            self._video_source = rtc.VideoSource(self.width, self.height)

            # Create video track from source
            self._video_track = rtc.LocalVideoTrack.create_video_track(
                "screenshare",
                self._video_source
            )

            # Publish track as screen share
            options = rtc.TrackPublishOptions(
                source=rtc.TrackSource.SOURCE_SCREENSHARE
            )
            await self._room.local_participant.publish_track(
                self._video_track,
                options
            )

            logger.info("Screen share track published successfully")

        except Exception as e:
            logger.error(f"Failed to join LiveKit room: {e}", exc_info=True)
            await self.cleanup()
            raise

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

        Args:
            image: PIL Image in RGB or RGBA format

        Raises:
            Exception: If frame send fails or transport not initialized
        """
        if not self._video_source:
            raise RuntimeError("Video source not initialized. Call join_room() first.")

        # Convert to RGB if needed
        if image.mode != 'RGB':
            image = image.convert('RGB')

        # Validate dimensions
        if image.size != (self.width, self.height):
            logger.warning(
                f"Image size mismatch: expected {self.width}x{self.height}, "
                f"got {image.size}. Resizing..."
            )
            image = image.resize((self.width, self.height), Image.Resampling.LANCZOS)

        # Convert PIL Image to bytes
        frame_data = image.tobytes()

        # Create VideoFrame
        frame = rtc.VideoFrame(
            width=self.width,
            height=self.height,
            type=rtc.VideoBufferType.RGB24,
            data=frame_data
        )

        # Send frame to video source
        self._video_source.capture_frame(frame)

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

        Safe to call multiple times.
        """
        logger.info("Cleaning up LiveKit transport...")

        try:
            # Unpublish track
            if self._room and self._video_track:
                try:
                    await self._room.local_participant.unpublish_track(
                        self._video_track.sid
                    )
                    logger.info("Video track unpublished")
                except Exception as e:
                    logger.warning(f"Error unpublishing track: {e}")

            # Disconnect from room
            if self._room:
                try:
                    await self._room.disconnect()
                    logger.info("Disconnected from LiveKit room")
                except Exception as e:
                    logger.warning(f"Error disconnecting from room: {e}")

        except Exception as e:
            logger.error(f"Error during LiveKit cleanup: {e}", exc_info=True)

        finally:
            # Clear references
            self._room = None
            self._video_source = None
            self._video_track = None
            logger.info("LiveKit transport cleaned up successfully")
