#!/usr/bin/env python3
"""
GPU Acceleration Diagnostic Script for Qt WebEngine
Tests GPU functionality and Qt WebEngine GPU acceleration status
"""

import os
import sys
import subprocess
import logging
from pathlib import Path

# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def run_command(cmd, shell=False):
    """Run a command and return output"""
    try:
        result = subprocess.run(cmd, shell=shell, capture_output=True, text=True, timeout=30)
        return result.returncode, result.stdout, result.stderr
    except subprocess.TimeoutExpired:
        return -1, "", "Command timed out"
    except Exception as e:
        return -1, "", str(e)

def check_nvidia_gpu():
    """Check NVIDIA GPU status"""
    logger.info("=== NVIDIA GPU Status ===")

    # Check nvidia-smi
    code, stdout, stderr = run_command(["nvidia-smi"])
    if code == 0:
        logger.info("nvidia-smi output:")
        logger.info(stdout)
    else:
        logger.error(f"nvidia-smi failed: {stderr}")

    # Check GPU processes
    code, stdout, stderr = run_command(["nvidia-smi", "pmon"])
    if code == 0:
        logger.info("GPU processes:")
        logger.info(stdout)
    else:
        logger.warning(f"Could not check GPU processes: {stderr}")

def check_opengl():
    """Check OpenGL functionality"""
    logger.info("=== OpenGL Status ===")

    # Check glxinfo
    code, stdout, stderr = run_command(["glxinfo", "|", "head", "-20"], shell=True)
    if code == 0:
        logger.info("OpenGL info:")
        logger.info(stdout)
    else:
        logger.warning(f"glxinfo failed: {stderr}")

    # Check if direct rendering is enabled
    code, stdout, stderr = run_command(["glxinfo", "|", "grep", "direct"], shell=True)
    if code == 0:
        logger.info("Direct rendering status:")
        logger.info(stdout)
    else:
        logger.warning("Could not check direct rendering")

def check_qt_environment():
    """Check Qt environment variables"""
    logger.info("=== Qt Environment Variables ===")

    qt_vars = [
        'QT_QPA_PLATFORM',
        'QT_DEBUG_PLUGINS',
        'QTWEBENGINE_DISABLE_SANDBOX',
        'QTWEBENGINE_CHROMIUM_FLAGS',
        'QTWEBENGINE_REMOTE_DEBUGGING',
        'LIBGL_ALWAYS_SOFTWARE',
        'MESA_GL_VERSION_OVERRIDE',
        'DISPLAY',
        'XDG_SESSION_TYPE'
    ]

    for var in qt_vars:
        value = os.environ.get(var)
        if value:
            logger.info(f"{var}={value}")
        else:
            logger.info(f"{var}=<not set>")

def check_qt_webengine_gpu():
    """Check Qt WebEngine GPU acceleration"""
    logger.info("=== Qt WebEngine GPU Acceleration Test ===")

    # Test Qt WebEngine GPU blacklist
    test_flags = [
        "--disable-gpu",
        "--enable-gpu-rasterization",
        "--enable-zero-copy",
        "--disable-software-rasterizer"
    ]

    for flag in test_flags:
        logger.info(f"Testing with flag: {flag}")
        # This would require running a Qt app with these flags

def create_qt_gpu_test():
    """Create a minimal Qt WebEngine GPU test"""
    logger.info("=== Creating Qt GPU Test Script ===")

    test_script = '''
import sys
import os
from PyQt6.QtWidgets import QApplication
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtCore import QUrl, QTimer

def test_gpu():
    app = QApplication(sys.argv)

    # Create WebEngine view
    view = QWebEngineView()

    # Test HTML with WebGL
    html = """
    <!DOCTYPE html>
    <html>
    <head>
        <title>GPU Test</title>
    </head>
    <body>
        <h1>Qt WebEngine GPU Test</h1>
        <canvas id="glcanvas" width="300" height="300"></canvas>
        <script>
            const canvas = document.getElementById('glcanvas');
            const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');

            if (gl) {
                console.log('WebGL is supported');
                gl.clearColor(0.0, 1.0, 0.0, 1.0);
                gl.clear(gl.COLOR_BUFFER_BIT);
                document.body.innerHTML += '<p style="color: green;">WebGL: SUCCESS</p>';
            } else {
                console.log('WebGL is not supported');
                document.body.innerHTML += '<p style="color: red;">WebGL: FAILED</p>';
            }
        </script>
    </body>
    </html>
    """

    view.setHtml(html)
    view.show()

    # Check GPU processes after 5 seconds
    def check_gpu_processes():
        import subprocess
        try:
            result = subprocess.run(['nvidia-smi', 'pmon'], capture_output=True, text=True)
            print("GPU processes during Qt WebEngine test:")
            print(result.stdout)
        except Exception as e:
            print(f"Could not check GPU processes: {e}")

    QTimer.singleShot(5000, check_gpu_processes)

    return app.exec()

if __name__ == "__main__":
    sys.exit(test_gpu())
'''

    with open('qt_gpu_test.py', 'w') as f:
        f.write(test_script)

    logger.info("Created qt_gpu_test.py - run this to test Qt WebEngine GPU acceleration")

def check_qt_plugins():
    """Check Qt plugin availability"""
    logger.info("=== Qt Plugins Status ===")

    try:
        from PyQt6.QtCore import QLibraryInfo
        plugins_path = QLibraryInfo.path(QLibraryInfo.LibraryPath.PluginsPath)
        logger.info(f"Qt plugins path: {plugins_path}")

        if os.path.exists(plugins_path):
            # List platform plugins
            platform_path = os.path.join(plugins_path, 'platforms')
            if os.path.exists(platform_path):
                platforms = os.listdir(platform_path)
                logger.info(f"Available platform plugins: {platforms}")
            else:
                logger.warning("No platforms plugin directory found")
        else:
            logger.error("Qt plugins path does not exist")

    except Exception as e:
        logger.error(f"Could not check Qt plugins: {e}")

def main():
    """Main diagnostic function"""
    logger.info("Starting GPU acceleration diagnostics...")

    check_nvidia_gpu()
    check_opengl()
    check_qt_environment()
    check_qt_plugins()
    create_qt_gpu_test()

    logger.info("=== Diagnostic Complete ===")
    logger.info("Run 'python qt_gpu_test.py' to test Qt WebEngine GPU acceleration")
    logger.info("Check the output for WebGL support and GPU process monitoring")

if __name__ == "__main__":
    main()