use std::path::PathBuf;
use std::str::FromStr;

use lobe_core::error::{Result, TloxError};
use lobe_core::explain::{explain_session, ExplainModel, ExplainOptions, ExplainResult};

pub async fn run_explain(
    session: PathBuf,
    model_flag: String,
    output: Option<PathBuf>,
) -> Result<()> {
    let model = ExplainModel::from_str(&model_flag)
        .map_err(|message| TloxError::InvalidTarget(message))?;

    let options = ExplainOptions {
        model,
        ..ExplainOptions::default()
    };

    eprintln!("lobe explain — using {} …", model.display_name());
    let ExplainResult {
        markdown,
        summary_stats,
        estimated_input_tokens,
        ..
    } = explain_session(&session, options).await?;

    eprintln!(
        "session: {} requests, {} errors, {:.1}s span, {} distinct routes (~{}k input tokens)",
        summary_stats.total_requests,
        summary_stats.error_requests,
        summary_stats.duration_seconds,
        summary_stats.distinct_routes,
        estimated_input_tokens / 1000,
    );

    match output {
        Some(path) => {
            std::fs::write(&path, &markdown)?;
            eprintln!("report written to {}", path.display());
        }
        None => {
            println!("{markdown}");
        }
    }

    Ok(())
}
