"""Utility functions for file operations and text processing."""

import asyncio
import aiofiles
from pathlib import Path
from typing import Optional, Tuple

from rich.console import Console

console = Console()


async def read_text_file(file_path: Path) -> str:
    """
    Read text content from a file asynchronously.
    
    Args:
        file_path: Path to the text file
        
    Returns:
        File content as string
        
    Raises:
        FileNotFoundError: If file doesn't exist
        UnicodeDecodeError: If file can't be decoded as UTF-8
    """
    if not file_path.exists():
        raise FileNotFoundError(f"File not found: {file_path}")
    
    try:
        async with aiofiles.open(file_path, 'r', encoding='utf-8') as f:
            content = await f.read()
        return content
    except UnicodeDecodeError as e:
        raise UnicodeDecodeError(f"Failed to decode {file_path} as UTF-8: {e}")


async def write_text_file(file_path: Path, content: str) -> None:
    """
    Write text content to a file asynchronously.
    
    Args:
        file_path: Path to write to
        content: Text content to write
    """
    async with aiofiles.open(file_path, 'w', encoding='utf-8') as f:
        await f.write(content)


def validate_file_path(file_path: Path) -> bool:
    """
    Validate if a file path is suitable for text processing.
    
    Args:
        file_path: Path to validate
        
    Returns:
        True if valid, False otherwise
    """
    if not file_path.exists():
        console.print(f"[red]Error: File does not exist: {file_path}[/red]")
        return False
    
    if not file_path.is_file():
        console.print(f"[red]Error: Path is not a file: {file_path}[/red]")
        return False
    
    # Check file size (warn if very large)
    file_size = file_path.stat().st_size
    if file_size > 100 * 1024 * 1024:  # 100MB
        console.print(f"[yellow]Warning: Large file detected ({file_size / 1024 / 1024:.1f}MB)[/yellow]")
    
    return True


def sanitize_text(text: str) -> str:
    """
    Sanitize text for processing by removing problematic characters.
    
    Args:
        text: Raw text input
        
    Returns:
        Sanitized text
    """
    # Remove null bytes and other control characters except newlines and tabs
    import re
    text = re.sub(r'[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]', '', text)
    
    # Normalize whitespace (but preserve paragraph breaks)
    text = '\n\n'.join(
        paragraph.strip() 
        for paragraph in text.split('\n\n') 
        if paragraph.strip()
    )
    
    return text


def estimate_processing_time(text_a: str, text_b: str) -> float:
    """
    Estimate processing time based on text size.
    
    Args:
        text_a: First text
        text_b: Second text
        
    Returns:
        Estimated processing time in seconds
    """
    # Rough estimation: 1 second per 1000 characters
    total_chars = len(text_a) + len(text_b)
    return max(1.0, total_chars / 1000.0)


def format_file_size(size_bytes: int) -> str:
    """
    Format file size in human-readable format.
    
    Args:
        size_bytes: Size in bytes
        
    Returns:
        Formatted size string
    """
    for unit in ['B', 'KB', 'MB', 'GB']:
        if size_bytes < 1024.0:
            return f"{size_bytes:.1f} {unit}"
        size_bytes /= 1024.0
    return f"{size_bytes:.1f} TB" 