"""
Custom URL scheme handler for serving overlay JavaScript files
"""

import logging
import os
from pathlib import Path

# Suppress Chromium sandbox warnings when running as root - MUST be set before Qt imports
if os.geteuid() == 0:  # Running as root
    os.environ['QTWEBENGINE_DISABLE_SANDBOX'] = '1'
    print("Qt WebEngine sandbox disabled for root user")

from PyQt6.QtCore import QBuffer, QIODevice, QByteArray
from PyQt6.QtWebEngineCore import QWebEngineUrlRequestJob, QWebEngineUrlSchemeHandler

logger = logging.getLogger(__name__)


class OverlayUrlSchemeHandler(QWebEngineUrlSchemeHandler):
    """Custom URL scheme handler for overlay:// URLs"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        logger.info("OverlayUrlSchemeHandler initialized")
    
    def requestStarted(self, job: QWebEngineUrlRequestJob):
        """Handle URL requests for overlay:// scheme"""
        try:
            url = job.requestUrl()
            path = url.path()
            
            logger.debug(f"Overlay URL requested: {url.toString()}")
            
            if path == "/overlay.js":
                # Serve the overlay.js file
                self._serve_overlay_js(job)
            else:
                # Unknown resource
                logger.warning(f"Unknown overlay resource requested: {path}")
                job.fail(QWebEngineUrlRequestJob.Error.UrlNotFound)
                
        except Exception as e:
            logger.error(f"Error handling overlay URL request: {e}")
            job.fail(QWebEngineUrlRequestJob.Error.RequestFailed)
    
    def _serve_overlay_js(self, job: QWebEngineUrlRequestJob):
        """Serve the overlay.js file content"""
        try:
            # Get overlay.js file from web dashboard static directory
            overlay_js_path = Path(__file__).parent.parent / "web_dashboard" / "static" / "overlay.js"
            
            if overlay_js_path.exists():
                # Read the file content
                with open(overlay_js_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                # Create QByteArray with content
                data = QByteArray(content.encode('utf-8'))
                
                # Create QBuffer for the data
                buffer = QBuffer()
                buffer.setData(data)
                buffer.open(QIODevice.OpenModeFlag.ReadOnly)
                
                # Reply with JavaScript content type
                job.reply(b"application/javascript", buffer)
                logger.debug("Served overlay.js successfully")
                
            else:
                logger.error(f"overlay.js file not found: {overlay_js_path}")
                job.fail(QWebEngineUrlRequestJob.Error.UrlNotFound)
                
        except Exception as e:
            logger.error(f"Failed to serve overlay.js: {e}")
            job.fail(QWebEngineUrlRequestJob.Error.RequestFailed)