"""
Supabase Client for Voice Agent

Provides Supabase client initialization and realtime channel management
for slide control commands.

Part of Issue #144 - Stream B: Tool Functions & Slide Control
Enhanced for Issue #148 - Stream A: 3-Participant Coordination with Realtime
"""

import asyncio
import logging
import os
from collections.abc import Callable
from datetime import UTC, datetime
from typing import Any

from supabase import Client, create_client

logger = logging.getLogger(__name__)


class SupabaseClient:
    """
    Supabase client wrapper for voice agent slide control.

    Manages connection to Supabase and provides methods for:
    - Publishing slide control commands to realtime channels
    - Querying slide deck information
    - Managing session state

    Example:
        >>> client = SupabaseClient(
        ...     url="https://project.supabase.co",
        ...     key="service-key"
        ... )
        >>> await client.publish_slide_command(
        ...     deck_id="deck-123",
        ...     command="next"
        ... )
    """

    def __init__(
        self,
        url: str | None = None,
        service_key: str | None = None,
        session_id: str | None = None
    ) -> None:
        """
        Initialize Supabase client.

        Args:
            url: Supabase project URL. Defaults to SUPABASE_URL env var.
            service_key: Supabase service role key. Defaults to SUPABASE_SERVICE_KEY env var.
            session_id: Optional session ID for tracking commands (defaults to timestamp-based ID)

        Raises:
            ValueError: If URL or service key is not provided
        """
        self.url = url or os.environ.get("SUPABASE_URL")
        self.service_key = service_key or os.environ.get("SUPABASE_SERVICE_KEY")
        self.session_id = session_id or f"sess_{int(datetime.now().timestamp())}"

        if not self.url or not self.service_key:
            raise ValueError(
                "Supabase URL and service key are required. "
                "Set SUPABASE_URL and SUPABASE_SERVICE_KEY environment variables."
            )

        # Initialize Supabase client
        self._client: Client = create_client(self.url, self.service_key)

        # Realtime channel subscriptions (Issue #148)
        self._channels: dict[str, Any] = {}
        self._confirmation_callbacks: dict[str, Callable[[dict[str, Any]], None]] = {}

        logger.info(f"Supabase client initialized (session_id={self.session_id})")

    @property
    def client(self) -> Client:
        """Get the underlying Supabase client instance."""
        return self._client

    async def publish_slide_command(
        self,
        deck_id: str,
        command: str,
        slide_number: int | None = None
    ) -> dict[str, Any]:
        """
        Publish a slide control command to Supabase realtime channel.

        Commands are published to the `slide_control:{deck_id}` channel
        and inserted into the `slide_control_commands` table.

        Args:
            deck_id: Unique identifier for the slide deck
            command: Command type ('next', 'prev', 'goto', 'reload')
            slide_number: Target slide number (required for 'goto' command)

        Returns:
            Dictionary containing the inserted command record

        Raises:
            ValueError: If command is invalid or slide_number missing for 'goto'
            Exception: If database insert fails
        """
        # Validate command
        valid_commands = {"next", "prev", "goto", "reload"}
        if command not in valid_commands:
            raise ValueError(
                f"Invalid command: {command}. "
                f"Valid commands: {valid_commands}"
            )

        # Validate slide_number for goto command
        if command == "goto":
            if slide_number is None:
                raise ValueError("slide_number is required for 'goto' command")
            if not isinstance(slide_number, int) or slide_number < 1:
                raise ValueError("slide_number must be a positive integer")

        # Insert command into database
        # The database trigger will broadcast to realtime channel
        command_data = {
            "deck_id": deck_id,
            "command": command,
            "slide_number": slide_number,
        }

        logger.info(
            f"Publishing slide command: {command} "
            f"(deck_id={deck_id}, slide_number={slide_number})"
        )

        try:
            result = self._client.table("slide_control_commands").insert(
                command_data
            ).execute()

            if not result.data:
                raise Exception("Failed to insert command: no data returned")

            logger.info(f"Command published successfully: {result.data[0]}")
            return result.data[0]

        except Exception as e:
            logger.error(f"Failed to publish command: {e}", exc_info=True)
            raise

    async def get_slide_deck(self, deck_id: str) -> dict[str, Any] | None:
        """
        Get slide deck information from Supabase.

        Args:
            deck_id: Unique identifier for the slide deck

        Returns:
            Dictionary containing deck information, or None if not found
        """
        try:
            result = self._client.table("slide_decks").select("*").eq(
                "id", deck_id
            ).execute()

            if not result.data:
                logger.warning(f"Slide deck not found: {deck_id}")
                return None

            return result.data[0]

        except Exception as e:
            logger.error(
                f"Failed to get slide deck {deck_id}: {e}",
                exc_info=True
            )
            return None

    async def get_current_slide_number(
        self,
        deck_id: str
    ) -> int | None:
        """
        Get the current slide number for a deck.

        Args:
            deck_id: Unique identifier for the slide deck

        Returns:
            Current slide number, or None if not found
        """
        deck = await self.get_slide_deck(deck_id)
        if not deck:
            return None

        return deck.get("current_slide", 1)

    async def update_current_slide(
        self,
        deck_id: str,
        slide_number: int
    ) -> bool:
        """
        Update the current slide number in the database.

        Args:
            deck_id: Unique identifier for the slide deck
            slide_number: New slide number

        Returns:
            True if update succeeded, False otherwise
        """
        try:
            result = self._client.table("slide_decks").update(
                {"current_slide": slide_number}
            ).eq("id", deck_id).execute()

            if not result.data:
                logger.error(f"Failed to update current slide for deck {deck_id}")
                return False

            logger.info(
                f"Updated current slide for deck {deck_id} to {slide_number}"
            )
            return True

        except Exception as e:
            logger.error(
                f"Failed to update current slide: {e}",
                exc_info=True
            )
            return False

    # Issue #148: Realtime channel methods for 3-participant coordination

    async def publish_slide_navigation(
        self,
        deck_id: str,
        direction: str,
        slide_number: int | None = None,
        timeout: float = 5.0
    ) -> dict[str, Any]:
        """
        Publish a slide navigation command to realtime channel and wait for confirmation.

        This method implements the Issue #148 communication protocol for voice agent
        to screenshare bot coordination.

        Args:
            deck_id: Unique identifier for the slide deck
            direction: Navigation direction ('next', 'previous', or 'goto')
            slide_number: Target slide number (required for 'goto' direction)
            timeout: Maximum seconds to wait for confirmation (default 5.0)

        Returns:
            Dictionary containing confirmation response with keys:
            - success: bool
            - current_slide: int
            - total_slides: int
            - error: str (if success=False)

        Raises:
            ValueError: If parameters are invalid
            TimeoutError: If confirmation not received within timeout
            Exception: If publishing fails
        """
        # Validate direction
        valid_directions = {"next", "previous", "goto"}
        if direction not in valid_directions:
            raise ValueError(
                f"Invalid direction: {direction}. "
                f"Valid directions: {valid_directions}"
            )

        # Validate slide_number for goto
        if direction == "goto":
            if slide_number is None:
                raise ValueError("slide_number is required for 'goto' direction")
            if not isinstance(slide_number, int) or slide_number < 1:
                raise ValueError("slide_number must be a positive integer")

        # Build message according to Issue #148 protocol
        message = {
            "type": "navigate",
            "direction": direction,
            "timestamp": datetime.now(UTC).isoformat().replace("+00:00", "Z"),
            "session_id": self.session_id
        }

        if slide_number is not None:
            message["slide_number"] = slide_number

        channel_name = f"slide_control:{deck_id}"

        logger.info(
            f"Publishing navigation command: {direction} "
            f"(deck_id={deck_id}, slide_number={slide_number})"
        )

        try:
            # Create future to wait for confirmation
            confirmation_future = asyncio.Future()

            # Store callback for this request
            request_id = f"{self.session_id}_{int(datetime.now().timestamp() * 1000)}"

            def on_confirmation(payload: dict[str, Any]) -> None:
                """Handle confirmation message from screenshare bot"""
                try:
                    if payload.get("session_id") == self.session_id and not confirmation_future.done():
                        confirmation_future.set_result(payload)
                        logger.info(f"Received confirmation: {payload}")
                except Exception as e:
                    logger.error(f"Error in confirmation callback: {e}", exc_info=True)
                    if not confirmation_future.done():
                        confirmation_future.set_exception(e)

            # Subscribe to channel if not already subscribed
            if channel_name not in self._channels:
                await self._subscribe_to_channel(channel_name, on_confirmation)

            # Store callback for this specific request
            self._confirmation_callbacks[request_id] = on_confirmation

            # Publish message to channel
            channel = self._channels.get(channel_name)
            if channel:
                channel.send({
                    "type": "broadcast",
                    "event": "navigate",
                    "payload": message
                })
            else:
                raise Exception(f"Channel {channel_name} not available")

            # Wait for confirmation with timeout
            try:
                confirmation = await asyncio.wait_for(
                    confirmation_future,
                    timeout=timeout
                )

                logger.info(
                    f"Navigation confirmed: slide {confirmation.get('current_slide')} "
                    f"of {confirmation.get('total_slides')}"
                )

                return confirmation

            except TimeoutError:
                logger.warning(
                    f"Timeout waiting for navigation confirmation "
                    f"(deck_id={deck_id}, timeout={timeout}s)"
                )
                raise TimeoutError(
                    f"No confirmation received within {timeout}s. "
                    "Screenshare bot may not be responding."
                ) from None

            finally:
                # Cleanup callback
                self._confirmation_callbacks.pop(request_id, None)

        except Exception as e:
            logger.error(f"Failed to publish navigation command: {e}", exc_info=True)
            raise

    async def _subscribe_to_channel(
        self,
        channel_name: str,
        callback: Callable[[dict[str, Any]], None]
    ) -> None:
        """
        Subscribe to a Supabase realtime channel.

        Args:
            channel_name: Name of the channel to subscribe to
            callback: Callback function to handle incoming messages
        """
        try:
            logger.info(f"Subscribing to channel: {channel_name}")

            # Create channel
            channel = self._client.channel(channel_name)

            # Subscribe to broadcast messages
            channel.on_broadcast(event="confirmation", callback=callback)

            # Subscribe to the channel
            channel.subscribe()

            # Store channel reference
            self._channels[channel_name] = channel

            logger.info(f"Successfully subscribed to channel: {channel_name}")

        except Exception as e:
            logger.error(
                f"Failed to subscribe to channel {channel_name}: {e}",
                exc_info=True
            )
            raise

    async def unsubscribe_from_channel(self, channel_name: str) -> None:
        """
        Unsubscribe from a Supabase realtime channel.

        Args:
            channel_name: Name of the channel to unsubscribe from
        """
        if channel_name in self._channels:
            try:
                channel = self._channels[channel_name]
                channel.unsubscribe()
                del self._channels[channel_name]
                logger.info(f"Unsubscribed from channel: {channel_name}")
            except Exception as e:
                logger.error(
                    f"Failed to unsubscribe from channel {channel_name}: {e}",
                    exc_info=True
                )

    async def cleanup(self) -> None:
        """
        Cleanup all realtime channel subscriptions.
        Call this when shutting down the client.
        """
        logger.info("Cleaning up Supabase client subscriptions")
        for channel_name in list(self._channels.keys()):
            await self.unsubscribe_from_channel(channel_name)
        self._confirmation_callbacks.clear()
        logger.info("Supabase client cleanup complete")


def create_supabase_client(
    url: str | None = None,
    service_key: str | None = None
) -> SupabaseClient:
    """
    Factory function to create a Supabase client instance.

    Args:
        url: Supabase project URL. Defaults to SUPABASE_URL env var.
        service_key: Supabase service role key. Defaults to SUPABASE_SERVICE_KEY env var.

    Returns:
        Initialized SupabaseClient instance

    Raises:
        ValueError: If URL or service key is not provided
    """
    return SupabaseClient(url=url, service_key=service_key)
