"""Test fixtures for trigger infrastructure tests."""

from __future__ import annotations

import sys
import types
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass

import pytest


@dataclass
class DummyWindow:
    """Mock window object for pywinctl tests."""

    title: str | None


class _PyWinCtlModule(types.ModuleType):
    """Typed pywinctl module stub for tests."""

    getActiveWindow: Callable[[], DummyWindow | None]


@pytest.fixture
def mock_pywinctl(monkeypatch: pytest.MonkeyPatch) -> Callable[[str | None], None]:
    """Factory fixture to install mocked pywinctl module.

    Usage:
        mock_pywinctl("Zoom Meeting")  # Window with title
        mock_pywinctl(None)  # No active window
    """

    def _install(title: str | None) -> None:
        window = DummyWindow(title) if title is not None else None
        module = _PyWinCtlModule("pywinctl")
        module.getActiveWindow = lambda: window
        monkeypatch.setitem(sys.modules, "pywinctl", module)

    return _install


@pytest.fixture
def mock_pywinctl_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:
    """Install pywinctl mock that raises ImportError."""
    monkeypatch.delitem(sys.modules, "pywinctl", raising=False)

    import builtins

    original_import = builtins.__import__

    def mock_import(
        name: str,
        globals: Mapping[str, object] | None = None,
        locals: Mapping[str, object] | None = None,
        fromlist: Sequence[str] | None = None,
        level: int = 0,
    ) -> object:
        if name == "pywinctl":
            raise ImportError("No module named 'pywinctl'")
        return original_import(name, globals, locals, fromlist, level)

    monkeypatch.setattr(builtins, "__import__", mock_import)


@pytest.fixture
def mock_pywinctl_raises(monkeypatch: pytest.MonkeyPatch) -> None:
    """Install pywinctl mock that raises RuntimeError on getActiveWindow."""

    def raise_runtime_error() -> None:
        msg = "No display available"
        raise RuntimeError(msg)

    module = _PyWinCtlModule("pywinctl")
    module.getActiveWindow = raise_runtime_error
    monkeypatch.setitem(sys.modules, "pywinctl", module)
