# -*- coding: utf-8 -*-
"""
Compatibility helpers for Qt/QGIS enum scoping and exec() renames.

Use these to write code that works with both PyQt5 and PyQt6, and across
QGIS versions where enums moved into nested classes.
"""

from __future__ import annotations

from typing import Any, Iterable

_MISSING = object()


def enum_value(
    container: Any,
    enum_name: str,
    value_name: str,
    *,
    default: Any = _MISSING,
) -> Any:
    """
    Return enum value from either a nested enum class or the container.

    Examples:
        enum_value(Qt, "CheckState", "Checked")
        enum_value(QMessageBox, "StandardButton", "Ok")
        enum_value(Qgis, "MessageLevel", "Warning")
    """
    enum_cls = getattr(container, enum_name, None)
    if enum_cls is not None and hasattr(enum_cls, value_name):
        return getattr(enum_cls, value_name)
    if hasattr(container, value_name):
        return getattr(container, value_name)
    if default is not _MISSING:
        return default
    raise AttributeError(
        f"{container!r} has no enum '{enum_name}.{value_name}' or '{value_name}'"
    )


def enum_value_any(
    container: Any,
    value_name: str,
    enum_names: Iterable[str],
    *,
    default: Any = _MISSING,
) -> Any:
    """
    Return the first matching enum value from a list of enum class names.
    """
    for enum_name in enum_names:
        enum_cls = getattr(container, enum_name, None)
        if enum_cls is not None and hasattr(enum_cls, value_name):
            return getattr(enum_cls, value_name)
    if hasattr(container, value_name):
        return getattr(container, value_name)
    if default is not _MISSING:
        return default
    names = ", ".join(enum_names)
    raise AttributeError(
        f"{container!r} has no enum value '{value_name}' in {names} or on container"
    )


def qt_enum(
    container: Any,
    enum_name: str,
    value_name: str,
    *,
    default: Any = _MISSING,
) -> Any:
    """
    Qt-specific alias for enum_value.
    """
    return enum_value(container, enum_name, value_name, default=default)


def qgis_enum(
    container: Any,
    enum_name: str,
    value_name: str,
    *,
    default: Any = _MISSING,
) -> Any:
    """
    QGIS-specific alias for enum_value.
    """
    return enum_value(container, enum_name, value_name, default=default)


def qt_exec(dialog: Any) -> int:
    """
    Call exec() on Qt dialogs across PyQt versions.
    """
    if hasattr(dialog, "exec"):
        return dialog.exec()
    return dialog.exec_()
