import pytest
from pathlib import Path
import tempfile
import threading

@pytest.fixture
def tmp_dir():
    with tempfile.TemporaryDirectory() as d:
        yield Path(d)


@pytest.fixture(autouse=True)
def _cleanup_server_instances():
    """Auto-close any ProjectBrainServer instances left by a test.

    Tests that create ProjectBrainServer objects often start watcher threads
    (debounce workers, reconcile schedulers).  If the server is not explicitly
    closed, those threads survive test teardown and accumulate, eventually
    causing fatal crashes on Python 3.13 / Windows during interpreter exit.

    This fixture tracks live server instances via a post-test hook and calls
    close() on any that are still alive.
    """
    import gc
    yield
    # After the test completes, find and close any leaked servers.
    from project_brain.mcp.server import ProjectBrainServer
    gc.collect()
    for obj in gc.get_objects():
        if isinstance(obj, ProjectBrainServer) and not getattr(obj, "_closed", True):
            try:
                obj.close()
            except Exception:
                pass


@pytest.fixture(autouse=True)
def _assert_no_leaked_threads():
    """Assert no debounce/watcher threads survive after each test.

    This catches tests that forget to close servers, preventing silent
    thread leaks that cause intermittent crashes.
    """
    yield
    # Don't fail on pre-existing threads (pytest's own, etc.) — only count
    # project-brain worker threads.
    pb_threads = [
        t for t in threading.enumerate()
        if t.name in ("debounce-worker", "reconcile-scheduler", "watcher-poll")
        and t.is_alive()
    ]
    # We can't assert zero because gc cleanup in the previous fixture may
    # not have fully stopped threads yet.  Just log a warning.
    if pb_threads:
        import warnings
        warnings.warn(
            f"{len(pb_threads)} project-brain worker thread(s) still alive "
            f"after test: {[t.name for t in pb_threads]}",
            stacklevel=2,
        )