//! Corpus command handlers

use std::process::ExitCode;

use aphoria::{AphoriaConfig, CorpusBuildArgs};

use crate::cli::CorpusCommands;

pub async fn handle_corpus_command(command: CorpusCommands, config: &AphoriaConfig) -> ExitCode {
    match command {
        CorpusCommands::Build { only, offline, clear_cache } => {
            let only_parsed = only.map(|s| s.split(',').map(|s| s.trim().to_string()).collect());
            let args = CorpusBuildArgs { only: only_parsed, offline, clear_cache };

            match aphoria::build_corpus(args, config).await {
                Ok(result) => {
                    println!("Corpus build complete:");
                    println!("  Total assertions: {}", result.total_assertions());
                    println!("  Successful sources: {}", result.successful_builders());
                    if result.failed_builders() > 0 {
                        println!("  Failed sources: {}", result.failed_builders());
                    }
                    if result.skipped_builders() > 0 {
                        println!("  Skipped sources: {} (offline mode)", result.skipped_builders());
                    }
                    println!();
                    for stat in &result.stats {
                        let status = if stat.skipped {
                            "SKIPPED".to_string()
                        } else if let Some(ref err) = stat.error {
                            format!("FAILED: {}", err)
                        } else {
                            format!("{} assertions", stat.assertions_built)
                        };
                        println!("  {}: {}", stat.name, status);
                    }
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    eprintln!("Corpus build error: {e}");
                    ExitCode::from(3)
                }
            }
        }

        CorpusCommands::List => {
            let sources = aphoria::list_corpus_sources(config);
            println!("Available corpus sources:");
            println!();
            for source in sources {
                let network_status = if source.requires_network { " (network)" } else { "" };
                println!(
                    "  {}:// (Tier {}) - {}{}",
                    source.scheme, source.tier, source.name, network_status
                );
                if !source.source_ids.is_empty() {
                    println!("    Sources: {}", source.source_ids.join(", "));
                }
            }
            ExitCode::SUCCESS
        }
    }
}
