"""Enhanced CLI interface with progress reporting and performance monitoring."""

import asyncio
import json
import os
import sys
import concurrent.futures
from pathlib import Path
from typing import List, Optional, Callable, Dict, Any
from datetime import datetime, timezone
import time

import click
import psutil
from rich.console import Console
from rich.progress import Progress, TextColumn, BarColumn, TaskProgressColumn, TimeRemainingColumn, SpinnerColumn
from rich.panel import Panel
from rich.table import Table
from rich.live import Live
from rich.layout import Layout

from .utils import console as base_console
from ..services.model_manager import ModelManager
from ..services.transcription_service import create_transcription_service, TranscriptionConfig
from ..services.factories import create_export_service

# Optional imports for advanced features
try:
    from ..services.diarization_service import create_diarization_service
    DIARIZATION_AVAILABLE = True
except ImportError:
    DIARIZATION_AVAILABLE = False
    create_diarization_service = None

try:
    from ..services.domain_adaptation_manager import DomainAdaptationManager
    DOMAIN_ADAPTATION_AVAILABLE = True
except ImportError:
    DOMAIN_ADAPTATION_AVAILABLE = False
    DomainAdaptationManager = None


class GranularProgressTracker:
    """Granular progress tracker for detailed transcription progress reporting."""
    
    def __init__(self, console: Console, total_steps: int = 100):
        """Initialize the progress tracker."""
        self.console = console
        self.total_steps = total_steps
        self.current_step = 0
        self.stage = "initializing"
        self.sub_stage = ""
        self.start_time = None
        self.stage_start_time = None
        
        # Progress bar components
        self.progress = Progress(
            TextColumn("[bold blue]{task.description}"),
            BarColumn(),
            TaskProgressColumn(),
            TimeRemainingColumn(),
            SpinnerColumn(),
            console=console
        )
        
        # Main progress task
        self.main_task = None
        self.stage_task = None
        
    def start_tracking(self, description: str = "Processing"):
        """Start progress tracking."""
        self.start_time = datetime.now()
        self.stage_start_time = self.start_time
        
        with self.progress:
            self.main_task = self.progress.add_task(
                f"[green]{description}[/green]", 
                total=self.total_steps
            )
            self.stage_task = self.progress.add_task(
                f"[cyan]Stage: {self.stage}[/cyan]", 
                total=100
            )
    
    def update_stage(self, stage: str, sub_stage: str = "", progress: int = 0):
        """Update the current processing stage."""
        self.stage = stage
        self.sub_stage = sub_stage
        
        if self.stage_task:
            self.progress.update(
                self.stage_task, 
                description=f"[cyan]Stage: {stage}[/cyan]"
                + (f" - {sub_stage}" if sub_stage else ""),
                completed=progress
            )
    
    def update_progress(self, step: int, description: str = None):
        """Update the main progress."""
        self.current_step = min(step, self.total_steps)
        
        if self.main_task:
            if description:
                self.progress.update(
                    self.main_task, 
                    description=f"[green]{description}[/green]",
                    completed=self.current_step
                )
            else:
                self.progress.update(self.main_task, completed=self.current_step)
    
    def update_stage_progress(self, progress: int, description: str = None):
        """Update the current stage progress."""
        if self.stage_task:
            if description:
                self.progress.update(
                    self.stage_task, 
                    description=f"[cyan]Stage: {stage}[/cyan] - {description}",
                    completed=progress
                )
            else:
                self.progress.update(self.stage_task, completed=progress)
    
    def add_info(self, message: str):
        """Add informational message to progress display."""
        self.console.print(f"[dim]ℹ️  {message}[/dim]")
    
    def add_warning(self, message: str):
        """Add warning message to progress display."""
        self.console.print(f"[yellow]⚠️  {message}[/yellow]")
    
    def add_error(self, message: str):
        """Add error message to progress display."""
        self.console.print(f"[red]❌ {message}[/red]")
    
    def add_success(self, message: str):
        """Add success message to progress display."""
        self.console.print(f"[green]✅ {message}[/green]")
    
    def complete(self, final_message: str = "Processing completed"):
        """Complete the progress tracking."""
        if self.main_task:
            self.progress.update(self.main_task, completed=self.total_steps)
        
        if self.stage_task:
            self.progress.update(self.stage_task, completed=100)
        
        self.add_success(final_message)
        
        if self.start_time:
            total_time = (datetime.now() - self.start_time).total_seconds()
            self.console.print(f"[dim]Total time: {total_time:.2f}s[/dim]")


