"""Validation utilities for pypack."""

import re
from pathlib import Path
from typing import Optional


def validate_directory_path(path: str) -> Optional[Path]:
    """Validate and resolve directory path.

    Args:
        path: Directory path to validate

    Returns
    -------
        Resolved Path object if valid, None otherwise
    """
    try:
        path_obj = Path(path).resolve()
        if not path_obj.exists():
            return None
        if not path_obj.is_dir():
            return None
        return path_obj
    except Exception:
        return None


def validate_file_path(path: str) -> Optional[Path]:
    """Validate and resolve file path.

    Args:
        path: File path to validate

    Returns
    -------
        Resolved Path object if valid, None otherwise
    """
    try:
        path_obj = Path(path).resolve()
        if not path_obj.exists():
            return None
        if not path_obj.is_file():
            return None
        return path_obj
    except Exception:
        return None


def is_safe_filename(filename: str) -> bool:
    """Check if filename is safe (no path traversal).

    Args:
        filename: Filename to check

    Returns
    -------
        True if filename is safe, False otherwise
    """
    dangerous_patterns = ["..", "../", "..\\", "/", "\\"]
    return not any(pattern in filename for pattern in dangerous_patterns)


def sanitize_filename(filename: str) -> str:
    """Sanitize filename by removing dangerous characters.

    Args:
        filename: Filename to sanitize

    Returns
    -------
        Sanitized filename
    """
    # Remove dangerous characters and replace with underscore
    safe_chars = re.compile(r"[^a-zA-Z0-9._-]")
    return safe_chars.sub("_", filename)
