"""Module discovery from glob patterns."""

from __future__ import annotations

from fnmatch import fnmatch
from pathlib import Path
from typing import Any, Callable


def discover_modules(
    root: Path,
    patterns: list[str],
    exclude: list[str] | None = None,
) -> list[str]:
    """Discover modules matching glob patterns.

    Args:
        root: Project root directory.
        patterns: Glob patterns to match (e.g., ["src/**/*.py"]).
        exclude: Patterns to exclude.

    Returns:
        List of relative paths to discovered modules.
    """
    exclude = exclude or []
    modules = set()

    for pattern in patterns:
        for path in root.glob(pattern):
            if not path.is_file():
                continue

            rel_path = str(path.relative_to(root))

            # Check exclusions
            excluded = False
            for exc_pattern in exclude:
                if fnmatch(rel_path, exc_pattern):
                    excluded = True
                    break

            if not excluded:
                modules.add(rel_path)

    return sorted(modules)


def sync_registry(
    root: Path,
    patterns: list[str],
    exclude: list[str] | None = None,
    existing: dict[str, Any] | None = None,
    get_priority: Callable[[str], tuple[str, int]] | None = None,
) -> tuple[list[str], list[str]]:
    """Sync registry with discovered modules.

    Args:
        root: Project root directory.
        patterns: Glob patterns for discovery.
        exclude: Patterns to exclude.
        existing: Existing module paths in registry.
        get_priority: Function to get (level, reviewers_required) for a path.

    Returns:
        Tuple of (added_paths, removed_paths).
    """
    existing = existing or {}
    discovered = set(discover_modules(root, patterns, exclude))
    current = set(existing.keys())

    added = discovered - current
    removed = current - discovered

    return sorted(added), sorted(removed)
