"""Unit tests for federation discovery (env roots + participant detection)."""

from __future__ import annotations

from pathlib import Path

import pytest

from mgf.fed_web.discovery import (
    ROOTS_ENV,
    discover_projects,
    discover_roots,
    find_project,
)


def test_discover_roots_uses_env_when_set(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    monkeypatch.setenv(ROOTS_ENV, f"{tmp_path / 'a'}:{tmp_path / 'b'}")
    roots = discover_roots()
    assert roots == [tmp_path / "a", tmp_path / "b"]


def test_discover_roots_defaults_to_workspace(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv(ROOTS_ENV, raising=False)
    roots = discover_roots()
    assert len(roots) == 1 and roots[0].is_dir()


def test_discover_finds_only_participants(synthetic: Path) -> None:
    slugs = {p.slug for p in discover_projects()}
    assert {"alpha", "beta", "broken"} <= slugs


def test_discover_skips_dirs_without_a_manifest(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    (tmp_path / "not-a-project").mkdir()
    (tmp_path / "bare" / "fed-resources").mkdir(parents=True)  # no generated/manifest
    monkeypatch.setenv(ROOTS_ENV, str(tmp_path))
    assert discover_projects() == []


def test_find_project_hit_and_miss(synthetic: Path) -> None:
    assert find_project("alpha") is not None
    assert find_project("does-not-exist") is None


def test_missing_root_is_tolerated(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    monkeypatch.setenv(ROOTS_ENV, str(tmp_path / "nope"))
    assert discover_projects() == []
