"""File operations utility - Cross Platform"""

import os
import shutil
import time
import platform

class FileUtils:
    """Handles file operations with proper permissions"""
    
    @staticmethod
    def ensure_directory(path, mode=0o777):
        """Create directory with proper permissions (platform-aware)"""
        try:
            os.makedirs(path, exist_ok=True)
            
            # Set permissions only on Unix-like systems
            if platform.system() != 'Windows':
                os.chmod(path, mode)
        except Exception as e:
            print(f"Warning: Could not create directory {path}: {e}")
    
    @staticmethod
    def copy_file_with_permissions(src, dst, mode=0o777):
        """Copy file with specific permissions (platform-aware)"""
        # Ensure destination directory exists
        FileUtils.ensure_directory(os.path.dirname(dst))
        
        # Copy file
        shutil.copy2(src, dst)
        
        # Set permissions only on Unix-like systems
        if platform.system() != 'Windows':
            try:
                os.chmod(dst, mode)
                os.chmod(os.path.dirname(dst), mode)
            except:
                pass
        
        # Sync only on Linux/Unix
        if platform.system() != 'Windows':
            os.sync()
        
        time.sleep(0.1)
    
    @staticmethod
    def is_file_ready(file_path, timeout=5):
        """Check if file is fully written and ready"""
        start_time = time.time()
        last_size = -1
        
        while time.time() - start_time < timeout:
            if not os.path.exists(file_path):
                return False
            
            current_size = os.path.getsize(file_path)
            if current_size == last_size and current_size > 0:
                return True
            
            last_size = current_size
            time.sleep(0.5)
        
        return last_size > 0
    
    @staticmethod
    def normalize_path(path):
        """Normalize path for current platform"""
        return os.path.normpath(path)