#!/usr/bin/env python3
"""
LiveKit Screenshare Bot

Joins a LiveKit room and streams a Slidev presentation deck using LiveKit Python SDK.
Integrates Stream A (screenshot capture) and Stream B (frame processing) modules.

Task #114 - Stream C: Integration
Task #115 - Slide Control Integration: Supabase Realtime listener for remote slide navigation
"""

print("=" * 70)
print("BOT.PY STARTING - Python process initiated")
print("=" * 70)
import sys
print(f"Python version: {sys.version}")
print(f"Python executable: {sys.executable}")
print("=" * 70)

# Import all synchronous stdlib modules first, then external libs, then asyncio LAST
# This minimizes Python 3.13 event loop initialization conflicts

print("Importing os...")
import os
print("✅ os imported")

print("Importing logging...")
import logging
print("✅ logging imported")

print("Importing time...")
import time
print("✅ time imported")

print("Importing BytesIO...")
from io import BytesIO
print("✅ BytesIO imported")

print("Importing typing...")
from typing import Optional, Dict, Any
print("✅ typing imported")

print("Importing pathlib...")
from pathlib import Path
print("✅ pathlib imported")

print("Importing PIL.Image...")
from PIL import Image
print("✅ PIL.Image imported")

print("Importing dotenv...")
from dotenv import load_dotenv
print("✅ dotenv imported")
sys.stdout.flush()  # Force flush before asyncio import

# Import asyncio LAST (Python 3.13+ best practice)
# Importing asyncio last minimizes event loop init conflicts with other modules
print("Importing asyncio...")
sys.stdout.flush()  # CRITICAL: Flush before potentially blocking import

import asyncio
sys.stdout.flush()  # Flush immediately after import
print("✅ asyncio imported successfully")
sys.stdout.flush()  # Final flush to ensure output is captured

print("=" * 70)
print("✅ ALL STANDARD LIBRARY IMPORTS SUCCESSFUL")
print("=" * 70)

# Import shared types from local copy
print("DEBUG: About to import shared_types...")
try:
    from shared_types import ConversationSession, SlidevDeck, SlideControlCommand, ActiveBotRow
    print("✅ shared_types imported")
except Exception as e:
    print(f"❌ Failed to import shared_types: {e}")
    raise

# LiveKit transport imports
print("DEBUG: About to import LiveKit SDK...")
try:
    from livekit import rtc
    from livekit.api import AccessToken, VideoGrants
    print("✅ LiveKit SDK imported")
except Exception as e:
    print(f"❌ Failed to import LiveKit SDK: {e}")
    raise

# Import Stream A & B modules
print("DEBUG: About to import screenshot_capture...")
try:
    from screenshot_capture import ScreenshotCapture
    print("✅ screenshot_capture imported")
except Exception as e:
    print(f"❌ Failed to import screenshot_capture: {e}")
    raise

print("DEBUG: About to import frame_processor...")
try:
    from frame_processor import FrameProcessor
    print("✅ frame_processor imported")
except Exception as e:
    print(f"❌ Failed to import frame_processor: {e}")
    raise

# Import slide control modules (Task #115)
print("DEBUG: About to import slide_control_listener...")
try:
    from slide_control_listener import SlideControlListener
    print("✅ slide_control_listener imported")
except Exception as e:
    print(f"❌ Failed to import slide_control_listener: {e}")
    raise

print("DEBUG: About to import slide_navigator...")
try:
    from slide_navigator import SlideNavigator
    print("✅ slide_navigator imported")
except Exception as e:
    print(f"❌ Failed to import slide_navigator: {e}")
    raise

# Import lifecycle manager (Task #116)
print("DEBUG: About to import lifecycle_manager...")
try:
    from lifecycle_manager import BotLifecycleManager, retry_with_backoff
    print("✅ lifecycle_manager imported")
except Exception as e:
    print(f"❌ Failed to import lifecycle_manager: {e}")
    raise

