"""Env module for pytola_core."""

import os
from abc import ABC, abstractmethod
from pathlib import Path

from .logger import get_logger

__all__ = [
    "setup_pyside_env",
]

logger = get_logger(__name__)


class BaseEnv(ABC):
    """Base environment class for all environments."""

    @classmethod
    @abstractmethod
    def setup(cls) -> None:
        """Set up the environment."""


class PysideEnv(BaseEnv):
    """PySide environment class for creating GUI applications."""

    @classmethod
    def setup(cls) -> None:
        """Set up the PySide environment."""
        qt_plugins_path = None
        try:
            import PySide2

            pyside2_dir = Path(PySide2.__file__).parent
            plugins_path = pyside2_dir / "plugins"

            if plugins_path.exists():
                qt_plugins_path = str(plugins_path.absolute()).strip()
                os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = qt_plugins_path
                os.environ["QT_PLUGIN_PATH"] = qt_plugins_path
            else:
                logger.warning("PySide2 plugins path not found")
        except ImportError:
            pass
        else:
            if qt_plugins_path:
                logger.info(f"PySide2 plugins path: {qt_plugins_path}")

            # WSL 环境下智能配置图形后端
            if cls._is_wsl():
                logger.info("WSL environment detected")

                # 检查是否有 WSLg 支持
                has_wslg = os.environ.get("WAYLAND_DISPLAY") or Path("/mnt/wslg").exists()

                if has_wslg:
                    # WSLg: 使用 XCB 平台, 可以显示窗口
                    logger.info("WSLg detected, using XCB platform for GUI display")
                    os.environ["DISPLAY"] = ":0"
                    os.environ["QT_QPA_PLATFORM"] = "xcb"
                else:
                    # 无 WSLg: 使用离屏模式, 软件渲染
                    logger.info("No WSLg, using offscreen rendering (headless mode)")
                    os.environ["QT_QPA_PLATFORM"] = "offscreen"
                    os.environ["LIBGL_ALWAYS_SOFTWARE"] = "1"
                    os.environ["XCB_GL_INTEGRATION"] = "none"

    @staticmethod
    def _is_wsl() -> bool:
        """Check if running in WSL environment.

        Returns
        -------
            True if running in WSL, False otherwise
        """
        try:
            # 检查 /proc/version 是否包含 WSL 相关标识
            proc_version = Path("/proc/version").read_text(encoding="utf-8").lower()
        except (FileNotFoundError, PermissionError):
            return False
        else:
            return "microsoft" in proc_version or "wsl" in proc_version


setup_pyside_env = PysideEnv.setup
