"""
Utilidades comunes para tai-storage.
"""
import re
from datetime import datetime
from typing import Optional


def normalize_path(path: str) -> str:
    """
    Normaliza una ruta eliminando barras redundantes y espacios.
    
    Args:
        path: Ruta a normalizar
        
    Returns:
        Ruta normalizada
        
    Examples:
        >>> normalize_path('//folder//subfolder/')
        'folder/subfolder'
        >>> normalize_path('  /folder/file.txt  ')
        'folder/file.txt'
    """
    # Eliminar espacios
    path = path.strip()
    
    # Reemplazar múltiples barras por una sola
    path = re.sub(r'/+', '/', path)
    
    # Eliminar barra inicial y final
    path = path.strip('/')
    
    return path


def join_paths(*paths: str) -> str:
    """
    Une múltiples segmentos de ruta de forma segura.
    
    Args:
        *paths: Segmentos de ruta a unir
        
    Returns:
        Ruta unida y normalizada
        
    Examples:
        >>> join_paths('folder', 'subfolder', 'file.txt')
        'folder/subfolder/file.txt'
        >>> join_paths('/folder/', '/subfolder/', 'file.txt')
        'folder/subfolder/file.txt'
    """
    # Unir con / y normalizar
    joined = '/'.join(str(p) for p in paths if p)
    return normalize_path(joined)


def parse_datetime(dt_str: str, format: Optional[str] = None) -> datetime:
    """
    Parsea una cadena a datetime.
    
    Args:
        dt_str: String con fecha/hora
        format: Formato strptime. Si None, intenta formatos comunes
        
    Returns:
        Objeto datetime
        
    Examples:
        >>> parse_datetime('2024-01-15 14:30:00')
        datetime(2024, 1, 15, 14, 30, 0)
        >>> parse_datetime('15/01/2024', '%d/%m/%Y')
        datetime(2024, 1, 15, 0, 0)
    """
    if format:
        return datetime.strptime(dt_str, format)
    
    # Intentar formatos comunes
    common_formats = [
        '%Y-%m-%d %H:%M:%S',
        '%Y-%m-%d %H:%M:%S.%f',
        '%Y-%m-%d',
        '%d/%m/%Y %H:%M:%S',
        '%d/%m/%Y',
        '%Y%m%d',
        '%Y%m%d%H%M%S',
    ]
    
    for fmt in common_formats:
        try:
            return datetime.strptime(dt_str, fmt)
        except ValueError:
            continue
    
    raise ValueError(f"Unable to parse datetime string: {dt_str}")


def format_bytes(size_bytes: int) -> str:
    """
    Formatea tamaño en bytes a formato legible.
    
    Args:
        size_bytes: Tamaño en bytes
        
    Returns:
        String formateado (ej: '1.5 MB', '3.2 GB')
        
    Examples:
        >>> format_bytes(1024)
        '1.0 KB'
        >>> format_bytes(1548576)
        '1.5 MB'
    """
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if size_bytes < 1024.0:
            return f"{size_bytes:.1f} {unit}"
        size_bytes /= 1024.0
    return f"{size_bytes:.1f} PB"


def match_pattern(text: str, pattern: str, case_sensitive: bool = False) -> bool:
    """
    Verifica si un texto coincide con un patrón regex.
    
    Args:
        text: Texto a verificar
        pattern: Patrón regex
        case_sensitive: Si True, distingue mayúsculas/minúsculas
        
    Returns:
        True si coincide, False en caso contrario
        
    Examples:
        >>> match_pattern('archivo.csv', r'.*\.csv$')
        True
        >>> match_pattern('ARCHIVO.CSV', r'.*\.csv$', case_sensitive=False)
        True
    """
    flags = 0 if case_sensitive else re.IGNORECASE
    return bool(re.match(pattern, text, flags))
