# -*- coding: utf-8 -*-
"""
Qt5/Qt6 and QGIS 3/QGIS 4 compatibility layer for MapBiomas Fogo plugin.

Provides Qt6-style nested enum syntax that works in both Qt5 and Qt6:
    Qt.CheckState.Checked, Qt.ItemDataRole.UserRole, etc.

This satisfies OSGEO plugin checker requirements for Qt6 compatibility.
"""

# Detect PyQt5 (QGIS 3) vs PyQt6 (QGIS 4)
try:
    from qgis.PyQt.QtCore import Qt as _Qt
    _Qt.CheckState.Checked  # Test for Qt6 nested enums
    _IS_QT6 = True
except (ImportError, AttributeError):
    from qgis.PyQt.QtCore import Qt as _Qt
    _IS_QT6 = False


# ============================================================================
# Qt Enum Namespaces (Qt6 style - nested)
# ============================================================================

class CheckState:
    """Qt.CheckState enum namespace."""
    if _IS_QT6:
        Checked = _Qt.CheckState.Checked
        Unchecked = _Qt.CheckState.Unchecked
        PartiallyChecked = _Qt.CheckState.PartiallyChecked
    else:
        Checked = _Qt.Checked
        Unchecked = _Qt.Unchecked
        PartiallyChecked = _Qt.PartiallyChecked


class KeyboardModifier:
    """Qt.KeyboardModifier enum namespace."""
    if _IS_QT6:
        NoModifier = _Qt.KeyboardModifier.NoModifier
        ControlModifier = _Qt.KeyboardModifier.ControlModifier
        ShiftModifier = _Qt.KeyboardModifier.ShiftModifier
        AltModifier = _Qt.KeyboardModifier.AltModifier
        MetaModifier = _Qt.KeyboardModifier.MetaModifier
    else:
        NoModifier = _Qt.NoModifier
        ControlModifier = _Qt.ControlModifier
        ShiftModifier = _Qt.ShiftModifier
        AltModifier = _Qt.AltModifier
        MetaModifier = _Qt.MetaModifier


class ItemDataRole:
    """Qt.ItemDataRole enum namespace."""
    if _IS_QT6:
        UserRole = _Qt.ItemDataRole.UserRole
        DisplayRole = _Qt.ItemDataRole.DisplayRole
        DecorationRole = _Qt.ItemDataRole.DecorationRole
        EditRole = _Qt.ItemDataRole.EditRole
        ToolTipRole = _Qt.ItemDataRole.ToolTipRole
        StatusTipRole = _Qt.ItemDataRole.StatusTipRole
        CheckStateRole = _Qt.ItemDataRole.CheckStateRole
        SizeHintRole = _Qt.ItemDataRole.SizeHintRole
    else:
        UserRole = _Qt.UserRole
        DisplayRole = _Qt.DisplayRole
        DecorationRole = _Qt.DecorationRole
        EditRole = _Qt.EditRole
        ToolTipRole = _Qt.ToolTipRole
        StatusTipRole = _Qt.StatusTipRole
        CheckStateRole = _Qt.CheckStateRole
        SizeHintRole = _Qt.SizeHintRole


class ItemFlag:
    """Qt.ItemFlag enum namespace."""
    if _IS_QT6:
        ItemIsEditable = _Qt.ItemFlag.ItemIsEditable
        ItemIsEnabled = _Qt.ItemFlag.ItemIsEnabled
        ItemIsSelectable = _Qt.ItemFlag.ItemIsSelectable
        ItemIsUserCheckable = _Qt.ItemFlag.ItemIsUserCheckable
        ItemIsUserTristate = _Qt.ItemFlag.ItemIsUserTristate
        ItemNeverHasChildren = _Qt.ItemFlag.ItemNeverHasChildren
        ItemIsDragEnabled = _Qt.ItemFlag.ItemIsDragEnabled
        ItemIsDropEnabled = _Qt.ItemFlag.ItemIsDropEnabled
        NoItemFlags = _Qt.ItemFlag.NoItemFlags
    else:
        ItemIsEditable = _Qt.ItemIsEditable
        ItemIsEnabled = _Qt.ItemIsEnabled
        ItemIsSelectable = _Qt.ItemIsSelectable
        ItemIsUserCheckable = _Qt.ItemIsUserCheckable
        ItemIsUserTristate = _Qt.ItemIsUserTristate
        ItemNeverHasChildren = _Qt.ItemNeverHasChildren
        ItemIsDragEnabled = _Qt.ItemIsDragEnabled
        ItemIsDropEnabled = _Qt.ItemIsDropEnabled
        NoItemFlags = _Qt.NoItemFlags


