"""Main CLI entry point for the Trax platform with enhanced CLI integration."""

import click
from rich.console import Console
from rich.panel import Panel

from .commands import youtube, batch_urls, transcribe, batch
from .enhanced_cli import EnhancedCLI, EnhancedTranscribeCommand

# Initialize console for rich output
console = Console()


@click.group()
@click.version_option(version="1.0.0")
def cli():
    """Trax: Personal Research Transcription Tool with Enhanced CLI"""
    pass


# Register existing commands
cli.add_command(youtube)
cli.add_command(batch_urls)
cli.add_command(transcribe)
cli.add_command(batch)


@cli.command()
@click.argument('input_path', type=click.Path(exists=True))
@click.option('--output-dir', '-o', type=click.Path(), help='Output directory for transcriptions')
@click.option('--format', type=click.Choice(['txt', 'srt', 'vtt', 'json']), default='txt', help='Output format')
@click.option('--diarize', is_flag=True, help='Enable speaker diarization')
@click.option('--domain', type=click.Choice(['general', 'technical', 'medical', 'academic']), help='Specify domain for adaptation')
@click.option('--auto-domain', is_flag=True, help='Auto-detect domain')
@click.option('--batch-size', type=int, default=1, help='Batch processing size')
@click.option('--progress', is_flag=True, default=True, help='Show progress bar')
@click.option('--min-accuracy', default=80.0, help='Minimum accuracy threshold (default: 80%)')
@click.option('--confidence-threshold', default=0.85, help='Confidence threshold for refinement (default: 0.85)')
def enhanced_transcribe(input_path, output_dir, format, diarize, domain, auto_domain, batch_size, progress, min_accuracy, confidence_threshold):
    """Enhanced transcription with progress tracking and advanced features."""
    try:
        # Initialize enhanced CLI
        enhanced_cli = EnhancedCLI()
        
        # Display system information
        if progress:
            enhanced_cli.display_performance_stats()
        
        # Process transcription with enhanced CLI
        enhanced_cli.process_transcription(
            input_path=input_path,
            output_dir=output_dir,
            format=format,
            diarize=diarize,
            domain=domain,
            auto_domain=auto_domain,
            batch_size=batch_size,
            show_progress=progress,
            min_accuracy=min_accuracy,
            confidence_threshold=confidence_threshold
        )
        
    except Exception as e:
        enhanced_cli = EnhancedCLI()
        enhanced_cli.handle_error(e, context="Enhanced transcription command")


@cli.command()
@click.option('--test-file', type=click.Path(exists=True), required=True, help='Audio file to use for benchmarking')
@click.option('--iterations', type=int, default=3, help='Number of benchmark iterations')
def benchmark(test_file, iterations):
    """Run performance benchmarks on the transcription system."""
    try:
        from ..services.performance_benchmarker import PerformanceBenchmarker
        
        console.print(Panel(f"Running benchmarks with {iterations} iterations"))
        
        # Run benchmarks
        benchmarker = PerformanceBenchmarker()
        
        # For now, just show that benchmarking is available
        # In a full implementation, this would run actual benchmarks
        results = f"Benchmarking available for {test_file} with {iterations} iterations"
        
        # Display results
        console.print(Panel(f"Benchmark Results:\n{results}", title="Benchmark Complete"))
        
    except Exception as e:
        enhanced_cli = EnhancedCLI()
        enhanced_cli.handle_error(e, context="Benchmark command")


@cli.command()
@click.option('--type', type=click.Choice(['whisper', 'diarization', 'domain']), required=True, help='Model type')
@click.option('--name', required=True, help='Model name/size to download')
def download_model(type, name):
    """Download a specific model."""
    try:
        from ..services.model_manager import ModelManager
        
        console.print(Panel(f"Downloading {type} model: {name}"))
        
        model_manager = ModelManager()
        model_manager.download_model(type, name)
        
        console.print(Panel(f"Successfully downloaded {type} model: {name}", title="Download Complete"))
        
    except Exception as e:
        enhanced_cli = EnhancedCLI()
        enhanced_cli.handle_error(e, context="Model download command")


@cli.command()
def list_models():
    """List available models."""
    try:
        from ..services.model_manager import ModelManager
        
        model_manager = ModelManager()
        models = model_manager.list_available_models()
        
        console.print(Panel("Available Models:", title="Model Information"))
        for model_type, model_list in models.items():
            console.print(f"[bold]{model_type}[/bold]: {', '.join(model_list)}")
            
    except Exception as e:
        enhanced_cli = EnhancedCLI()
        enhanced_cli.handle_error(e, context="Model listing command")


@cli.command()
def system_info():
    """Display system information and resource usage."""
    try:
        enhanced_cli = EnhancedCLI()
        enhanced_cli.display_performance_stats()
        
    except Exception as e:
        enhanced_cli = EnhancedCLI()
        enhanced_cli.handle_error(e, context="System info command")


if __name__ == "__main__":
    cli()
