#!/usr/bin/env python3
"""
Optimized transcription CLI command using parallel + adaptive processing.

Implements the optimizations from DEV_HANDOFF_TRANSCRIPTION_OPTIMIZATION.md
"""

import asyncio
import click
from pathlib import Path
import time
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
from rich.table import Table

from src.services.optimized_transcription import OptimizedTranscriptionPipeline

console = Console()


@click.command()
@click.argument('audio_path', type=click.Path(exists=True))
@click.option('--model', default='distil-large-v3', help='Model to use (distil-large-v3 recommended for M3)')
@click.option('--language', default=None, help='Language code (e.g., en, es, fr)')
@click.option('--workers', default=4, type=int, help='Number of parallel workers')
@click.option('--no-adaptive', is_flag=True, help='Disable adaptive chunking')
@click.option('--no-parallel', is_flag=True, help='Disable parallel processing')
@click.option('--output', '-o', type=click.Path(), help='Output file path')
@click.option('--verbose', '-v', is_flag=True, help='Verbose output')
def transcribe_optimized(
    audio_path: str,
    model: str,
    language: str,
    workers: int,
    no_adaptive: bool,
    no_parallel: bool,
    output: str,
    verbose: bool
):
    """
    Transcribe audio using optimized pipeline with parallel + adaptive processing.
    
    Achieves 3-8x speed improvement on M3 hardware through:
    - Parallel chunk processing (2-4x)
    - Adaptive chunk sizing (1.5-2x)
    - M3-specific optimizations
    """
    audio_file = Path(audio_path)
    
    if not audio_file.exists():
        console.print(f"[red]Error: File not found: {audio_path}[/red]")
        return
    
    # Show configuration
    console.print("\n[bold cyan]🚀 Optimized Transcription Pipeline[/bold cyan]")
    console.print(f"📁 File: {audio_file.name}")
    console.print(f"🤖 Model: {model}")
    
    config_table = Table(title="Configuration", show_header=False)
    config_table.add_column("Setting", style="cyan")
    config_table.add_column("Value", style="green")
    
    config_table.add_row("Parallel Processing", "✅ Enabled" if not no_parallel else "❌ Disabled")
    config_table.add_row("Adaptive Chunking", "✅ Enabled" if not no_adaptive else "❌ Disabled")
    config_table.add_row("Workers", str(workers) if not no_parallel else "1")
    config_table.add_row("M3 Optimized", "✅ Yes")
    
    console.print(config_table)
    console.print()
    
    # Initialize pipeline
    pipeline = OptimizedTranscriptionPipeline(
        max_workers=workers,
        enable_adaptive=not no_adaptive,
        enable_parallel=not no_parallel,
        m3_optimized=True
    )
    
    # Process with progress bar
    with Progress(
        SpinnerColumn(),
        TextColumn("[progress.description]{task.description}"),
        BarColumn(),
        TimeElapsedColumn(),
        console=console
    ) as progress:
        task = progress.add_task("[cyan]Processing audio...", total=None)
        
        # Run async transcription
        result = asyncio.run(
            pipeline.transcribe(
                audio_file,
                model=model,
                language=language
            )
        )
        
        progress.update(task, completed=100)
    
    # Display results
    console.print("\n[bold green]✅ Transcription Complete![/bold green]\n")
    
    # Performance metrics
    perf_table = Table(title="Performance Metrics")
    perf_table.add_column("Metric", style="cyan")
    perf_table.add_column("Value", style="yellow")
    
    perf_table.add_row("Processing Time", f"{result.processing_time:.2f} seconds")
    perf_table.add_row("Realtime Factor", f"{result.speedup_factor:.1f}x")
    perf_table.add_row("Chunks Processed", str(result.chunks_processed))
    perf_table.add_row("Strategy Used", result.strategy_used.title())
    perf_table.add_row("Memory Usage", f"{result.memory_usage_mb:.1f} MB")
    
    console.print(perf_table)
    
    # Improvement breakdown
    if not no_parallel or not no_adaptive:
        console.print("\n[bold]Speed Improvements:[/bold]")
        console.print(f"  • Parallel Processing: {result.parallel_speedup:.1f}x")
        console.print(f"  • Adaptive Chunking: {result.adaptive_improvement:.1f}x")
        console.print(f"  • [bold green]Total Improvement: {result.total_improvement:.1f}x[/bold green]")
    
    # Output transcription
    if output:
        output_path = Path(output)
        output_path.write_text(result.text)
        console.print(f"\n[green]Transcription saved to: {output_path}[/green]")
    
    if verbose or not output:
        console.print("\n[bold]Transcription:[/bold]")
        console.print("-" * 50)
        # Show first 500 chars in verbose mode
        preview = result.text[:500] + "..." if len(result.text) > 500 else result.text
        console.print(preview)
        if len(result.text) > 500:
            console.print(f"\n[dim]... ({len(result.text)} total characters)[/dim]")
    
    # Success message
    if result.total_improvement >= 3.0:
        console.print("\n[bold green]🎉 Achieved target 3x+ improvement![/bold green]")
    
    return result


if __name__ == '__main__':
    transcribe_optimized()