class AlignmentFlag:
    """Qt.AlignmentFlag enum namespace."""
    if _IS_QT6:
        AlignLeft = _Qt.AlignmentFlag.AlignLeft
        AlignRight = _Qt.AlignmentFlag.AlignRight
        AlignCenter = _Qt.AlignmentFlag.AlignCenter
        AlignHCenter = _Qt.AlignmentFlag.AlignHCenter
        AlignVCenter = _Qt.AlignmentFlag.AlignVCenter
        AlignTop = _Qt.AlignmentFlag.AlignTop
        AlignBottom = _Qt.AlignmentFlag.AlignBottom
        AlignJustify = _Qt.AlignmentFlag.AlignJustify
        AlignAbsolute = _Qt.AlignmentFlag.AlignAbsolute
    else:
        AlignLeft = _Qt.AlignLeft
        AlignRight = _Qt.AlignRight
        AlignCenter = _Qt.AlignCenter
        AlignHCenter = _Qt.AlignHCenter
        AlignVCenter = _Qt.AlignVCenter
        AlignTop = _Qt.AlignTop
        AlignBottom = _Qt.AlignBottom
        AlignJustify = _Qt.AlignJustify
        AlignAbsolute = _Qt.AlignAbsolute


class SortOrder:
    """Qt.SortOrder enum namespace."""
    if _IS_QT6:
        AscendingOrder = _Qt.SortOrder.AscendingOrder
        DescendingOrder = _Qt.SortOrder.DescendingOrder
    else:
        AscendingOrder = _Qt.AscendingOrder
        DescendingOrder = _Qt.DescendingOrder


class ContextMenuPolicy:
    """Qt.ContextMenuPolicy enum namespace."""
    if _IS_QT6:
        CustomContextMenu = _Qt.ContextMenuPolicy.CustomContextMenu
        NoContextMenu = _Qt.ContextMenuPolicy.NoContextMenu
        DefaultContextMenu = _Qt.ContextMenuPolicy.DefaultContextMenu
        ActionsContextMenu = _Qt.ContextMenuPolicy.ActionsContextMenu
        PreventContextMenu = _Qt.ContextMenuPolicy.PreventContextMenu
    else:
        CustomContextMenu = _Qt.CustomContextMenu
        NoContextMenu = _Qt.NoContextMenu
        DefaultContextMenu = _Qt.DefaultContextMenu
        ActionsContextMenu = _Qt.ActionsContextMenu
        PreventContextMenu = _Qt.PreventContextMenu


class WidgetAttribute:
    """Qt.WidgetAttribute enum namespace."""
    if _IS_QT6:
        WA_DeleteOnClose = _Qt.WidgetAttribute.WA_DeleteOnClose
        WA_TranslucentBackground = _Qt.WidgetAttribute.WA_TranslucentBackground
        WA_NoSystemBackground = _Qt.WidgetAttribute.WA_NoSystemBackground
    else:
        WA_DeleteOnClose = _Qt.WA_DeleteOnClose
        WA_TranslucentBackground = _Qt.WA_TranslucentBackground
        WA_NoSystemBackground = _Qt.WA_NoSystemBackground


