"""File system operations for config upload/download."""

from pathlib import Path
from typing import List, Tuple


class ConfigFileHandler:
    """Handles all local file system operations.

    Responsible for reading, writing, and filtering config files.
    Single responsibility: local file system operations only.
    """

    ALLOWED_EXTENSIONS = {".yaml", ".yml", ".md"}

    def read_files(self, local_path: Path) -> List[Tuple[Path, bytes]]:
        """Read all allowed config files from local path.

        Args:
            local_path: Directory path to read from

        Returns:
            List of (file_path, content) tuples for allowed files

        Raises:
            FileNotFoundError: If local_path doesn't exist
            PermissionError: If files can't be read
        """
        if not local_path.exists():
            raise FileNotFoundError(f"Path does not exist: {local_path}")

        if not local_path.is_dir():
            raise ValueError(f"Path is not a directory: {local_path}")

        files = []
        for file_path in local_path.rglob("*"):
            if file_path.is_file() and file_path.suffix in self.ALLOWED_EXTENSIONS:
                content = file_path.read_bytes()
                files.append((file_path, content))

        return files

    def write_file(self, output_path: Path, content: bytes) -> None:
        """Write file to local file system.

        Args:
            output_path: Destination file path
            content: File content as bytes

        Raises:
            PermissionError: If file can't be written
        """
        output_path.parent.mkdir(parents=True, exist_ok=True)
        output_path.write_bytes(content)

    def create_directory(self, dir_path: Path) -> None:
        """Create directory if it doesn't exist.

        Args:
            dir_path: Directory path to create
        """
        dir_path.mkdir(parents=True, exist_ok=True)

    def file_exists(self, path: Path) -> bool:
        """Check if file exists.

        Args:
            path: File path to check

        Returns:
            True if file exists, False otherwise
        """
        return path.exists()