class MultiPassProgressTracker(GranularProgressTracker):
    """Specialized progress tracker for multi-pass transcription pipelines."""
    
    def __init__(self, console: Console, total_steps: int = 100):
        """Initialize the multi-pass progress tracker."""
        super().__init__(console, total_steps)
        self.pass_number = 0
        self.total_passes = 0
        self.pass_tasks = {}
        self.current_pass_task = None
        
    def start_multi_pass_tracking(self, total_passes: int = 3, description: str = "Multi-Pass Transcription"):
        """Start multi-pass progress tracking."""
        self.total_passes = total_passes
        self.start_tracking(description)
        
        # Add pass-specific progress tracking
        with self.progress:
            self.current_pass_task = self.progress.add_task(
                f"[magenta]Pass 1/{total_passes}[/magenta]", 
                total=100
            )
    
    def start_pass(self, pass_number: int, pass_name: str, description: str = None):
        """Start tracking a specific pass."""
        self.pass_number = pass_number
        
        if self.current_pass_task:
            self.progress.update(
                self.current_pass_task,
                description=f"[magenta]Pass {pass_number}/{self.total_passes}: {pass_name}[/magenta]",
                completed=0
            )
        
        if description:
            self.add_info(f"Starting {pass_name} (Pass {pass_number}/{self.total_passes})")
    
    def update_pass_progress(self, progress: int, description: str = None):
        """Update progress for the current pass."""
        if self.current_pass_task:
            if description:
                self.progress.update(
                    self.current_pass_task,
                    description=f"[magenta]Pass {self.pass_number}/{self.total_passes}: {description}[/magenta]",
                    completed=progress
                )
            else:
                self.progress.update(self.current_pass_task, completed=progress)
    
    def complete_pass(self, pass_name: str, results: dict = None):
        """Complete the current pass."""
        if self.current_pass_task:
            self.progress.update(self.current_pass_task, completed=100)
        
        self.add_success(f"Completed {pass_name} (Pass {self.pass_number}/{self.total_passes})")
        
        # Show pass-specific results if available
        if results:
            if 'segments' in results:
                segments = results['segments']
                if isinstance(segments, list):
                    self.add_info(f"Generated {len(segments)} segments")
                else:
                    self.add_info(f"Generated {segments} segments")
            if 'confidence' in results:
                self.add_info(f"Average confidence: {results['confidence']:.2f}")
            if 'processing_time' in results:
                self.add_info(f"Pass processing time: {results['processing_time']:.2f}s")
    
    def show_pipeline_summary(self, final_results: dict):
        """Show a summary of the multi-pass pipeline results."""
        self.console.print("\n" + "="*60)
        self.console.print("[bold blue]Multi-Pass Pipeline Summary[/bold blue]")
        self.console.print("="*60)
        
        if 'segments' in final_results:
            segments = final_results['segments']
            if isinstance(segments, list):
                self.console.print(f"[cyan]Total Segments:[/cyan] {len(segments)}")
            else:
                self.console.print(f"[cyan]Total Segments:[/cyan] {segments}")
        
        if 'confidence' in final_results:
            self.console.print(f"[cyan]Overall Confidence:[/cyan] {final_results['confidence']:.2f}")
        
        if 'processing_time' in final_results:
            self.console.print(f"[cyan]Total Processing Time:[/cyan] {final_results['processing_time']:.2f}s")
        
        if 'pipeline_stages' in final_results:
            self.console.print(f"[cyan]Pipeline Stages:[/cyan] {', '.join(final_results['pipeline_stages'])}")
        
        self.console.print("="*60)
    
    def track_refinement_pass(self, low_confidence_segments: int, total_segments: int):
        """Track progress during refinement pass."""
        self.add_info(f"Refinement pass: {low_confidence_segments}/{total_segments} segments need improvement")
        
        if low_confidence_segments > 0:
            self.add_warning(f"Processing {low_confidence_segments} low-confidence segments")
        else:
            self.add_info("All segments meet confidence threshold - no refinement needed")
    
    def track_enhancement_pass(self, domain: str = None):
        """Track progress during enhancement pass."""
        if domain:
            self.add_info(f"Applying {domain} domain enhancement")
        else:
            self.add_info("Applying general domain enhancement")
    
    def track_diarization_progress(self, current_speaker: int, total_speakers: int):
        """Track speaker diarization progress."""
        if self.current_pass_task:
            self.progress.update(
                self.current_pass_task,
                description=f"[magenta]Pass {self.pass_number}/{self.total_passes}: Speaker {current_speaker}/{total_speakers}[/magenta]",
                completed=int((current_speaker / total_speakers) * 100)
            )


class ModelLoadingProgressTracker(GranularProgressTracker):
    """Specialized progress tracker for model loading and initialization."""
    
    def __init__(self, console: Console, total_steps: int = 100):
        """Initialize the model loading progress tracker."""
        super().__init__(console, total_steps)
        self.model_name = ""
        self.model_size = 0
        self.device = "cpu"
        self.loading_stage = "initializing"
        
    def start_model_loading(self, model_name: str, model_size: int = 0, device: str = "cpu"):
        """Start tracking model loading progress."""
        self.model_name = model_name
        self.model_size = model_size
        self.device = device
        
        description = f"Loading {model_name}"
        if model_size > 0:
            description += f" ({model_size}MB)"
        description += f" on {device.upper()}"
        
        self.start_tracking(description)
        
        # Add model-specific progress tracking
        with self.progress:
            self.model_task = self.progress.add_task(
                f"[yellow]Model: {model_name}[/yellow]", 
                total=100
            )
    
    def update_loading_stage(self, stage: str, progress: int = 0, description: str = None):
        """Update the current loading stage."""
        self.loading_stage = stage
        
        if self.stage_task:
            stage_desc = f"[yellow]Stage: {stage}[/yellow]"
            if description:
                stage_desc += f" - {description}"
            self.progress.update(self.stage_task, description=stage_desc, completed=progress)
    
    def track_download_progress(self, downloaded_bytes: int, total_bytes: int):
        """Track model download progress."""
        if self.model_task:
            progress = int((downloaded_bytes / total_bytes) * 100)
            downloaded_mb = downloaded_bytes / (1024 * 1024)
            total_mb = total_bytes / (1024 * 1024)
            
            self.progress.update(
                self.model_task,
                description=f"[yellow]Downloading: {downloaded_mb:.1f}MB / {total_mb:.1f}MB[/yellow]",
                completed=progress
            )
    
    def track_extraction_progress(self, progress: int, description: str = None):
        """Track model extraction progress."""
        if self.model_task:
            if description:
                self.progress.update(
                    self.model_task,
                    description=f"[yellow]Extracting: {description}[/yellow]",
                    completed=progress
                )
            else:
                self.progress.update(self.model_task, completed=progress)
    
    def track_loading_progress(self, progress: int, description: str = None):
        """Track model loading into memory progress."""
        if self.model_task:
            if description:
                self.progress.update(
                    self.model_task,
                    description=f"[yellow]Loading: {description}[/yellow]",
                    completed=progress
                )
            else:
                self.progress.update(self.model_task, completed=progress)
    
    def track_optimization_progress(self, progress: int, description: str = None):
        """Track model optimization progress."""
        if self.model_task:
            if description:
                self.progress.update(
                    self.model_task,
                    description=f"[yellow]Optimizing: {description}[/yellow]",
                    completed=progress
                )
            else:
                self.progress.update(self.model_task, completed=progress)
    
    def show_model_info(self, model_info: dict):
        """Show detailed model information after loading."""
        self.console.print("\n" + "="*50)
        self.console.print("[bold blue]Model Information[/bold blue]")
        self.console.print("="*50)
        
        if 'name' in model_info:
            self.console.print(f"[cyan]Model Name:[/cyan] {model_info['name']}")
        
        if 'size_mb' in model_info:
            self.console.print(f"[cyan]Model Size:[/cyan] {model_info['size_mb']:.1f}MB")
        
        if 'device' in model_info:
            self.console.print(f"[cyan]Device:[/cyan] {model_info['device'].upper()}")
        
        if 'load_time' in model_info:
            self.console.print(f"[cyan]Load Time:[/cyan] {model_info['load_time']:.2f}s")
        
        if 'memory_usage' in model_info:
            self.console.print(f"[cyan]Memory Usage:[/cyan] {model_info['memory_usage']:.1f}MB")
        
        if 'optimization' in model_info:
            self.console.print(f"[cyan]Optimization:[/cyan] {model_info['optimization']}")
        
        self.console.print("="*50)
    
    def complete_model_loading(self, model_info: dict = None):
        """Complete model loading progress tracking."""
        if self.model_task:
            self.progress.update(self.model_task, completed=100)
        
        if self.stage_task:
            self.progress.update(self.stage_task, completed=100)
        
        self.add_success(f"Model {self.model_name} loaded successfully on {self.device.upper()}")
        
        if model_info:
            self.show_model_info(model_info)
        
        if self.start_time:
            total_time = (datetime.now() - self.start_time).total_seconds()
            self.console.print(f"[dim]Total loading time: {total_time:.2f}s[/dim]")