class DockWidgetArea:
    """Qt.DockWidgetArea enum namespace."""
    if _IS_QT6:
        RightDockWidgetArea = _Qt.DockWidgetArea.RightDockWidgetArea
        LeftDockWidgetArea = _Qt.DockWidgetArea.LeftDockWidgetArea
        TopDockWidgetArea = _Qt.DockWidgetArea.TopDockWidgetArea
        BottomDockWidgetArea = _Qt.DockWidgetArea.BottomDockWidgetArea
        NoDockWidgetArea = _Qt.DockWidgetArea.NoDockWidgetArea
    else:
        RightDockWidgetArea = _Qt.RightDockWidgetArea
        LeftDockWidgetArea = _Qt.LeftDockWidgetArea
        TopDockWidgetArea = _Qt.TopDockWidgetArea
        BottomDockWidgetArea = _Qt.BottomDockWidgetArea
        NoDockWidgetArea = _Qt.NoDockWidgetArea


class FocusReason:
    """Qt.FocusReason enum namespace."""
    if _IS_QT6:
        OtherFocusReason = _Qt.FocusReason.OtherFocusReason
        TabFocusReason = _Qt.FocusReason.TabFocusReason
        MouseFocusReason = _Qt.FocusReason.MouseFocusReason
        BacktabFocusReason = _Qt.FocusReason.BacktabFocusReason
        ActiveWindowFocusReason = _Qt.FocusReason.ActiveWindowFocusReason
        PopupFocusReason = _Qt.FocusReason.PopupFocusReason
        ShortcutFocusReason = _Qt.FocusReason.ShortcutFocusReason
        MenuBarFocusReason = _Qt.FocusReason.MenuBarFocusReason
    else:
        OtherFocusReason = _Qt.OtherFocusReason
        TabFocusReason = _Qt.TabFocusReason
        MouseFocusReason = _Qt.MouseFocusReason
        BacktabFocusReason = _Qt.BacktabFocusReason
        ActiveWindowFocusReason = _Qt.ActiveWindowFocusReason
        PopupFocusReason = _Qt.PopupFocusReason
        ShortcutFocusReason = _Qt.ShortcutFocusReason
        MenuBarFocusReason = _Qt.MenuBarFocusReason


class Orientation:
    """Qt.Orientation enum namespace."""
    if _IS_QT6:
        Horizontal = _Qt.Orientation.Horizontal
        Vertical = _Qt.Orientation.Vertical
    else:
        Horizontal = _Qt.Horizontal
        Vertical = _Qt.Vertical


class _QtCompat:
    """
    Qt compatibility namespace providing Qt6-style nested enum access.
    Works in both Qt5 and Qt6 environments.
    """
    # Nested enum namespaces (Qt6 style)
    CheckState = CheckState
    KeyboardModifier = KeyboardModifier
    ItemDataRole = ItemDataRole
    ItemFlag = ItemFlag
    AlignmentFlag = AlignmentFlag
    SortOrder = SortOrder
    ContextMenuPolicy = ContextMenuPolicy
    WidgetAttribute = WidgetAttribute
    DockWidgetArea = DockWidgetArea
    FocusReason = FocusReason
    Orientation = Orientation
    
    # Shortcuts for commonly used values (for backward compatibility)
    CustomContextMenu = ContextMenuPolicy.CustomContextMenu


# Export as Qt for use in plugin code
Qt = _QtCompat


# ============================================================================
# QMessageBox.StandardButton compatibility
# ============================================================================

from qgis.PyQt.QtWidgets import QMessageBox as _QMessageBox


