//! Research command handlers

use std::process::ExitCode;

use aphoria::{AphoriaConfig, ResearchArgs};

use crate::cli::ResearchCommands;

pub async fn handle_research_command(
    command: ResearchCommands,
    config: &AphoriaConfig,
) -> ExitCode {
    match command {
        ResearchCommands::Run { threshold, strict, prune, max_age } => {
            let args = ResearchArgs {
                threshold: Some(threshold),
                max_age_days: Some(max_age),
                strict,
                prune,
            };

            match aphoria::run_research(args, config).await {
                Ok(outcome) => {
                    println!("Research agent complete:");
                    println!("  Gaps analyzed: {}", outcome.gaps_analyzed);
                    println!("  Gaps filled: {}", outcome.gaps_filled);
                    println!("  Assertions created: {}", outcome.assertions_created);

                    if !outcome.gaps_failed.is_empty() {
                        println!("  Failed gaps: {}", outcome.gaps_failed.len());
                        for gap in outcome.gaps_failed.iter().take(5) {
                            println!("    - {}", gap);
                        }
                        if outcome.gaps_failed.len() > 5 {
                            println!("    ... and {} more", outcome.gaps_failed.len() - 5);
                        }
                    }

                    // Show quality reports for successful researches
                    println!();
                    for result in &outcome.results {
                        if let Some(ref report) = result.quality_report {
                            println!(
                                "  {}: {} passed, {} failed (quality: {:.0}%)",
                                result.gap,
                                report.passed,
                                report.failed,
                                report.overall_score * 100.0
                            );
                        }
                    }

                    ExitCode::SUCCESS
                }
                Err(e) => {
                    eprintln!("Research error: {e}");
                    ExitCode::from(3)
                }
            }
        }

        ResearchCommands::Status => match aphoria::show_research_status(config).await {
            Ok(output) => {
                println!("{output}");
                ExitCode::SUCCESS
            }
            Err(e) => {
                eprintln!("Research status error: {e}");
                ExitCode::from(3)
            }
        },

        ResearchCommands::Gaps { threshold, ready } => handle_gaps(threshold, ready, config).await,
    }
}

async fn handle_gaps(threshold: u32, ready: bool, config: &AphoriaConfig) -> ExitCode {
    let gap_store_path = config.episteme.data_dir.join("gaps.json");

    if !gap_store_path.exists() {
        println!("No gaps recorded yet. Run scans to collect gap data.");
        return ExitCode::SUCCESS;
    }

    match aphoria::GapStore::open(&gap_store_path) {
        Ok(store) => {
            let effective_threshold = if ready { 3 } else { threshold };
            let gaps = store.gaps_by_project_count(effective_threshold);

            if gaps.is_empty() {
                println!("No gaps seen in {}+ projects.", effective_threshold);
                return ExitCode::SUCCESS;
            }

            println!("Gaps seen in {}+ projects ({} total):\n", effective_threshold, gaps.len());

            for gap in gaps.iter().take(20) {
                let research_status = if gap.research_successful {
                    " [RESEARCHED]"
                } else if gap.research_attempted {
                    " [FAILED]"
                } else {
                    ""
                };

                println!("  {} ({}{})", gap.topic, gap.project_count, research_status);

                // Show sample descriptions
                if let Some(desc) = gap.sample_descriptions.first() {
                    let truncated =
                        if desc.len() > 60 { format!("{}...", &desc[..60]) } else { desc.clone() };
                    println!("    \"{}\"", truncated);
                }
            }

            if gaps.len() > 20 {
                println!("\n  ... and {} more gaps", gaps.len() - 20);
            }

            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("Error opening gap store: {e}");
            ExitCode::from(3)
        }
    }
}