class EnhancedCLI:
    """Enhanced CLI interface with progress reporting and performance monitoring."""
    
    def __init__(self):
        """Initialize the enhanced CLI."""
        self.model_manager = ModelManager()
        self.console = Console()
        # Don't initialize export service here to avoid issues
    
    def _get_error_guidance(self, error_type: str, error_message: str) -> str:
        """Get specific guidance based on error type."""
        if error_type == "FileNotFoundError":
            return "Check that the input file path is correct and the file exists."
        elif error_type == "PermissionError":
            return "Check file permissions. Try running with administrator privileges."
        elif "CUDA" in error_message or "GPU" in error_message:
            return "GPU-related error. Try using --device cpu to process with CPU instead."
        elif "memory" in error_message.lower():
            return "Memory error. Try using a smaller model with --model small or reduce concurrency."
        else:
            return "Check input parameters and try again. If the issue persists, please report it."
    
    def handle_error(self, error: Exception, context: Optional[str] = None) -> None:
        """Handle errors with user guidance."""
        error_type = type(error).__name__
        
        error_panel = Panel(
            f"[bold red]Error:[/bold red] {str(error)}\n\n"
            f"[yellow]Type:[/yellow] {error_type}\n"
            f"[yellow]Context:[/yellow] {context or 'Unknown'}\n\n"
            f"[bold cyan]Suggested Action:[/bold cyan]\n{self._get_error_guidance(error_type, str(error))}",
            title="Error Occurred",
            border_style="red"
        )
        
        self.console.print(error_panel)
    
    def _get_performance_stats(self) -> Dict[str, Any]:
        """Get system performance metrics."""
        cpu_percent = psutil.cpu_percent(interval=0.5)
        memory = psutil.virtual_memory()
        
        stats = {
            'cpu_percent': cpu_percent,
            'memory_used_gb': memory.used / (1024 ** 3),
            'memory_total_gb': memory.total / (1024 ** 3),
            'memory_percent': memory.percent,
            'cpu_temperature': None
        }
        
        # Try to get CPU temperature if available
        try:
            temps = psutil.sensors_temperatures()
            if temps and 'coretemp' in temps:
                stats['cpu_temperature'] = max(temp.current for temp in temps['coretemp'])
        except (AttributeError, KeyError):
            pass
        
        return stats
    
    def display_performance_stats(self) -> None:
        """Display system performance statistics."""
        stats = self._get_performance_stats()
        
        table = Table(title="System Performance")
        table.add_column("Metric", style="cyan")
        table.add_column("Value", style="green")
        
        table.add_row("CPU Usage", f"{stats['cpu_percent']}%")
        table.add_row("Memory Usage", 
                     f"{stats['memory_used_gb']:.2f}GB / {stats['memory_total_gb']:.2f}GB ({stats['memory_percent']}%)")
        
        if stats['cpu_temperature']:
            table.add_row("CPU Temperature", f"{stats['cpu_temperature']}°C")
        
        self.console.print(Panel(table))

    def process_transcription(
        self,
        input_path: str,
        output_dir: Optional[str] = None,
        format: str = "txt",
        diarize: bool = False,
        domain: Optional[str] = None,
        auto_domain: bool = False,
        batch_size: int = 1,
        show_progress: bool = True,
        min_accuracy: float = 80.0,
        confidence_threshold: float = 0.85
    ) -> None:
        """Process transcription for a file or directory with enhanced progress reporting."""
        try:
            import asyncio
            
            # Determine if input is a file or directory
            if os.path.isfile(input_path):
                files = [input_path]
            elif os.path.isdir(input_path):
                import glob
                files = glob.glob(os.path.join(input_path, "*.wav")) + \
                        glob.glob(os.path.join(input_path, "*.mp3")) + \
                        glob.glob(os.path.join(input_path, "*.m4a"))
            else:
                self.console.print(f"[bold red]Error:[/bold red] Input path {input_path} does not exist")
                return

            # Create output directory if it doesn't exist
            if output_dir and not os.path.exists(output_dir):
                os.makedirs(output_dir)

            # Process files with progress tracking
            self.console.print(Panel(f"Processing {len(files)} audio files"))

            if show_progress:
                with Progress(
                    TextColumn("[bold blue]{task.description}[/bold blue]"),
                    BarColumn(),
                    TaskProgressColumn(),
                    TimeRemainingColumn(),
                    console=self.console
                ) as progress:
                    # Create overall progress task
                    overall_task = progress.add_task(f"[cyan]Overall Progress", total=len(files))

                    for i, file_path in enumerate(files):
                        file_name = os.path.basename(file_path)
                        file_task = progress.add_task(f"Processing {file_name}", total=100)

                        # Process the file using multi-pass pipeline
                        result = self._process_single_file(
                            file_path, 
                            diarize, 
                            domain, 
                            auto_domain, 
                            min_accuracy, 
                            confidence_threshold,
                            progress,
                            file_task
                        )

                        # Save the result in the specified format
                        if result and output_dir:
                            output_path = os.path.join(output_dir, os.path.splitext(file_name)[0])
                            self._save_result(result, output_path, format)

                        # Update overall progress
                        progress.update(overall_task, advance=1)
                        progress.remove_task(file_task)

                    # Show summary after completion
                    self.console.print(Panel(f"[bold green]Completed processing {len(files)} files[/bold green]"))
            else:
                # Process without progress bar
                for file_path in files:
                    result = self._process_single_file(
                        file_path, 
                        diarize, 
                        domain, 
                        auto_domain, 
                        min_accuracy, 
                        confidence_threshold
                    )

                    if result and output_dir:
                        file_name = os.path.basename(file_path)
                        output_path = os.path.join(output_dir, os.path.splitext(file_name)[0])
                        self._save_result(result, output_path, format)

                self.console.print(Panel(f"[bold green]Completed processing {len(files)} files[/bold green]"))

        except Exception as e:
            self.handle_error(e, context="Transcription processing")

    def _process_single_file(
        self,
        file_path: str,
        diarize: bool = False,
        domain: Optional[str] = None,
        auto_domain: bool = False,
        min_accuracy: float = 80.0,
        confidence_threshold: float = 0.85,
        progress=None,
        task_id=None
    ):
        """Process a single audio file using the multi-pass pipeline."""
        try:
            from ..services.multi_pass_transcription import MultiPassTranscriptionPipeline
            from ..services.diarization_service import DiarizationManager
            from ..services.domain_adaptation_manager import DomainAdaptationManager

            # Initialize pipeline components
            diarization_manager = DiarizationManager() if diarize else None
            domain_adapter = DomainAdaptationManager(domain) if domain or auto_domain else None

            # Initialize transcription pipeline
            pipeline = MultiPassTranscriptionPipeline(
                domain_adapter=domain_adapter,
                auto_detect_domain=auto_domain
            )
            pipeline.confidence_threshold = confidence_threshold

            # Register progress callback if progress tracking is enabled
            if progress and task_id:
                def update_progress(stage, percentage):
                    progress.update(task_id, completed=percentage, description=f"[cyan]{os.path.basename(file_path)}[/cyan] - {stage}")

                # Register the progress callback with the pipeline
                pipeline.register_progress_callback(update_progress)

            # Process the file
            result_dict = pipeline.transcribe_with_parallel_processing(
                audio_path=file_path,
                speaker_diarization=diarize,
                domain=domain
            )

            # Convert to expected format for compatibility
            if isinstance(result_dict, dict) and "transcript" in result_dict:
                # Extract segments from transcript
                segments = result_dict["transcript"]
                # Create a result structure that matches what the save methods expect
                result = {
                    "segments": segments,
                    "confidence": result_dict.get("confidence_score", 0.9),
                    "processing_time": result_dict.get("processing_time", 0.0)
                }
                return result
            else:
                return result_dict

        except Exception as e:
            self.handle_error(e, context=f"Processing file {file_path}")
            return None

    def _save_result(self, result, output_path: str, format: str) -> None:
        """Save transcription result in the specified format."""
        try:
            if format == "txt":
                with open(f"{output_path}.txt", "w", encoding="utf-8") as f:
                    # Extract text content from result
                    if isinstance(result, dict) and "segments" in result:
                        text_content = " ".join([seg.get("text", "") for seg in result["segments"]])
                    else:
                        text_content = str(result)
                    f.write(text_content)
            elif format == "srt":
                with open(f"{output_path}.srt", "w", encoding="utf-8") as f:
                    self._write_srt_format(result, f)
            elif format == "vtt":
                with open(f"{output_path}.vtt", "w", encoding="utf-8") as f:
                    self._write_vtt_format(result, f)
            elif format == "json":
                with open(f"{output_path}.json", "w", encoding="utf-8") as f:
                    json.dump(result, f, indent=2, ensure_ascii=False, default=str)

        except Exception as e:
            self.handle_error(e, context=f"Saving result in {format} format")

    def _write_srt_format(self, result, file_handle) -> None:
        """Write result in SRT format."""
        if isinstance(result, dict) and "segments" in result:
            for i, segment in enumerate(result["segments"], 1):
                start_time = segment.get("start", 0)
                end_time = segment.get("end", 0)
                text = segment.get("text", "")
                
                # Convert seconds to SRT time format (HH:MM:SS,mmm)
                start_srt = self._seconds_to_srt_time(start_time)
                end_srt = self._seconds_to_srt_time(end_time)
                
                file_handle.write(f"{i}\n")
                file_handle.write(f"{start_srt} --> {end_srt}\n")
                file_handle.write(f"{text}\n\n")

    def _write_vtt_format(self, result, file_handle) -> None:
        """Write result in VTT format."""
        file_handle.write("WEBVTT\n\n")
        
        if isinstance(result, dict) and "segments" in result:
            for segment in result["segments"]:
                start_time = segment.get("start", 0)
                end_time = segment.get("end", 0)
                text = segment.get("text", "")
                
                # Convert seconds to VTT time format (HH:MM:SS.mmm)
                start_vtt = self._seconds_to_vtt_time(start_time)
                end_vtt = self._seconds_to_vtt_time(end_time)
                
                file_handle.write(f"{start_vtt} --> {end_vtt}\n")
                file_handle.write(f"{text}\n\n")

    def _seconds_to_srt_time(self, seconds: float) -> str:
        """Convert seconds to SRT time format (HH:MM:SS,mmm)."""
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        millisecs = int((seconds % 1) * 1000)
        return f"{hours:02d}:{minutes:02d}:{secs:02d},{millisecs:03d}"

    def _seconds_to_vtt_time(self, seconds: float) -> str:
        """Convert seconds to VTT time format (HH:MM:SS.mmm)."""
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        millisecs = int((seconds % 1) * 1000)
        return f"{hours:02d}:{minutes:02d}:{secs:02d}.{millisecs:03d}"


