"""Implementation of init file patcher for generated directories."""

import os
from pathlib import Path


class InitFilePatcher:
    """Patcher for adding __init__.py files to generated code directories.

    This class implements the CodePatcher protocol.
    It ensures that all directories in the output directory structure
    have an __init__.py file, making them proper Python packages.
    """

    def __init__(self, code_dir: str) -> None:
        """Initialize the init file patcher.

        Args:
            code_dir: Directory with generated code
        """
        self.code_dir = Path(code_dir)
        # Get the root project directory (parent of the output directory)
        self.root_dir = self.code_dir.parent

    def patch(self) -> None:
        """Apply all patches.

        This method adds __init__.py files to all directories in the output
        directory structure to ensure proper package structure.
        """
        self._add_init_files()

    def _add_init_files(self) -> None:
        """Add __init__.py files to all directories in the output structure."""
        # Get all directories in the output structure
        all_dirs = set()
        
        # Include the output directory itself
        all_dirs.add(self.code_dir)
        
        # First, collect all directories
        for root, dirs, _ in os.walk(self.code_dir):
            root_path = Path(root)
            
            # Add current directory
            all_dirs.add(root_path)
            
            # Add all subdirectories
            for dir_name in dirs:
                dir_path = root_path / dir_name
                all_dirs.add(dir_path)
        
        # Add __init__.py to each directory if it doesn't exist
        for directory in all_dirs:
            # Skip the root project directory
            if directory == self.root_dir:
                continue
                
            init_file = directory / "__init__.py"
            if not init_file.exists():
                # Create an empty __init__.py file
                with open(init_file, "w") as f:
                    f.write("# Generated by PBReflect\n")
