"""Batch processing commands for the Trax CLI."""

import asyncio
import json
import click
from pathlib import Path
from rich.table import Table

from ..utils import console
from .transcription import find_media_files, validate_media_directory
from ...services.batch_processor import create_batch_processor, TaskType
from ...services.transcription_service import TranscriptionConfig
from ..progress import CliProgressRenderer


@click.command()
@click.argument('folder', type=click.Path(exists=True, file_okay=False, dir_okay=True))
@click.option('--workers', '-w', default=8, help='Number of worker processes (default: 8)')
@click.option('--v1', 'version', flag_value='v1', default=True, help='Use v1 pipeline (Whisper only)')
@click.option('--v2', 'version', flag_value='v2', help='Use v2 pipeline (Whisper + Enhancement)')
@click.option('--min-accuracy', default=80.0, help='Minimum accuracy threshold (default: 80%)')
@click.option('--json', 'output_format', flag_value='json', default=True, help='Output as JSON')
@click.option('--txt', 'output_format', flag_value='txt', help='Output as plain text')
def batch(folder, workers, version, min_accuracy, output_format):
    """Process multiple files in batch with parallel processing."""
    async def _batch():
        try:
            folder_path = Path(folder)
            
            # Find audio files in directory
            audio_files = find_media_files(folder_path)
            
            if not audio_files:
                console.print(f"[red]No audio/video files found in directory: {folder}[/red]")
                return
            
            console.print(f"[bold blue]Batch Processing Setup[/bold blue]")
            console.print(f"[cyan]Folder:[/cyan] {folder}")
            console.print(f"[cyan]Files found:[/cyan] {len(audio_files)}")
            console.print(f"[cyan]Workers:[/cyan] {workers}")
            console.print(f"[cyan]Version:[/cyan] {version}")
            console.print(f"[cyan]Min Accuracy:[/cyan] {min_accuracy}%")
            
            # Create batch processor
            processor = create_batch_processor(
                max_workers=workers,
                progress_interval=5.0,
                memory_limit_mb=2048,
                cpu_limit_percent=90
            )
            
            # Configure transcription
            config = TranscriptionConfig(
                model="whisper-1",
                chunk_size_seconds=600
            )
            
            console.print(f"\n[yellow]Adding {len(audio_files)} transcription tasks to queue...[/yellow]")
            
            for file_path in audio_files:
                await processor.add_task(
                    TaskType.TRANSCRIBE,
                    {
                        "file_path": str(file_path),
                        "config": {
                            "model": config.model,
                            "language": config.language,
                            "chunk_size_seconds": config.chunk_size_seconds
                        }
                    }
                )
            
            # Progress tracking with renderer ticker line (non-intrusive)
            renderer = CliProgressRenderer(console)

            def progress_callback(progress):
                renderer.render_batch_line(
                    f"\r[cyan]Progress:[/cyan] {progress.completed_tasks}/{progress.total_tasks} "
                    f"({progress.success_rate:.1f}% success) | "
                    f"[yellow]Active:[/yellow] {progress.current_worker_count} | "
                    f"[red]Failed:[/red] {progress.failed_tasks} | "
                    f"[green]Memory:[/green] {progress.memory_usage_mb:.1f}MB | "
                    f"[blue]CPU:[/blue] {progress.cpu_usage_percent:.1f}%"
                )
            
            console.print(f"\n[bold green]Starting batch processing...[/bold green]")
            console.print("Press Ctrl+C to stop processing\n")
            
            # Start processing
            result = await processor.start(progress_callback=progress_callback)
            
            # Display final results
            console.print(f"\n\n[bold]Batch Processing Complete![/bold]")
            
            if output_format == 'json':
                output_data = {
                    'total_files': result.total_count,
                    'successful': result.success_count,
                    'failed': result.failure_count,
                    'success_rate': result.success_rate,
                    'processing_time': result.processing_time,
                    'memory_peak_mb': result.memory_peak_mb,
                    'cpu_peak_percent': result.cpu_peak_percent,
                    'failures': result.failures
                }
                console.print(json.dumps(output_data, indent=2))
            else:
                summary_table = Table(title="Processing Summary")
                summary_table.add_column("Metric", style="cyan")
                summary_table.add_column("Value", style="green")
                
                summary_table.add_row("Total Files", str(result.total_count))
                summary_table.add_row("Successful", str(result.success_count))
                summary_table.add_row("Failed", str(result.failure_count))
                summary_table.add_row("Success Rate", f"{result.success_rate:.1f}%")
                summary_table.add_row("Processing Time", f"{result.processing_time:.1f}s")
                summary_table.add_row("Peak Memory", f"{result.memory_peak_mb:.1f}MB")
                summary_table.add_row("Peak CPU", f"{result.cpu_peak_percent:.1f}%")
                
                console.print(summary_table)
                
                # Failed files
                if result.failures:
                    console.print(f"\n[red]Failed Files:[/red]")
                    for failure in result.failures:
                        console.print(f"  • {failure['task_id']}: {failure['error']}")
        
        except KeyboardInterrupt:
            console.print(f"\n[yellow]Batch processing interrupted by user[/yellow]")
        except Exception as e:
            console.print(f"\n[red]Error during batch processing: {e}[/red]")
            raise click.Abort()
    
    asyncio.run(_batch())