class EnhancedTranscribeCommand:
    """Enhanced transcribe command with progress reporting."""
    
    def __init__(self):
        """Initialize the transcribe command."""
        self.console = Console()
        # Don't initialize export service here to avoid issues
    
    def _create_progress_callback(self, task_id, total_duration: float) -> Callable:
        """Create a progress callback for transcription."""
        def callback(current_time: float, total_time: float) -> None:
            percent = min(100, int(current_time / total_time * 100))
            # Update the progress bar
            # Note: In a real implementation, this would need access to the progress object
            # For now, we'll just track the progress
            pass
        return callback
    
    def _get_audio_duration(self, file_path: str) -> float:
        """Get audio file duration for progress estimation."""
        try:
            import librosa
            duration = librosa.get_duration(path=file_path)
            return duration
        except ImportError:
            # Fallback: estimate based on file size
            file_size = os.path.getsize(file_path)
            # Rough estimate: 1MB ≈ 1 minute for typical audio
            return file_size / (1024 * 1024) * 60
    
    async def execute_transcription(
        self,
        input_path: str,
        output_dir: str,
        format_type: str = "json",
        model: str = "base",
        device: str = "cpu",
        domain: Optional[str] = None,
        diarize: bool = False,
        speakers: Optional[int] = None
    ) -> Optional[str]:
        """Execute transcription with enhanced progress reporting."""
        try:
            file_path = Path(input_path)
            if not file_path.exists():
                raise FileNotFoundError(f"Input file not found: {input_path}")
            
            # Check for optional features
            if diarize and not DIARIZATION_AVAILABLE:
                self.console.print("[yellow]Warning: Diarization not available. Install pyannote.audio for speaker diarization.[/yellow]")
                diarize = False
            
            if domain and not DOMAIN_ADAPTATION_AVAILABLE:
                self.console.print("[yellow]Warning: Domain adaptation not available. Install required dependencies.[/yellow]")
                domain = None
            
            # Initialize services
            transcription_service = create_transcription_service()
            await transcription_service.initialize()
            
            # Configure transcription
            config = TranscriptionConfig(
                model=model,
                chunk_size_seconds=600
            )
            
            # Get audio duration for progress estimation
            audio_duration = self._get_audio_duration(str(file_path))
            
            with Progress(
                TextColumn("[bold blue]{task.description}"),
                BarColumn(),
                TaskProgressColumn(),
                TimeRemainingColumn(),
            ) as progress:
                task = progress.add_task("Transcribing...", total=100)
                
                # Create progress callback
                progress_callback = self._create_progress_callback(task, audio_duration)
                
                # Transcribe file
                result = await transcription_service.transcribe_file(file_path, config)
                progress.update(task, completed=100)
                
                # Apply domain adaptation if specified and available
                if domain and DOMAIN_ADAPTATION_AVAILABLE:
                    domain_manager = DomainAdaptationManager()
                    result = await domain_manager.apply_domain_adaptation(result, domain)
                
                # Apply diarization if requested and available
                if diarize and DIARIZATION_AVAILABLE:
                    diarization_service = create_diarization_service()
                    result = await diarization_service.diarize_transcript(result, speakers)
                
                # Export result
                output_path = self._export_result(result, str(file_path), output_dir, format_type)
                
                return output_path
        
        except Exception as e:
            self.console.print(f"[red]Transcription failed: {str(e)}[/red]")
            return None
    
    def _export_result(self, result, input_file: str, output_dir: str, format_type: str) -> str:
        """Export transcription result in specified format."""
        base_name = Path(input_file).stem
        os.makedirs(output_dir, exist_ok=True)
        
        if format_type == "json":
            output_path = os.path.join(output_dir, f"{base_name}.json")
            with open(output_path, "w", encoding="utf-8") as f:
                json.dump(result.__dict__, f, indent=2, ensure_ascii=False, default=str)
        
        elif format_type == "txt":
            output_path = os.path.join(output_dir, f"{base_name}.txt")
            with open(output_path, "w", encoding="utf-8") as f:
                f.write(result.text_content or "")
        
        elif format_type == "srt":
            output_path = os.path.join(output_dir, f"{base_name}.srt")
            self._write_srt(result.segments or [], output_path)
        
        elif format_type == "vtt":
            output_path = os.path.join(output_dir, f"{base_name}.vtt")
            self._write_vtt(result.segments or [], output_path)
        
        return output_path
    
    def _write_srt(self, segments: List[Dict], output_path: str) -> None:
        """Write segments in SRT format."""
        with open(output_path, "w", encoding="utf-8") as f:
            for i, segment in enumerate(segments, 1):
                start_time = self._format_timestamp(segment.get("start", 0))
                end_time = self._format_timestamp(segment.get("end", 0))
                text = segment.get("text", "")
                
                f.write(f"{i}\n")
                f.write(f"{start_time} --> {end_time}\n")
                f.write(f"{text}\n\n")
    
    def _write_vtt(self, segments: List[Dict], output_path: str) -> None:
        """Write segments in VTT format."""
        with open(output_path, "w", encoding="utf-8") as f:
            f.write("WEBVTT\n\n")
            
            for segment in segments:
                start_time = self._format_timestamp(segment.get("start", 0), vtt=True)
                end_time = self._format_timestamp(segment.get("end", 0), vtt=True)
                text = segment.get("text", "")
                
                f.write(f"{start_time} --> {end_time}\n")
                f.write(f"{text}\n\n")
    
    def _format_timestamp(self, seconds: float, vtt: bool = False) -> str:
        """Format timestamp for SRT/VTT."""
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        millisecs = int((seconds % 1) * 1000)
        
        if vtt:
            return f"{hours:02d}:{minutes:02d}:{secs:02d}.{millisecs:03d}"
        else:
            return f"{hours:02d}:{minutes:02d}:{secs:02d},{millisecs:03d}"


