"""
conftest.py - Shared pytest fixtures for filesystemwatcher-mcp tests.
"""

import sys
import time
from collections import deque
from pathlib import Path
import threading
import pytest

# Make src/ importable without installing the package
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from watcher import WatchManager  # noqa: E402 – after path insertion


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------


@pytest.fixture()
def tmp_watch_dir(tmp_path: Path) -> Path:
    """A fresh temporary directory for each test."""
    watch_dir = tmp_path / "watch"
    watch_dir.mkdir()
    return watch_dir


@pytest.fixture()
def fresh_manager() -> "WatchManager":
    """
    An isolated WatchManager instance.
    Calls stop_all() after the test to clean up observer threads.
    """
    mgr = WatchManager()
    yield mgr
    mgr.stop_all()


@pytest.fixture()
def fresh_queue():
    """A fresh deque + lock pair for DebouncedEventHandler unit tests."""
    q: deque = deque()
    lock = threading.Lock()
    return q, lock


def wait_for_events(
    manager: WatchManager,
    watch_id: str,
    expected_count: int,
    timeout: float = 3.0,
) -> list:
    """
    Poll until *expected_count* events appear in the manager's queue for
    *watch_id*, or until *timeout* seconds elapse.
    """
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        events = manager.poll_events(watch_id=watch_id)
        if len(events) >= expected_count:
            return events
        # Put them back — poll_events consumed them
        with manager._queue_lock:
            manager._queue.extend(events)
        time.sleep(0.05)
    # Return whatever we have
    return manager.poll_events(watch_id=watch_id)
