"""PNPM project detection and utilities."""

from pathlib import Path


class PnpmProject:
    """PNPM project detection and root finding."""

    @staticmethod
    def find_root(start_path: Path) -> Path | None:
        """Find the frontend project root directory containing package.json.

        Searches from start_path up to its ancestors and also checks subdirectories.

        Args:
            start_path: Starting path to search from

        Returns:
            Path to project root or None if not found
        """
        start_path = start_path.resolve()

        # Check if start_path itself is the root
        if (start_path / "package.json").exists():
            return start_path

        # Search upwards in the directory tree
        current = start_path.parent
        while current != current.parent:
            if (current / "package.json").exists():
                return current
            current = current.parent

        # Search subdirectories
        for subdir in start_path.iterdir():
            if subdir.is_dir() and not subdir.name.startswith("."):
                subdir_root = PnpmProject.find_root(subdir)
                if subdir_root:
                    return subdir_root

        return None

    @staticmethod
    def validate(root: Path) -> bool:
        """Validate that the path is a valid PNPM project.

        Args:
            root: Project root path

        Returns:
            True if valid, False otherwise
        """
        return (root / "package.json").exists()