class EnhancedBatchCommand:
    """Enhanced batch command with intelligent queuing and progress reporting."""
    
    def __init__(self):
        """Initialize the batch command."""
        self.console = Console()
    
    def _discover_files(self, input_path: str) -> List[Path]:
        """Discover media files in input path."""
        path = Path(input_path)
        media_extensions = {'.mp3', '.wav', '.m4a', '.flac', '.ogg', '.mp4', '.avi', '.mov'}
        
        if path.is_file():
            return [path] if path.suffix.lower() in media_extensions else []
        
        files = []
        for file_path in path.rglob('*'):
            if file_path.is_file() and file_path.suffix.lower() in media_extensions:
                files.append(file_path)
        
        return files
    
    def _sort_files_by_size(self, files: List[Path]) -> List[Path]:
        """Sort files by size for intelligent queuing."""
        return sorted(files, key=lambda f: f.stat().st_size if f.exists() else float('inf'))
    
    def _get_performance_stats(self) -> Dict[str, Any]:
        """Get system performance metrics."""
        cpu_percent = psutil.cpu_percent(interval=0.5)
        memory = psutil.virtual_memory()
        
        stats = {
            'cpu_percent': cpu_percent,
            'memory_used_gb': memory.used / (1024 ** 3),
            'memory_total_gb': memory.total / (1024 ** 3),
            'memory_percent': memory.percent,
            'cpu_temperature': None
        }
        
        # Try to get CPU temperature if available
        try:
            temps = psutil.sensors_temperatures()
            if temps and 'coretemp' in temps:
                stats['cpu_temperature'] = max(temp.current for temp in temps['coretemp'])
        except (AttributeError, KeyError):
            pass
        
        return stats
    
    async def _process_concurrently(
        self,
        files: List[str],
        concurrency: int,
        transcription_func: Callable,
        progress_callback: Callable
    ) -> List[Dict]:
        """Process files concurrently with progress tracking."""
        results = []
        
        with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as executor:
            futures = {executor.submit(transcription_func, file_path): file_path for file_path in files}
            
            for future in concurrent.futures.as_completed(futures):
                file_path = futures[future]
                try:
                    result = future.result()
                    results.append({"file": file_path, "status": "success", "result": result})
                    self.console.print(f"✅ Completed: {Path(file_path).name}")
                except Exception as e:
                    results.append({"file": file_path, "status": "error", "error": str(e)})
                    self.console.print(f"❌ Error processing {Path(file_path).name}: {str(e)}")
                
                progress_callback()
        
        return results


