"""
Qt5/Qt6 Compatibility Module for Dual Profile Viewer Plugin

This module provides compatibility shims for PyQt5 and PyQt6 differences,
allowing the plugin to work with both QGIS 3.x (Qt5) and QGIS 4.x (Qt6).

Usage:
    from . import qt_compat

    # Instead of Qt.Horizontal:
    slider = QSlider(qt_compat.Horizontal)

    # Instead of Qt.AlignCenter:
    label.setAlignment(qt_compat.AlignCenter)

    # Instead of dialog.exec_():
    if qt_compat.dialog_exec(dialog):
        ...
"""

from qgis.PyQt.QtCore import Qt

# Detect Qt version
try:
    from qgis.PyQt.QtCore import PYQT_VERSION_STR
    QT_VERSION = int(PYQT_VERSION_STR.split('.')[0])
except Exception:
    QT_VERSION = 5

IS_QT6 = QT_VERSION >= 6


def _get_enum_value(enum_class_name, value_name):
    """Get enum value compatible with both Qt5 and Qt6.

    In Qt5: Qt.AlignCenter
    In Qt6: Qt.AlignmentFlag.AlignCenter
    """
    # First try direct access (Qt5 style)
    if hasattr(Qt, value_name):
        return getattr(Qt, value_name)

    # Then try scoped enum (Qt6 style)
    if hasattr(Qt, enum_class_name):
        enum_class = getattr(Qt, enum_class_name)
        if hasattr(enum_class, value_name):
            return getattr(enum_class, value_name)

    raise AttributeError(f"Could not find {enum_class_name}.{value_name} in Qt")


# Qt.AlignmentFlag / Qt.Alignment
AlignLeft = _get_enum_value('AlignmentFlag', 'AlignLeft')
AlignRight = _get_enum_value('AlignmentFlag', 'AlignRight')
AlignCenter = _get_enum_value('AlignmentFlag', 'AlignCenter')
AlignTop = _get_enum_value('AlignmentFlag', 'AlignTop')
AlignBottom = _get_enum_value('AlignmentFlag', 'AlignBottom')
AlignHCenter = _get_enum_value('AlignmentFlag', 'AlignHCenter')
AlignVCenter = _get_enum_value('AlignmentFlag', 'AlignVCenter')


# Qt.Orientation
Horizontal = _get_enum_value('Orientation', 'Horizontal')
Vertical = _get_enum_value('Orientation', 'Vertical')


# Qt.ItemDataRole
UserRole = _get_enum_value('ItemDataRole', 'UserRole')
DisplayRole = _get_enum_value('ItemDataRole', 'DisplayRole')
EditRole = _get_enum_value('ItemDataRole', 'EditRole')


# Qt.WindowModality
WindowModal = _get_enum_value('WindowModality', 'WindowModal')
ApplicationModal = _get_enum_value('WindowModality', 'ApplicationModal')
NonModal = _get_enum_value('WindowModality', 'NonModal')


# Qt.CheckState
Checked = _get_enum_value('CheckState', 'Checked')
Unchecked = _get_enum_value('CheckState', 'Unchecked')
PartiallyChecked = _get_enum_value('CheckState', 'PartiallyChecked')


# Qt.CursorShape
WaitCursor = _get_enum_value('CursorShape', 'WaitCursor')
ArrowCursor = _get_enum_value('CursorShape', 'ArrowCursor')
CrossCursor = _get_enum_value('CursorShape', 'CrossCursor')
PointingHandCursor = _get_enum_value('CursorShape', 'PointingHandCursor')


# Qt.ItemFlag
ItemIsEnabled = _get_enum_value('ItemFlag', 'ItemIsEnabled')
ItemIsSelectable = _get_enum_value('ItemFlag', 'ItemIsSelectable')
ItemIsEditable = _get_enum_value('ItemFlag', 'ItemIsEditable')
ItemIsUserCheckable = _get_enum_value('ItemFlag', 'ItemIsUserCheckable')


# Qt.DockWidgetArea
LeftDockWidgetArea = _get_enum_value('DockWidgetArea', 'LeftDockWidgetArea')
RightDockWidgetArea = _get_enum_value('DockWidgetArea', 'RightDockWidgetArea')
TopDockWidgetArea = _get_enum_value('DockWidgetArea', 'TopDockWidgetArea')
BottomDockWidgetArea = _get_enum_value('DockWidgetArea', 'BottomDockWidgetArea')


# Qt.ToolBarArea
LeftToolBarArea = _get_enum_value('ToolBarArea', 'LeftToolBarArea')
RightToolBarArea = _get_enum_value('ToolBarArea', 'RightToolBarArea')
TopToolBarArea = _get_enum_value('ToolBarArea', 'TopToolBarArea')
BottomToolBarArea = _get_enum_value('ToolBarArea', 'BottomToolBarArea')