class StandardButton:
    """QMessageBox.StandardButton enum namespace."""
    if _IS_QT6:
        Ok = _QMessageBox.StandardButton.Ok
        Cancel = _QMessageBox.StandardButton.Cancel
        Save = _QMessageBox.StandardButton.Save
        Discard = _QMessageBox.StandardButton.Discard
        Yes = _QMessageBox.StandardButton.Yes
        No = _QMessageBox.StandardButton.No
        Retry = _QMessageBox.StandardButton.Retry
        Ignore = _QMessageBox.StandardButton.Ignore
        NoButton = _QMessageBox.StandardButton.NoButton
    else:
        Ok = _QMessageBox.Ok
        Cancel = _QMessageBox.Cancel
        Save = _QMessageBox.Save
        Discard = _QMessageBox.Discard
        Yes = _QMessageBox.Yes
        No = _QMessageBox.No
        Retry = _QMessageBox.Retry
        Ignore = _QMessageBox.Ignore
        NoButton = _QMessageBox.NoButton


class _QMessageBoxCompat:
    """QMessageBox compatibility wrapper."""
    StandardButton = StandardButton
    
    # Delegate methods to actual QMessageBox
    @staticmethod
    def question(*args, **kwargs):
        return _QMessageBox.question(*args, **kwargs)
    
    @staticmethod
    def information(*args, **kwargs):
        return _QMessageBox.information(*args, **kwargs)
    
    @staticmethod
    def warning(*args, **kwargs):
        return _QMessageBox.warning(*args, **kwargs)
    
    @staticmethod
    def critical(*args, **kwargs):
        return _QMessageBox.critical(*args, **kwargs)


QMessageBox = _QMessageBoxCompat


# ============================================================================
# QHeaderView.ResizeMode compatibility
# ============================================================================

from qgis.PyQt.QtWidgets import QHeaderView as _QHeaderView


class ResizeMode:
    """QHeaderView.ResizeMode enum namespace."""
    if _IS_QT6:
        ResizeToContents = _QHeaderView.ResizeMode.ResizeToContents
        Stretch = _QHeaderView.ResizeMode.Stretch
        Fixed = _QHeaderView.ResizeMode.Fixed
        Interactive = _QHeaderView.ResizeMode.Interactive
    else:
        ResizeToContents = _QHeaderView.ResizeToContents
        Stretch = _QHeaderView.Stretch
        Fixed = _QHeaderView.Fixed
        Interactive = _QHeaderView.Interactive


class _QHeaderViewCompat:
    """QHeaderView compatibility wrapper."""
    ResizeMode = ResizeMode


QHeaderView = _QHeaderViewCompat


# ============================================================================
# QAbstractItemView compatibility
# ============================================================================

from qgis.PyQt.QtWidgets import QAbstractItemView as _QAbstractItemView


class EditTrigger:
    """QAbstractItemView.EditTrigger enum namespace."""
    if _IS_QT6:
        NoEditTriggers = _QAbstractItemView.EditTrigger.NoEditTriggers
        CurrentChanged = _QAbstractItemView.EditTrigger.CurrentChanged
        DoubleClicked = _QAbstractItemView.EditTrigger.DoubleClicked
        SelectedClicked = _QAbstractItemView.EditTrigger.SelectedClicked
        EditKeyPressed = _QAbstractItemView.EditTrigger.EditKeyPressed
        AnyKeyPressed = _QAbstractItemView.EditTrigger.AnyKeyPressed
        AllEditTriggers = _QAbstractItemView.EditTrigger.AllEditTriggers
    else:
        NoEditTriggers = _QAbstractItemView.NoEditTriggers
        CurrentChanged = _QAbstractItemView.CurrentChanged
        DoubleClicked = _QAbstractItemView.DoubleClicked
        SelectedClicked = _QAbstractItemView.SelectedClicked
        EditKeyPressed = _QAbstractItemView.EditKeyPressed
        AnyKeyPressed = _QAbstractItemView.AnyKeyPressed
        AllEditTriggers = _QAbstractItemView.AllEditTriggers


