"""
Simplified GUI integration utilities for threading in XPCS Viewer.

This module provides basic threading integration for GUI responsiveness.
"""

from __future__ import annotations

from collections.abc import Callable
from functools import wraps

# Qt imports via compatibility layer
from xpcsviewer.gui.qt_compat import QtWidgets

from ..utils.logging_config import get_logger
from .async_workers import WorkerManager
from .progress_manager import ProgressManager

logger = get_logger(__name__)


class ThreadingIntegrator:
    """Simplified threading integration for GUI applications."""

    def __init__(self, main_window: QtWidgets.QMainWindow):
        """Initialize with basic threading components."""
        self.main_window = main_window

        from xpcsviewer.gui.qt_compat import QThreadPool

        # Initialize basic components
        self.worker_manager = WorkerManager(QThreadPool.globalInstance())
        self.progress_manager = ProgressManager(main_window)

        # Set up status bar if available
        if hasattr(main_window, "statusbar") or hasattr(main_window, "statusBar"):
            statusbar = getattr(main_window, "statusbar", None) or getattr(
                main_window, "statusBar", None
            )
            if statusbar:
                widget = statusbar() if callable(statusbar) else statusbar
                self.progress_manager.set_statusbar(widget)

        logger.info("ThreadingIntegrator initialized")

    def get_worker_manager(self) -> WorkerManager:
        """Get the worker manager."""
        return self.worker_manager

    def get_progress_manager(self) -> ProgressManager:
        """Get the progress manager."""
        return self.progress_manager


def make_async(func: Callable) -> Callable:
    """Decorator that submits a function to WorkerManager for async execution (BUG-049).

    The decorated function will be run in a background thread via QThreadPool
    instead of blocking the calling thread (typically the GUI main thread).

    The wrapper returns a WorkerResult future-like object. For GUI-connected
    callbacks, callers should connect to signals on the worker rather than
    using the return value directly.
    """
    from xpcsviewer.gui.qt_compat import QThreadPool

    @wraps(func)
    def wrapper(*args, **kwargs):
        thread_pool = QThreadPool.globalInstance()
        worker_manager = WorkerManager(thread_pool)
        try:
            return worker_manager.submit_task(func, *args, **kwargs)
        except Exception as exc:
            # Fallback: execute synchronously if submission fails
            logger.warning(
                f"make_async: failed to submit {func.__name__!r} to WorkerManager "
                f"({exc!r}); falling back to synchronous execution."
            )
            return func(*args, **kwargs)

    return wrapper


def setup_enhanced_threading(main_window: QtWidgets.QMainWindow) -> ThreadingIntegrator:
    """Set up simplified threading for a main window."""
    return ThreadingIntegrator(main_window)


# Simplified async functions for compatibility
def async_load_xpcs_files(file_paths, progress_callback=None):
    """Simplified async file loading."""
    logger.info(f"Loading {len(file_paths)} XPCS files")
    # This would normally be implemented with proper async loading
    return []


def async_generate_g2_plot(data, progress_callback=None):
    """Simplified async G2 plot generation."""
    logger.info("Generating G2 plot")
    # This would normally be implemented with proper async plotting


def async_generate_saxs_plot(data, progress_callback=None):
    """Simplified async SAXS plot generation."""
    logger.info("Generating SAXS plot")
    # This would normally be implemented with proper async plotting


def create_progress_callback(progress_manager, task_name):
    """Create a simple progress callback."""

    def callback(progress):
        logger.debug(f"{task_name}: {progress}%")

    return callback


def create_completion_callback(on_complete):
    """Create a simple completion callback."""

    def callback(result):
        if on_complete:
            on_complete(result)

    return callback


class AsyncMethodMixin:
    """Simplified mixin for async methods."""

    def make_async_method(self, method):
        """Make a method async (simplified)."""
        return make_async(method)
