#!/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.

"""Helpers for loading Wnck only when the session can support it."""

from __future__ import annotations

import importlib
import os
from types import ModuleType


def get_session_type() -> str:
    sessionType = (os.environ.get("XDG_SESSION_TYPE") or "").strip().lower()
    if sessionType:
        return sessionType
    if os.environ.get("WAYLAND_DISPLAY"):
        return "wayland"
    if os.environ.get("DISPLAY"):
        return "x11"
    return "unknown"


def can_use_wnck(session_type: str | None = None) -> bool:
    return (session_type or get_session_type()).strip().lower() == "x11"


def load_wnck(session_type: str | None = None) -> ModuleType | None:
    if not can_use_wnck(session_type):
        return None

    gi = importlib.import_module("gi")
    gi.require_version("Wnck", "3.0")
    return importlib.import_module("gi.repository.Wnck")