class SystemResourceMonitor:
    """Real-time system resource monitoring for transcription processing."""
    
    def __init__(self, console: Console, update_interval: float = 1.0):
        """Initialize the system resource monitor."""
        self.console = console
        self.update_interval = update_interval
        self.monitoring = False
        self.monitor_task = None
        self.start_time = None
        self.peak_cpu = 0.0
        self.peak_memory = 0.0
        self.peak_temperature = 0.0
        
    def start_monitoring(self, description: str = "System Resources"):
        """Start real-time system resource monitoring."""
        self.monitoring = True
        self.start_time = datetime.now()
        self.peak_cpu = 0.0
        self.peak_memory = 0.0
        self.peak_temperature = 0.0
        
        self.console.print(f"[bold green]🔍 Starting system resource monitoring: {description}[/bold green]")
        
        # Create monitoring display
        with Live(self._create_monitoring_display(), refresh_per_second=1, console=self.console) as live:
            while self.monitoring:
                live.update(self._create_monitoring_display())
                time.sleep(self.update_interval)
    
    def stop_monitoring(self):
        """Stop system resource monitoring."""
        self.monitoring = False
        if self.start_time:
            duration = (datetime.now() - self.start_time).total_seconds()
            self._show_monitoring_summary(duration)
    
    def _create_monitoring_display(self) -> Panel:
        """Create the real-time monitoring display."""
        # Get current system metrics
        cpu_percent = psutil.cpu_percent(interval=0.1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        
        # Update peak values
        self.peak_cpu = max(self.peak_cpu, cpu_percent)
        self.peak_memory = max(self.peak_memory, memory.percent)
        
        # Get CPU temperature if available
        try:
            temps = psutil.sensors_temperatures()
            if temps and 'coretemp' in temps:
                current_temp = max(temp.current for temp in temps['coretemp'])
                self.peak_temperature = max(self.peak_temperature, current_temp)
            else:
                current_temp = None
        except (AttributeError, KeyError):
            current_temp = None
        
        # Create monitoring table
        table = Table(title="🖥️  Real-Time System Resources", show_header=True, header_style="bold magenta")
        table.add_column("Metric", style="cyan", width=20)
        table.add_column("Current", style="green", width=15)
        table.add_column("Peak", style="yellow", width=15)
        table.add_column("Status", style="bold", width=15)
        
        # CPU row
        cpu_status = self._get_status_indicator(cpu_percent, 80, 95)
        table.add_row(
            "CPU Usage",
            f"{cpu_percent:.1f}%",
            f"{self.peak_cpu:.1f}%",
            cpu_status
        )
        
        # Memory row
        memory_status = self._get_status_indicator(memory.percent, 80, 95)
        table.add_row(
            "Memory Usage",
            f"{memory.percent:.1f}%",
            f"{self.peak_memory:.1f}%",
            memory_status
        )
        
        # Memory details
        memory_used_gb = memory.used / (1024 ** 3)
        memory_total_gb = memory.total / (1024 ** 3)
        table.add_row(
            "Memory (GB)",
            f"{memory_used_gb:.1f}/{memory_total_gb:.1f}",
            f"{memory_used_gb:.1f}",
            memory_status
        )
        
        # Disk usage
        disk_status = self._get_status_indicator(disk.percent, 80, 95)
        table.add_row(
            "Disk Usage",
            f"{disk.percent:.1f}%",
            f"{disk.percent:.1f}%",
            disk_status
        )
        
        # CPU Temperature
        if current_temp is not None:
            temp_status = self._get_status_indicator(current_temp, 70, 85)
            table.add_row(
                "CPU Temp",
                f"{current_temp:.1f}°C",
                f"{self.peak_temperature:.1f}°C",
                temp_status
            )
        
        # Network I/O
        try:
            net_io = psutil.net_io_counters()
            bytes_sent_mb = net_io.bytes_sent / (1024 ** 2)
            bytes_recv_mb = net_io.bytes_recv / (1024 ** 2)
            table.add_row(
                "Network I/O",
                f"↑{bytes_sent_mb:.1f} ↓{bytes_recv_mb:.1f}MB",
                "N/A",
                "🟢"
            )
        except (AttributeError, OSError):
            table.add_row("Network I/O", "N/A", "N/A", "⚪")
        
        # Process count
        try:
            process_count = len(psutil.pids())
            table.add_row(
                "Processes",
                str(process_count),
                str(process_count),
                "🟢"
            )
        except (AttributeError, OSError):
            table.add_row("Processes", "N/A", "N/A", "⚪")
        
        return Panel(table, border_style="blue")
    
    def _get_status_indicator(self, value: float, warning_threshold: float, critical_threshold: float) -> str:
        """Get status indicator based on threshold values."""
        if value >= critical_threshold:
            return "🔴"
        elif value >= warning_threshold:
            return "🟡"
        else:
            return "🟢"
    
    def _show_monitoring_summary(self, duration: float):
        """Show monitoring session summary."""
        self.console.print("\n" + "="*60)
        self.console.print("[bold blue]📊 System Resource Monitoring Summary[/bold blue]")
        self.console.print("="*60)
        
        self.console.print(f"[cyan]Monitoring Duration:[/cyan] {duration:.1f}s")
        self.console.print(f"[cyan]Peak CPU Usage:[/cyan] {self.peak_cpu:.1f}%")
        self.console.print(f"[cyan]Peak Memory Usage:[/cyan] {self.peak_memory:.1f}%")
        
        if self.peak_temperature > 0:
            self.console.print(f"[cyan]Peak CPU Temperature:[/cyan] {self.peak_temperature:.1f}°C")
        
        # Performance assessment
        if self.peak_cpu > 90 or self.peak_memory > 90:
            self.console.print("[red]⚠️  High resource usage detected - consider optimization[/red]")
        elif self.peak_cpu > 70 or self.peak_memory > 70:
            self.console.print("[yellow]⚠️  Moderate resource usage - monitor closely[/yellow]")
        else:
            self.console.print("[green]✅ Resource usage within normal limits[/green]")
        
        self.console.print("="*60)
    
    def get_current_metrics(self) -> dict:
        """Get current system metrics as a dictionary."""
        try:
            cpu_percent = psutil.cpu_percent(interval=0.1)
            memory = psutil.virtual_memory()
            disk = psutil.disk_usage('/')
            
            metrics = {
                'timestamp': datetime.now().isoformat(),
                'cpu_percent': cpu_percent,
                'memory_percent': memory.percent,
                'memory_used_gb': memory.used / (1024 ** 3),
                'memory_total_gb': memory.total / (1024 ** 3),
                'disk_percent': disk.percent,
                'disk_free_gb': disk.free / (1024 ** 3)
            }
            
            # Try to get temperature
            try:
                temps = psutil.sensors_temperatures()
                if temps and 'coretemp' in temps:
                    metrics['cpu_temperature'] = max(temp.current for temp in temps['coretemp'])
            except (AttributeError, KeyError):
                pass
            
            return metrics
        except (AttributeError, OSError) as e:
            return {'error': str(e), 'timestamp': datetime.now().isoformat()}
    
    def check_resource_health(self) -> dict:
        """Check overall system resource health."""
        metrics = self.get_current_metrics()
        
        if 'error' in metrics:
            return {'status': 'error', 'message': metrics['error']}
        
        health_checks = []
        
        # CPU health
        if metrics['cpu_percent'] > 95:
            health_checks.append(('CPU', 'critical', f"CPU usage at {metrics['cpu_percent']:.1f}%"))
        elif metrics['cpu_percent'] > 80:
            health_checks.append(('CPU', 'warning', f"CPU usage at {metrics['cpu_percent']:.1f}%"))
        else:
            health_checks.append(('CPU', 'healthy', f"CPU usage at {metrics['cpu_percent']:.1f}%"))
        
        # Memory health
        if metrics['memory_percent'] > 95:
            health_checks.append(('Memory', 'critical', f"Memory usage at {metrics['memory_percent']:.1f}%"))
        elif metrics['memory_percent'] > 80:
            health_checks.append(('Memory', 'warning', f"Memory usage at {metrics['memory_percent']:.1f}%"))
        else:
            health_checks.append(('Memory', 'healthy', f"Memory usage at {metrics['memory_percent']:.1f}%"))
        
        # Disk health
        if metrics['disk_percent'] > 95:
            health_checks.append(('Disk', 'critical', f"Disk usage at {metrics['disk_percent']:.1f}%"))
        elif metrics['disk_percent'] > 80:
            health_checks.append(('Disk', 'warning', f"Disk usage at {metrics['disk_percent']:.1f}%"))
        else:
            health_checks.append(('Disk', 'healthy', f"Disk usage at {metrics['disk_percent']:.1f}%"))
        
        # Overall status
        if any(check[1] == 'critical' for check in health_checks):
            overall_status = 'critical'
        elif any(check[1] == 'warning' for check in health_checks):
            overall_status = 'warning'
        else:
            overall_status = 'healthy'
        
        return {
            'status': overall_status,
            'checks': health_checks,
            'metrics': metrics
        }


class ErrorRecoveryProgressTracker(GranularProgressTracker):
    """Specialized progress tracker for error recovery and export operations."""
    
    def __init__(self, console: Console, total_steps: int = 100):
        """Initialize the error recovery progress tracker."""
        super().__init__(console, total_steps)
        self.error_count = 0
        self.recovery_attempts = 0
        self.max_recovery_attempts = 3
        self.export_formats = []
        self.export_progress = {}
        
    def start_error_recovery(self, error_type: str, error_message: str, context: str = None):
        """Start tracking error recovery progress."""
        self.error_count += 1
        self.recovery_attempts = 0
        
        self.add_warning(f"Error #{self.error_count}: {error_type} - {error_message}")
        if context:
            self.add_info(f"Context: {context}")
        
        self.update_stage("error_recovery", "Starting error recovery")
        self.update_progress(0, "Error recovery initiated")
    
    def track_recovery_attempt(self, attempt_number: int, strategy: str, description: str = None):
        """Track a recovery attempt."""
        self.recovery_attempts = attempt_number
        
        if attempt_number > self.max_recovery_attempts:
            self.add_error(f"Maximum recovery attempts ({self.max_recovery_attempts}) exceeded")
            return False
        
        self.add_info(f"Recovery attempt {attempt_number}/{self.max_recovery_attempts}: {strategy}")
        if description:
            self.add_info(f"Strategy details: {description}")
        
        self.update_stage("error_recovery", f"Attempt {attempt_number}: {strategy}")
        self.update_progress(attempt_number * 25, f"Recovery attempt {attempt_number}")
        
        return True
    
    def track_recovery_progress(self, progress: int, description: str = None):
        """Track progress within a recovery attempt."""
        if self.stage_task:
            if description:
                self.progress.update(
                    self.stage_task,
                    description=f"[yellow]Stage: error_recovery - {description}[/yellow]",
                    completed=progress
                )
            else:
                self.progress.update(self.stage_task, completed=progress)
    
    def complete_recovery(self, success: bool, strategy_used: str = None):
        """Complete error recovery tracking."""
        if success:
            self.add_success(f"Error recovery successful using strategy: {strategy_used or 'Unknown'}")
            self.update_progress(100, "Error recovery completed successfully")
        else:
            self.add_error(f"Error recovery failed after {self.recovery_attempts} attempts")
            self.update_progress(100, "Error recovery failed")
    
    def start_export_tracking(self, formats: List[str], output_dir: str):
        """Start tracking export progress for multiple formats."""
        self.export_formats = formats
        self.export_progress = {fmt: 0 for fmt in formats}
        
        self.add_info(f"Starting export to {output_dir} in formats: {', '.join(formats)}")
        self.update_stage("export", f"Exporting in {len(formats)} formats")
        self.update_progress(0, "Export started")
    
    def track_export_progress(self, format_type: str, progress: int, description: str = None):
        """Track progress for a specific export format."""
        if format_type in self.export_formats:
            self.export_progress[format_type] = progress
            
            if description:
                self.add_info(f"{format_type.upper()} export: {description}")
            
            # Calculate overall export progress
            total_progress = sum(self.export_progress.values()) / len(self.export_formats)
            self.update_progress(int(total_progress), f"Export progress: {total_progress:.1f}%")
    
    def complete_export_format(self, format_type: str, output_path: str = None):
        """Mark a specific export format as completed."""
        if format_type in self.export_formats:
            self.export_progress[format_type] = 100
            self.add_success(f"{format_type.upper()} export completed")
            
            if output_path:
                self.add_info(f"Output saved to: {output_path}")
            
            # Check if all exports are complete
            if all(progress == 100 for progress in self.export_progress.values()):
                self.update_progress(100, "All exports completed")
                self.add_success("All export formats completed successfully")
    
    def show_export_summary(self, export_results: dict):
        """Show a summary of export operations."""
        self.console.print("\n" + "="*50)
        self.console.print("[bold blue]📤 Export Summary[/bold blue]")
        self.console.print("="*50)
        
        for format_type, result in export_results.items():
            if result.get('success'):
                self.console.print(f"[green]✅ {format_type.upper()}:[/green] {result.get('path', 'Exported')}")
            else:
                self.console.print(f"[red]❌ {format_type.upper()}:[/red] {result.get('error', 'Failed')}")
        
        # Show export statistics
        successful_exports = sum(1 for r in export_results.values() if r.get('success'))
        total_exports = len(export_results)
        
        self.console.print(f"\n[cyan]Export Success Rate:[/cyan] {successful_exports}/{total_exports} ({successful_exports/total_exports*100:.1f}%)")
        
        if successful_exports == total_exports:
            self.console.print("[green]🎉 All exports completed successfully![/green]")
        elif successful_exports > 0:
            self.console.print(f"[yellow]⚠️  {total_exports - successful_exports} export(s) failed[/yellow]")
        else:
            self.console.print("[red]💥 All exports failed![/red]")
        
        self.console.print("="*50)
    
    def track_cleanup_progress(self, progress: int, description: str = None):
        """Track cleanup operations after export."""
        self.update_stage("cleanup", "Cleaning up temporary files")
        self.update_stage_progress(progress, description or "Cleanup in progress")
    
    def show_error_summary(self):
        """Show a summary of errors encountered and recovery attempts."""
        if self.error_count == 0:
            self.console.print("[green]✅ No errors encountered during processing[/green]")
            return
        
        self.console.print("\n" + "="*50)
        self.console.print("[bold blue]⚠️  Error Recovery Summary[/bold blue]")
        self.console.print("="*50)
        
        self.console.print(f"[cyan]Total Errors:[/cyan] {self.error_count}")
        self.console.print(f"[cyan]Recovery Attempts:[/cyan] {self.recovery_attempts}")
        self.console.print(f"[cyan]Recovery Success Rate:[/cyan] {self.recovery_attempts / self.error_count * 100:.1f}%")
        
        if self.recovery_attempts > 0:
            self.console.print("[green]✅ Error recovery system was active[/green]")
        else:
            self.console.print("[yellow]⚠️  No recovery attempts were made[/yellow]")
        
        self.console.print("="*50)


# Click command definitions
@click.group()
@click.version_option(version="2.0.0")
def cli():
    """Enhanced Audio Transcription Tool with Progress Reporting and Performance Monitoring"""
    pass


@cli.command()
@click.argument('input', type=click.Path(exists=True))
@click.option('--output', '-o', type=click.Path(), default='./output', help='Output directory')
@click.option('--format', '-f', type=click.Choice(['json', 'txt', 'srt', 'vtt']), default='json', help='Output format')
@click.option('--model', '-m', type=click.Choice(['tiny', 'base', 'small', 'medium', 'large']), default='base', help='Model size')
@click.option('--device', '-d', type=click.Choice(['cpu', 'cuda']), default='cpu', help='Processing device')
@click.option('--domain', type=click.Choice(['general', 'technical', 'medical', 'academic']), help='Domain adaptation')
@click.option('--diarize', is_flag=True, help='Enable speaker diarization')
@click.option('--speakers', type=int, help='Number of speakers (for diarization)')
def transcribe(input, output, format, model, device, domain, diarize, speakers):
    """Transcribe a single audio file with enhanced progress reporting."""
    async def _transcribe():
        try:
            command = EnhancedTranscribeCommand()
            result = await command.execute_transcription(
                input_path=input,
                output_dir=output,
                format_type=format,
                model=model,
                device=device,
                domain=domain,
                diarize=diarize,
                speakers=speakers
            )
            
            if result:
                base_console.print(f"[green]✓[/green] Transcription completed: {result}")
            else:
                base_console.print("[red]✗[/red] Transcription failed!")
                
        except Exception as e:
            cli_instance = EnhancedCLI()
            cli_instance.handle_error(e, "Single file transcription")
            sys.exit(1)
    
    asyncio.run(_transcribe())


@cli.command()
@click.argument('input', type=click.Path(exists=True))
@click.option('--output', '-o', type=click.Path(), default='./output', help='Output directory')
@click.option('--concurrency', '-c', type=int, default=2, help='Number of concurrent processes')
@click.option('--format', '-f', type=click.Choice(['json', 'txt', 'srt', 'vtt']), default='json', help='Output format')
@click.option('--model', '-m', type=click.Choice(['tiny', 'base', 'small', 'medium', 'large']), default='base', help='Model size')
@click.option('--device', '-d', type=click.Choice(['cpu', 'cuda']), default='cpu', help='Processing device')
@click.option('--domain', type=click.Choice(['general', 'technical', 'medical', 'academic']), help='Domain adaptation')
@click.option('--diarize', is_flag=True, help='Enable speaker diarization')
@click.option('--speakers', type=int, help='Number of speakers (for diarization)')
def batch(input, output, concurrency, format, model, device, domain, diarize, speakers):
    """Process multiple files in batch with intelligent queuing and progress reporting."""
    async def _batch():
        try:
            command = EnhancedBatchCommand()
            files = command._discover_files(input)
            
            if not files:
                base_console.print(f"[red]No media files found in: {input}[/red]")
                return
            
            # Sort files by size for intelligent queuing
            sorted_files = command._sort_files_by_size(files)
            
            base_console.print(f"[bold blue]Batch Processing Setup[/bold blue]")
            base_console.print(f"[cyan]Input:[/cyan] {input}")
            base_console.print(f"[cyan]Files found:[/cyan] {len(files)}")
            base_console.print(f"[cyan]Concurrency:[/cyan] {concurrency}")
            base_console.print(f"[cyan]Format:[/cyan] {format}")
            base_console.print(f"[cyan]Model:[/cyan] {model}")
            
            # Process files
            transcribe_command = EnhancedTranscribeCommand()
            
            def transcription_func(file_path):
                return asyncio.run(transcribe_command.execute_transcription(
                    input_path=str(file_path),
                    output_dir=output,
                    format_type=format,
                    model=model,
                    device=device,
                    domain=domain,
                    diarize=diarize,
                    speakers=speakers
                ))
            
            results = asyncio.run(command._process_concurrently(
                files=[str(f) for f in sorted_files],
                concurrency=concurrency,
                transcription_func=transcription_func,
                progress_callback=lambda: None  # Progress handled by individual transcribe calls
            ))
            
            # Display summary
            successful = sum(1 for r in results if r['status'] == 'success')
            failed = len(results) - successful
            
            base_console.print(f"\n[bold]Batch Processing Complete![/bold]")
            base_console.print(f"[green]Successful:[/green] {successful}")
            base_console.print(f"[red]Failed:[/red] {failed}")
            
            # Display performance stats
            cli_instance = EnhancedCLI()
            cli_instance.display_performance_stats()
            
        except Exception as e:
            cli_instance = EnhancedCLI()
            cli_instance.handle_error(e, "Batch processing")
            sys.exit(1)
    
    asyncio.run(_batch())


if __name__ == "__main__":
    cli()
