#!/usr/bin/env python3
#
# Copyright (c) 2026 Stormux
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

"""Local ext-workspace protocol wrapper built on top of base pywayland."""

from __future__ import annotations

import importlib
from types import ModuleType
from typing import Any

INTERFACE_NAME = "ext_workspace_manager_v1"
INTERFACE_VERSION = 1
ACTIVE_STATE_VALUE = 1
WORKSPACE_HANDLE_INTERFACE_NAME = "ext_workspace_handle_v1"


def _load_module(module_names: list[str]) -> ModuleType | None:
    for moduleName in module_names:
        try:
            return importlib.import_module(moduleName)
        except ImportError:
            continue
    return None


def _first_attribute(module: ModuleType | None, attribute_names: list[str]) -> Any:
    if module is None:
        return None

    for attributeName in attribute_names:
        if hasattr(module, attributeName):
            return getattr(module, attributeName)
    return None


_pywaylandClientModule = _load_module(
    [
        "pywayland.client",
        "pywayland.client.display",
    ]
)
Display = _first_attribute(_pywaylandClientModule, ["Display"])


class _LocalProtocolProxy:
    """Minimal local proxy descriptor with a dispatcher-compatible shape."""

    interface_name = ""
    version = 1
    event_names: tuple[str, ...] = ()

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        try:
            super().__init__(*args, **kwargs)
        except Exception:
            pass
        self.dispatcher = getattr(self, "dispatcher", {}) or {}


class ExtWorkspaceManagerV1(_LocalProtocolProxy):
    interface_name = INTERFACE_NAME
    version = INTERFACE_VERSION
    event_names = ("workspace", "done", "finished")


class ExtWorkspaceHandleV1(_LocalProtocolProxy):
    interface_name = WORKSPACE_HANDLE_INTERFACE_NAME
    version = INTERFACE_VERSION
    event_names = ("name", "coordinates", "state", "removed")


def get_display_class() -> Any:
    return Display


def has_runtime_support() -> bool:
    return Display is not None


def bind_workspace_manager(registry: Any, global_name: int, version: int) -> Any:
    bind = getattr(registry, "bind", None)
    if not callable(bind):
        return None

    for bindArgs in (
        (global_name, ExtWorkspaceManagerV1, version),
        (global_name, version, ExtWorkspaceManagerV1),
        (global_name, INTERFACE_NAME, version),
        (global_name, version, INTERFACE_NAME),
    ):
        try:
            proxy = bind(*bindArgs)
            return _ensure_dispatcher(proxy)
        except TypeError:
            continue

    return None


def _ensure_dispatcher(proxy: Any) -> Any:
    if proxy is None:
        return None

    if getattr(proxy, "dispatcher", None) is None:
        try:
            proxy.dispatcher = {}
        except Exception:
            pass
    return proxy


__all__ = [
    "ACTIVE_STATE_VALUE",
    "Display",
    "ExtWorkspaceHandleV1",
    "ExtWorkspaceManagerV1",
    "INTERFACE_NAME",
    "INTERFACE_VERSION",
    "WORKSPACE_HANDLE_INTERFACE_NAME",
    "bind_workspace_manager",
    "get_display_class",
    "has_runtime_support",
]