class SelectionBehavior:
    """QAbstractItemView.SelectionBehavior enum namespace."""
    if _IS_QT6:
        SelectItems = _QAbstractItemView.SelectionBehavior.SelectItems
        SelectRows = _QAbstractItemView.SelectionBehavior.SelectRows
        SelectColumns = _QAbstractItemView.SelectionBehavior.SelectColumns
    else:
        SelectItems = _QAbstractItemView.SelectItems
        SelectRows = _QAbstractItemView.SelectRows
        SelectColumns = _QAbstractItemView.SelectColumns


class SelectionMode:
    """QAbstractItemView.SelectionMode enum namespace."""
    if _IS_QT6:
        NoSelection = _QAbstractItemView.SelectionMode.NoSelection
        SingleSelection = _QAbstractItemView.SelectionMode.SingleSelection
        MultiSelection = _QAbstractItemView.SelectionMode.MultiSelection
        ExtendedSelection = _QAbstractItemView.SelectionMode.ExtendedSelection
        ContiguousSelection = _QAbstractItemView.SelectionMode.ContiguousSelection
    else:
        NoSelection = _QAbstractItemView.NoSelection
        SingleSelection = _QAbstractItemView.SingleSelection
        MultiSelection = _QAbstractItemView.MultiSelection
        ExtendedSelection = _QAbstractItemView.ExtendedSelection
        ContiguousSelection = _QAbstractItemView.ContiguousSelection


class _QAbstractItemViewCompat:
    """QAbstractItemView compatibility wrapper."""
    EditTrigger = EditTrigger
    SelectionBehavior = SelectionBehavior
    SelectionMode = SelectionMode


QAbstractItemView = _QAbstractItemViewCompat


# ============================================================================
# QGIS-specific compatibility
# ============================================================================

from qgis.core import QgsMapLayerProxyModel as _QgsMapLayerProxyModel


# QgsMapLayerProxyModel.Filter compatibility (QGIS 3 vs QGIS 4)
class Filter:
    """QgsMapLayerProxyModel.Filter enum namespace."""
    try:
        PolygonLayer = _QgsMapLayerProxyModel.Filter.PolygonLayer  # QGIS 4
    except AttributeError:
        PolygonLayer = _QgsMapLayerProxyModel.PolygonLayer  # QGIS 3


class _QgsMapLayerProxyModelCompat:
    """QgsMapLayerProxyModel compatibility wrapper."""
    Filter = Filter


QgsMapLayerProxyModel = _QgsMapLayerProxyModelCompat


# QgsWkbTypes.GeometryType compatibility (QGIS 3 vs QGIS 4)
try:
    from qgis.core import Qgis as _Qgis
    _POLYGON_GEOMETRY = _Qgis.GeometryType.Polygon  # QGIS 4
    _HAS_QGIS4_GEOMETRY = True
except AttributeError:
    from qgis.core import QgsWkbTypes as _QgsWkbTypes
    _POLYGON_GEOMETRY = _QgsWkbTypes.PolygonGeometry  # QGIS 3
    _HAS_QGIS4_GEOMETRY = False


class GeometryType:
    """Qgis.GeometryType / QgsWkbTypes enum namespace."""
    if _HAS_QGIS4_GEOMETRY:
        Polygon = _Qgis.GeometryType.Polygon
        PolygonGeometry = _Qgis.GeometryType.Polygon  # Alias for QGIS 3 compat
    else:
        Polygon = _QgsWkbTypes.PolygonGeometry
        PolygonGeometry = _QgsWkbTypes.PolygonGeometry


# Export Qgis compatibility namespace
class _QgisCompat:
    """Qgis compatibility wrapper."""
    GeometryType = GeometryType
    
    # Expose QGIS_VERSION for version detection
    try:
        QGIS_VERSION = _Qgis.QGIS_VERSION
    except (AttributeError, NameError):
        QGIS_VERSION = "3.0.0"  # Fallback


Qgis = _QgisCompat


# ============================================================================
# QGIS Message Level compatibility
# ============================================================================

from qgis.core import Qgis as _QgisCore

# Detect QGIS 4 by checking for nested enums
try:
    _QgisCore.MessageLevel.Info
    _IS_QGIS4 = True
