"""CLI utility functions for the Trax platform."""

import re
from typing import Dict, Any
from rich.console import Console

console = Console()


def is_valid_youtube_url(url: str) -> bool:
    """Validate YouTube URL format."""
    youtube_patterns = [
        r'https?://(?:www\.)?youtube\.com/watch\?v=[\w-]+',
        r'https?://(?:www\.)?youtu\.be/[\w-]+',
        r'https?://(?:www\.)?youtube\.com/embed/[\w-]+'
    ]
    return any(re.match(pattern, url) for pattern in youtube_patterns)


def display_text_metadata(metadata: Dict[str, Any]) -> None:
    """Display metadata in text format."""
    console.print(f"[bold cyan]Title:[/bold cyan] {metadata.get('title', 'N/A')}")
    console.print(f"[bold blue]Channel:[/bold blue] {metadata.get('channel', 'N/A')}")
    console.print(f"[bold yellow]Duration:[/bold yellow] {metadata.get('duration_seconds', 0)} seconds")
    console.print(f"[bold green]Description:[/bold green] {metadata.get('description', 'N/A')[:200]}...")


def format_duration(seconds: int) -> str:
    """Format duration in seconds to MM:SS format."""
    minutes = seconds // 60
    remaining_seconds = seconds % 60
    return f"{minutes}:{remaining_seconds:02d}"


def get_audio_extensions() -> set:
    """Get supported audio file extensions."""
    return {'.mp3', '.wav', '.m4a', '.flac', '.ogg', '.aac', '.wma'}


def get_video_extensions() -> set:
    """Get supported video file extensions."""
    return {'.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv'}


def get_media_extensions() -> set:
    """Get all supported media file extensions."""
    return get_audio_extensions() | get_video_extensions()


def validate_file_path(file_path: str) -> bool:
    """Validate that a file path exists and is a file."""
    from pathlib import Path
    path = Path(file_path)
    return path.exists() and path.is_file()


def validate_directory_path(dir_path: str) -> bool:
    """Validate that a directory path exists and is a directory."""
    from pathlib import Path
    path = Path(dir_path)
    return path.exists() and path.is_dir()


def format_file_size(size_bytes: int) -> str:
    """Format file size in bytes to human readable format."""
    if size_bytes == 0:
        return "0B"
    
    size_names = ["B", "KB", "MB", "GB", "TB"]
    i = 0
    while size_bytes >= 1024 and i < len(size_names) - 1:
        size_bytes /= 1024.0
        i += 1
    
    return f"{size_bytes:.1f}{size_names[i]}"


def format_percentage(value: float, total: float) -> str:
    """Format a percentage value."""
    if total == 0:
        return "0.0%"
    return f"{(value / total) * 100:.1f}%"
