//! Corpus command handlers

use std::process::ExitCode;

use aphoria::{AphoriaConfig, CorpusBuildArgs};

use crate::cli::{CorpusCommands, ImportSource};

pub async fn handle_corpus_command(command: CorpusCommands, config: &AphoriaConfig) -> ExitCode {
    match command {
        CorpusCommands::Import { source } => match source {
            ImportSource::Wiki { path } => {
                match aphoria::import_corpus_from_wiki(&path, config).await {
                    Ok(count) => {
                        println!("Imported {} patterns from wiki at {}", count, path.display());
                        ExitCode::SUCCESS
                    }
                    Err(e) => {
                        eprintln!("Wiki import error: {e}");
                        ExitCode::from(3)
                    }
                }
            }
        },

        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::ExportPack { name, output, only, offline } => {
            let only_parsed = only.map(|s| s.split(',').map(|s| s.trim().to_string()).collect());
            match aphoria::export_corpus_as_pack(name, output, only_parsed, offline, config).await {
                Ok(count) => {
                    println!("Exported {count} assertions as Trust Pack");
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    eprintln!("Export 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
        }

        CorpusCommands::Create {
            subject,
            predicate,
            value,
            explanation,
            authority,
            category,
            tier,
        } => {
            match aphoria::create_corpus_item(
                subject,
                predicate,
                value,
                explanation,
                authority,
                category,
                tier,
                config,
            )
            .await
            {
                Ok(corpus_id) => {
                    println!("Created corpus item: {}", corpus_id);
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    eprintln!("Error creating corpus item: {e}");
                    ExitCode::from(3)
                }
            }
        }
    }
}
