"""
LiveKit screen share — publishes the desktop screen as a video track
to a LiveKit room so mobile/web viewers can watch in real-time.

Requires: pip install livekit
"""
import asyncio
import logging
import time
from typing import Optional

logger = logging.getLogger(__name__)

_room = None
_sharing = False


async def start_screen_share(livekit_url: str, token: str) -> bool:
    """Connect to LiveKit room and publish screen as video track."""
    global _room, _sharing
    try:
        from livekit import rtc
    except ImportError:
        logger.error("livekit SDK not installed. Run: pip install livekit")
        return False

    if _room and _sharing:
        logger.info("Screen share already active")
        return True

    try:
        room = rtc.Room()

        await room.connect(livekit_url, token)
        logger.info(f"Connected to LiveKit room: {room.name}")

        # Create screen capture source
        source = rtc.VideoSource(1920, 1080)
        track = rtc.LocalVideoTrack.create_video_track("screen", source)

        # Publish the track
        options = rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_SCREENSHARE)
        await room.local_participant.publish_track(track, options)

        _room = room
        _sharing = True

        # Start capture loop in background
        asyncio.create_task(_capture_loop(source))

        logger.info("Screen share started")
        return True
    except Exception as e:
        logger.error(f"Failed to start screen share: {e}")
        return False


async def _capture_loop(source):
    """Continuously capture screen and feed frames to the LiveKit source."""
    global _sharing
    try:
        import mss
        from livekit import rtc
        import numpy as np
    except ImportError:
        logger.error("Missing dependencies for screen capture")
        _sharing = False
        return

    sct = mss.mss()
    monitor = sct.monitors[0]  # Primary monitor

    while _sharing:
        try:
            # Capture screen
            img = sct.grab(monitor)
            # Convert BGRA to RGBA
            frame_data = bytearray(img.raw)
            for i in range(0, len(frame_data), 4):
                frame_data[i], frame_data[i + 2] = frame_data[i + 2], frame_data[i]

            frame = rtc.VideoFrame(
                width=img.width,
                height=img.height,
                type=rtc.VideoBufferType.RGBA,
                data=bytes(frame_data),
            )
            source.capture_frame(frame)

            # ~15 FPS
            await asyncio.sleep(1 / 15)
        except Exception as e:
            logger.error(f"Screen capture error: {e}")
            await asyncio.sleep(1)

    sct.close()


async def stop_screen_share():
    """Disconnect from LiveKit room and stop screen share."""
    global _room, _sharing
    _sharing = False
    if _room:
        await _room.disconnect()
        _room = None
        logger.info("Screen share stopped")


def is_sharing() -> bool:
    return _sharing
