"""Input validation utilities."""

import os
import re
from pathlib import Path
from typing import Union

from kamimind_storage.exceptions import ValidationError


def validate_session_id(session_id: str) -> None:
    """Validate a session ID format.

    Args:
        session_id: The session ID to validate.

    Raises:
        ValidationError: If the session ID is invalid.
    """
    if not session_id:
        raise ValidationError("Session ID cannot be empty", field="session_id")

    if not isinstance(session_id, str):
        raise ValidationError("Session ID must be a string", field="session_id")

    # UUID format validation (basic)
    uuid_pattern = re.compile(
        r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
        re.IGNORECASE,
    )
    if not uuid_pattern.match(session_id):
        raise ValidationError("Session ID must be a valid UUID", field="session_id")


def validate_file_path(file_path: Union[str, Path]) -> Path:
    """Validate and normalize a file path.

    Args:
        file_path: The file path to validate.

    Returns:
        Normalized Path object.

    Raises:
        ValidationError: If the file path is invalid or file doesn't exist.
    """
    if not file_path:
        raise ValidationError("File path cannot be empty", field="file_path")

    path = Path(file_path)

    if not path.exists():
        raise ValidationError(f"File not found: {path}", field="file_path")

    if not path.is_file():
        raise ValidationError(f"Path is not a file: {path}", field="file_path")

    if not os.access(path, os.R_OK):
        raise ValidationError(f"File is not readable: {path}", field="file_path")

    return path


def validate_shortcut(shortcut: str) -> None:
    """Validate a public URL shortcut.

    Args:
        shortcut: The shortcut to validate.

    Raises:
        ValidationError: If the shortcut is invalid.
    """
    if not shortcut:
        raise ValidationError("Shortcut cannot be empty", field="shortcut")

    if not isinstance(shortcut, str):
        raise ValidationError("Shortcut must be a string", field="shortcut")

    # Shortcut should be alphanumeric
    if not re.match(r"^[a-zA-Z0-9]+$", shortcut):
        raise ValidationError("Shortcut must be alphanumeric", field="shortcut")