except (AttributeError, TypeError):
    _IS_QGIS4 = False


class MessageLevel:
    """Qgis.MessageLevel enum namespace."""
    if _IS_QGIS4:
        Info = _QgisCore.MessageLevel.Info
        Warning = _QgisCore.MessageLevel.Warning
        Critical = _QgisCore.MessageLevel.Critical
        Success = _QgisCore.MessageLevel.Success
    else:
        Info = _QgisCore.Info
        Warning = _QgisCore.Warning
        Critical = _QgisCore.Critical
        Success = _QgisCore.Success


class _QgisMessageLevelCompat:
    """Qgis.MessageLevel compatibility wrapper."""
    MessageLevel = MessageLevel
    
    # Provide flat access for backward compatibility
    Info = MessageLevel.Info
    Warning = MessageLevel.Warning
    Critical = MessageLevel.Critical
    Success = MessageLevel.Success


QgisMessageLevel = _QgisMessageLevelCompat


# ============================================================================
# QgsVectorFileWriter.WriterError compatibility
# ============================================================================

from qgis.core import QgsVectorFileWriter as _QgsVectorFileWriter


class WriterError:
    """QgsVectorFileWriter.WriterError enum namespace."""
    if _IS_QGIS4:
        NoError = _QgsVectorFileWriter.WriterError.NoError
        ErrDriverNotFound = _QgsVectorFileWriter.WriterError.ErrDriverNotFound
        ErrCreateDataSource = _QgsVectorFileWriter.WriterError.ErrCreateDataSource
        ErrCreateLayer = _QgsVectorFileWriter.WriterError.ErrCreateLayer
        ErrAttributeTypeUnsupported = _QgsVectorFileWriter.WriterError.ErrAttributeTypeUnsupported
        ErrAttributeCreationFailed = _QgsVectorFileWriter.WriterError.ErrAttributeCreationFailed
        ErrProjection = _QgsVectorFileWriter.WriterError.ErrProjection
        ErrFeatureWriteFailed = _QgsVectorFileWriter.WriterError.ErrFeatureWriteFailed
        ErrInvalidLayer = _QgsVectorFileWriter.WriterError.ErrInvalidLayer
    else:
        NoError = _QgsVectorFileWriter.NoError
        ErrDriverNotFound = _QgsVectorFileWriter.ErrDriverNotFound
        ErrCreateDataSource = _QgsVectorFileWriter.ErrCreateDataSource
        ErrCreateLayer = _QgsVectorFileWriter.ErrCreateLayer
        ErrAttributeTypeUnsupported = _QgsVectorFileWriter.ErrAttributeTypeUnsupported
        ErrAttributeCreationFailed = _QgsVectorFileWriter.ErrAttributeCreationFailed
        ErrProjection = _QgsVectorFileWriter.ErrProjection
        ErrFeatureWriteFailed = _QgsVectorFileWriter.ErrFeatureWriteFailed
        ErrInvalidLayer = _QgsVectorFileWriter.ErrInvalidLayer


class _QgsVectorFileWriterCompat:
    """QgsVectorFileWriter compatibility wrapper."""
    WriterError = WriterError
    
    # Provide flat access for backward compatibility
    NoError = WriterError.NoError
    ErrDriverNotFound = WriterError.ErrDriverNotFound
    ErrCreateDataSource = WriterError.ErrCreateDataSource
    ErrCreateLayer = WriterError.ErrCreateLayer
    ErrAttributeTypeUnsupported = WriterError.ErrAttributeTypeUnsupported
    ErrAttributeCreationFailed = WriterError.ErrAttributeCreationFailed
    ErrProjection = WriterError.ErrProjection
    ErrFeatureWriteFailed = WriterError.ErrFeatureWriteFailed
    ErrInvalidLayer = WriterError.ErrInvalidLayer


QgsVectorFileWriterError = _QgsVectorFileWriterCompat