print("=" * 70)
print("ALL IMPORTS SUCCESSFUL - Initializing logging")
print("=" * 70)

logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

load_dotenv()
logger.info("Bot initialization complete")


class ScreenshareBot:
    """
    LiveKit screenshare bot that streams a Slidev deck.

    Architecture:
    - LiveKit Python SDK: Direct room connection and video streaming
    - ScreenshotCapture (Stream A): Browser automation and PNG capture
    - FrameProcessor (Stream B): PNG to RGBA conversion
    - SlideNavigator: Keyboard navigation for Slidev deck
    - SlideControlListener: Supabase Realtime listener for remote commands
    - 10 FPS streaming loop with jitter control

    Args:
        room_url: LiveKit room URL (wss://...)
        deck_url: Slidev deck URL (http:// or file://)
        session_id: Session UUID for filtering Supabase commands (required for slide control)
        bot_id: Bot UUID for Supabase status reporting
        meeting_token: LiveKit access token for authentication
    """

    def __init__(self, room_url: str, deck_url: str, session_id: str, bot_id: str, meeting_token: Optional[str] = None) -> None:
        self.room_url: str = room_url
        self.deck_url: str = deck_url
        self.session_id: str = session_id
        self.bot_id: str = bot_id
        self.meeting_token: Optional[str] = meeting_token

        # LiveKit components
        self._room: Optional[rtc.Room] = None
        self._video_source: Optional[rtc.VideoSource] = None
        self._video_track: Optional[rtc.LocalVideoTrack] = None
        self.width: int = 1280
        self.height: int = 720

        # Stream A & B components
        self.screenshot_capture: ScreenshotCapture = ScreenshotCapture(deck_url)
        self.frame_processor: FrameProcessor = FrameProcessor(validate_dimensions=True, profile=True)

        # Slide control modules (Task #115) - initialized after screenshot capture starts
        self.slide_navigator: Optional[SlideNavigator] = None
        self.slide_listener: Optional[SlideControlListener] = None

        # Control flags
        self.is_running: bool = False
        self.frame_rate: int = 10  # FPS
        self.frame_interval: float = 1.0 / self.frame_rate

        # Performance tracking
        self.frame_count: int = 0
        self.start_time: Optional[float] = None
        self.last_frame: Optional[Image.Image] = None  # Fallback frame on capture error

    async def start_screenshot_capture(self) -> None:
        """Initialize browser and load deck (Stream A)"""
        try:
            logger.info("🌐 Starting screenshot capture module...")
            await self.screenshot_capture.start()
            logger.info("✅ Screenshot capture ready")

            # Log initial metrics
            metrics = self.screenshot_capture.metrics
            logger.info(f"📊 Capture module initialized: {metrics}")

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

    async def start_slide_control(self) -> None:
        """
        Initialize slide navigation and Supabase listener (Task #115).

        This must be called AFTER screenshot capture is started since SlideNavigator
        needs the Playwright page object.
        """
        try:
            # Check if Supabase credentials are available
            supabase_url = os.getenv("SUPABASE_URL")
            supabase_key = os.getenv("SUPABASE_SERVICE_KEY")

            if not supabase_url or not supabase_key:
                logger.warning(
                    "⚠️  SUPABASE_URL or SUPABASE_SERVICE_KEY not set. "
                    "Slide control will be disabled. "
                    "Set these environment variables to enable remote slide navigation."
                )
                return

            logger.info("🎮 Starting slide control modules...")

            # Initialize SlideNavigator with Playwright page
            page = self.screenshot_capture._page
            if page is None:
                raise RuntimeError("Screenshot capture page is not initialized")
            self.slide_navigator = SlideNavigator(page)
            await self.slide_navigator.start()
            logger.info("✅ Slide navigator ready")

            # Extract deck_id from deck_url (format: https://example.com/path/to/deck_id/)
            # For URLs like https://buzztrail.github.io/buzztrail-presentations/abc123/ => deck_id = abc123
            deck_id = self.deck_url.rstrip('/').split('/')[-1]

            # Initialize SlideControlListener with callback to navigator
            self.slide_listener = SlideControlListener(
                supabase_url=supabase_url,
                supabase_key=supabase_key,
                deck_id=deck_id,
                session_id=self.session_id,
                on_command=self.slide_navigator.execute_command
            )
            await self.slide_listener.start()
            logger.info(f"✅ Supabase listener ready (session: {self.session_id})")

        except Exception as e:
            logger.warning(
                f"Failed to start slide control: {e}. "
                "Bot will continue without remote slide navigation.",
                exc_info=True
            )
            # Don't raise - bot can still work without slide control

    async def join_livekit_room(self) -> None:
        """
        Connect to LiveKit room and start streaming.

        Enhanced with retry logic.
        """
        async def _join_impl() -> None:
            logger.info(f"🚀 Joining LiveKit room: {self.room_url}")

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

            # Get LiveKit URL from environment
            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://"
                )

            # Extract room name from URL path
            from urllib.parse import urlparse
            parsed = urlparse(livekit_url)
            room_name = parsed.path.strip('/')

            # Connect to room using provided token
            if not self.meeting_token:
                raise ValueError("LiveKit access token (meeting_token) is required")
            await self._room.connect(livekit_url, self.meeting_token)
            logger.info(f"✅ Connected to LiveKit room: {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")

        # Use retry logic for room join
        await retry_with_backoff(
            _join_impl,
            max_attempts=3,
            operation_name="LiveKit room join"
        )

    async def capture_and_process_frame(self) -> Image.Image:
        """
        Capture screenshot and process to PIL Image.

        Uses Stream A (screenshot capture) and Stream B (frame processing).

        Returns:
            PIL Image in RGB format (ready for transport.send_image())
        """
        try:
            # Stream A: Capture PNG screenshot
            png_bytes = await self.screenshot_capture.capture_frame()

            # Stream B: Convert PNG to RGBA bytes
            rgba_bytes = self.frame_processor.process(png_bytes)

            # Convert RGBA bytes back to PIL Image for transport.send_image()
            # (Task #113 proved send_image() works with PIL Images directly)
            image = Image.frombytes('RGBA', (1280, 720), rgba_bytes)

            # Convert to RGB (transport prefers RGB based on Task #113)
            image = image.convert('RGB')

            # Cache as fallback
            self.last_frame = image

            return image

        except Exception as e:
            logger.warning(f"Frame capture/processing failed: {e}")

            # Fallback to last successful frame
            if self.last_frame:
                logger.info("Using last successful frame as fallback")
                return self.last_frame
            else:
                logger.error("No fallback frame available, re-raising error")
                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
        """
        if not self._video_source:
            raise RuntimeError("Video source not initialized. Call join_livekit_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 start_frame_streaming(self) -> None:
        """
        Continuously capture and stream frames at 10 FPS.

        Integrates Stream A (capture) + Stream B (processing) + LiveKit SDK.
        """
        try:
            logger.info(f"🎬 Starting frame streaming at {self.frame_rate} FPS")
            self.is_running = True
            self.start_time = time.time()

            while self.is_running:
                loop_start = time.time()

                # Capture and process frame (Streams A & B)
                frame_image = await self.capture_and_process_frame()

                # Send to LiveKit
                await self.send_image(frame_image)

                self.frame_count += 1

                # Log progress every 10 frames (1 second at 10 FPS)
                if self.frame_count % 10 == 0:
                    elapsed = time.time() - self.start_time
                    actual_fps = self.frame_count / elapsed if elapsed > 0 else 0

                    # Get module metrics
                    capture_metrics = self.screenshot_capture.metrics
                    processor_stats = self.frame_processor.get_performance_stats()

                    # Build log message
                    log_parts = [
                        f"📊 Frames: {self.frame_count}",
                        f"Elapsed: {elapsed:.1f}s",
                        f"FPS: {actual_fps:.2f}",
                        f"Capture avg: {capture_metrics['avg_capture_time_ms']:.1f}ms",
                        f"Process avg: {processor_stats['avg_time_ms']:.1f}ms"
                    ]

                    # Add slide control metrics if enabled (Task #115)
                    if self.slide_listener and self.slide_listener.is_running:
                        listener_metrics = self.slide_listener.metrics
                        nav_metrics = self.slide_navigator.metrics if self.slide_navigator else {}

                        log_parts.append(
                            f"Slide cmds: {listener_metrics['command_count']} "
                            f"(latency: {listener_metrics['avg_latency_ms']:.1f}ms)"
                        )

                        # Alert if slide control latency exceeds 500ms target
                        if listener_metrics['avg_latency_ms'] > 500:
                            logger.warning(
                                f"⚠️  Slide control latency high: {listener_metrics['avg_latency_ms']:.1f}ms "
                                f"(target: <500ms)"
                            )

                    logger.info(" | ".join(log_parts))

                # Calculate time to sleep for 10 FPS target
                loop_duration = time.time() - loop_start
                sleep_time = max(0, self.frame_interval - loop_duration)

                # Warn if we're missing target (jitter > 50ms)
                if sleep_time == 0:
                    jitter = loop_duration - self.frame_interval
                    if jitter > 0.05:  # 50ms
                        logger.warning(
                            f"⚠️  Frame processing took too long: {loop_duration*1000:.1f}ms "
                            f"(target: {self.frame_interval*1000:.0f}ms, jitter: {jitter*1000:.1f}ms)"
                        )

                await asyncio.sleep(sleep_time)

        except Exception as e:
            logger.error(f"Frame streaming error: {e}", exc_info=True)
            raise
        finally:
            # Final stats
            if self.start_time:
                final_elapsed = time.time() - self.start_time
                final_fps = self.frame_count / final_elapsed if final_elapsed > 0 else 0

                logger.info("=" * 70)
                logger.info("STREAMING SESSION SUMMARY")
                logger.info("=" * 70)
                logger.info(f"✅ Total frames streamed: {self.frame_count}")
                logger.info(f"✅ Session duration: {final_elapsed:.2f}s")
                logger.info(f"✅ Average FPS: {final_fps:.2f}")
                logger.info(f"✅ Target FPS: {self.frame_rate}")
                logger.info(f"✅ FPS Accuracy: {(final_fps/self.frame_rate)*100:.1f}%")

                # Module metrics
                capture_metrics = self.screenshot_capture.metrics
                logger.info(f"📊 Screenshot capture: {capture_metrics}")

                processor_stats = self.frame_processor.get_performance_stats()
                logger.info(f"📊 Frame processing: {processor_stats}")

                logger.info("=" * 70)

    async def start(self) -> None:
        """Start the bot (main entry point)"""
        try:
            logger.info("=" * 70)
            logger.info("LIVEKIT SCREENSHARE BOT - Tasks #114 & #115")
            logger.info("=" * 70)
            logger.info(f"Bot ID: {self.bot_id}")
            logger.info(f"Session ID: {self.session_id}")
            logger.info(f"Room: {self.room_url}")
            logger.info(f"Deck: {self.deck_url}")
            logger.info(f"Target FPS: {self.frame_rate}")
            logger.info("=" * 70)

            # Step 1: Start screenshot capture (Stream A)
            await self.start_screenshot_capture()

            # Step 2: Initialize slide control (Task #115)
            # Must be after screenshot capture since navigator needs Playwright page
            await self.start_slide_control()

            # Step 3: Join LiveKit room
            await self.join_livekit_room()

            # Step 4: Start frame streaming loop (Stream C integration)
            await self.start_frame_streaming()

        except Exception as e:
            logger.error(f"Bot error: {e}", exc_info=True)
            raise

    async def stop(self) -> None:
        """Clean up resources"""
        logger.info("🛑 Stopping bot...")
        self.is_running = False

        # Stop slide control modules (Task #115)
        if self.slide_listener:
            try:
                logger.info("Stopping slide control listener...")
                await self.slide_listener.stop()
                logger.info("✅ Slide listener stopped")
            except Exception as e:
                logger.warning(f"Slide listener cleanup error: {e}")

        if self.slide_navigator:
            try:
                logger.info("Stopping slide navigator...")
                await self.slide_navigator.stop()
                logger.info("✅ Slide navigator stopped")
            except Exception as e:
                logger.warning(f"Slide navigator cleanup error: {e}")

        # Cleanup LiveKit resources
        if self._room:
            try:
                logger.info("Cleaning up LiveKit connection...")
                # Unpublish track
                if 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
                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.warning(f"LiveKit cleanup error: {e}")

        # Stop screenshot capture (Stream A cleanup)
        if self.screenshot_capture:
            try:
                logger.info("Stopping screenshot capture...")
                await self.screenshot_capture.stop()
                logger.info("✅ Screenshot capture stopped")
            except Exception as e:
                logger.warning(f"Screenshot capture cleanup error: {e}")

        logger.info("✅ Bot stopped successfully")


async def main() -> None:
    """Main entry point with lifecycle management (Task #116)"""
    if len(sys.argv) < 5:
        print("Usage: python bot.py <room_url> <deck_url> <session_id> <bot_id> [meeting_token] [timeout_minutes]")
        print()
        print("Arguments:")
        print("  room_url:        LiveKit room URL (wss://...)")
        print("  deck_url:        Slidev deck URL (http:// or file://)")
        print("  session_id:      Session UUID for Supabase slide control filtering")
        print("  bot_id:          Bot UUID for Supabase status reporting (required)")
        print("  meeting_token:   Optional LiveKit access token (for authentication)")
        print("  timeout_minutes: Optional inactivity timeout in minutes (default: 30)")
        print()
        print("Example:")
        print("  python bot.py \\")
        print("    wss://buzztrail-xxx.livekit.cloud/test-room \\")
        print("    https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/ \\")
        print("    550e8400-e29b-41d4-a716-446655440000 \\")
        print("    660e8400-e29b-41d4-a716-446655440000 \\")
        print("    optional-livekit-token \\")
        print("    30")
        print()
        print("For testing with local deck:")
        print("  python bot.py \\")
        print("    wss://buzztrail-xxx.livekit.cloud/test-room \\")
        print("    file:///path/to/tests/fixtures/test_deck.html \\")
        print("    550e8400-e29b-41d4-a716-446655440000 \\")
        print("    660e8400-e29b-41d4-a716-446655440000")
        print()
        print("Environment Variables:")
        print("  SUPABASE_URL:         Supabase project URL (for slide control)")
        print("  SUPABASE_SERVICE_KEY: Supabase service role key (for slide control)")
        print("  TRANSPORT_TYPE:       Transport type (default: livekit)")
        sys.exit(1)

    room_url = sys.argv[1]
    deck_url = sys.argv[2]
    session_id = sys.argv[3]
    bot_id = sys.argv[4]
    meeting_token = sys.argv[5] if len(sys.argv) > 5 else None
    timeout_minutes = int(sys.argv[6]) if len(sys.argv) > 6 else 30

    bot = ScreenshareBot(room_url, deck_url, session_id, bot_id, meeting_token)
    lifecycle_manager = BotLifecycleManager(bot, timeout_minutes=timeout_minutes)

    try:
        await lifecycle_manager.start()
    except KeyboardInterrupt:
        logger.info("⚠️  Received interrupt signal")
        await lifecycle_manager.terminate("keyboard_interrupt")
    except Exception as e:
        logger.error(f"Bot error: {e}", exc_info=True)
        await lifecycle_manager.terminate("unexpected_error")
        raise


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass  # Handled in main()
    except Exception as e:
        logger.error(f"❌ Fatal error: {e}", exc_info=True)
        sys.exit(1)