# Qt.AspectRatioMode
KeepAspectRatio = _get_enum_value('AspectRatioMode', 'KeepAspectRatio')
IgnoreAspectRatio = _get_enum_value('AspectRatioMode', 'IgnoreAspectRatio')
KeepAspectRatioByExpanding = _get_enum_value('AspectRatioMode', 'KeepAspectRatioByExpanding')


# Qt.TransformationMode
SmoothTransformation = _get_enum_value('TransformationMode', 'SmoothTransformation')
FastTransformation = _get_enum_value('TransformationMode', 'FastTransformation')


# Qt.ScrollBarPolicy
ScrollBarAlwaysOff = _get_enum_value('ScrollBarPolicy', 'ScrollBarAlwaysOff')
ScrollBarAlwaysOn = _get_enum_value('ScrollBarPolicy', 'ScrollBarAlwaysOn')
ScrollBarAsNeeded = _get_enum_value('ScrollBarPolicy', 'ScrollBarAsNeeded')


# Qt.WindowType
Widget = _get_enum_value('WindowType', 'Widget')
Window = _get_enum_value('WindowType', 'Window')
Dialog = _get_enum_value('WindowType', 'Dialog')
Popup = _get_enum_value('WindowType', 'Popup')
Tool = _get_enum_value('WindowType', 'Tool')


# Qt.GlobalColor
black = _get_enum_value('GlobalColor', 'black')
white = _get_enum_value('GlobalColor', 'white')
red = _get_enum_value('GlobalColor', 'red')
green = _get_enum_value('GlobalColor', 'green')
blue = _get_enum_value('GlobalColor', 'blue')
yellow = _get_enum_value('GlobalColor', 'yellow')
gray = _get_enum_value('GlobalColor', 'gray')
darkGray = _get_enum_value('GlobalColor', 'darkGray')
lightGray = _get_enum_value('GlobalColor', 'lightGray')
transparent = _get_enum_value('GlobalColor', 'transparent')


# Qt.PenStyle
NoPen = _get_enum_value('PenStyle', 'NoPen')
SolidLine = _get_enum_value('PenStyle', 'SolidLine')
DashLine = _get_enum_value('PenStyle', 'DashLine')
DotLine = _get_enum_value('PenStyle', 'DotLine')


# Qt.BrushStyle
NoBrush = _get_enum_value('BrushStyle', 'NoBrush')
SolidPattern = _get_enum_value('BrushStyle', 'SolidPattern')


# Qt.Key
Key_Escape = _get_enum_value('Key', 'Key_Escape')
Key_Return = _get_enum_value('Key', 'Key_Return')
Key_Enter = _get_enum_value('Key', 'Key_Enter')
Key_Delete = _get_enum_value('Key', 'Key_Delete')


# Qt.KeyboardModifier
NoModifier = _get_enum_value('KeyboardModifier', 'NoModifier')
ShiftModifier = _get_enum_value('KeyboardModifier', 'ShiftModifier')
ControlModifier = _get_enum_value('KeyboardModifier', 'ControlModifier')
AltModifier = _get_enum_value('KeyboardModifier', 'AltModifier')


# Qt.MouseButton
LeftButton = _get_enum_value('MouseButton', 'LeftButton')
RightButton = _get_enum_value('MouseButton', 'RightButton')
MiddleButton = _get_enum_value('MouseButton', 'MiddleButton')
NoButton = _get_enum_value('MouseButton', 'NoButton')


def dialog_exec(dialog):
    """Execute dialog in a way compatible with both Qt5 and Qt6.

    In Qt6, exec_() was removed and only exec() exists.
    In Qt5, both exec() and exec_() exist.

    Args:
        dialog: QDialog instance

    Returns:
        Dialog result code (QDialog.Accepted or QDialog.Rejected)
    """
    if hasattr(dialog, 'exec'):
        return dialog.exec()
    else:
        return dialog.exec_()


# QAction import compatibility
# In Qt6, QAction moved from QtWidgets to QtGui
try:
    from qgis.PyQt.QtGui import QAction
except ImportError:
    from qgis.PyQt.QtWidgets import QAction


# WebEngine/WebKit compatibility
def get_web_view():
    """Get WebEngineView or WebView class, whichever is available."""
    try:
        from qgis.PyQt.QtWebEngineWidgets import QWebEngineView
        return QWebEngineView
    except ImportError:
        try:
            from qgis.PyQt.QtWebKitWidgets import QWebView
            return QWebView
        except ImportError:
            return None
