//! `hephaes ask` — query the wiki (plan §8). A thin wrapper over `engine::ask`;
//! the engine does the work, this renders the answer. Read-only; `--save` files
//! the answer back as a new wiki page.

use super::{base_overrides, ensure_config, repo_root, verbosity};
use crate::cli::{AskArgs, GlobalArgs};
use crate::config::Paths;
use crate::engine::{self, AskOptions, EngineCtx};
use crate::progress_term::TerminalProgress;
use crate::util;
use anyhow::Result;
use owo_colors::OwoColorize;

pub async fn run(global: &GlobalArgs, args: AskArgs) -> Result<()> {
    let root = repo_root(None)?;
    let paths = Paths::new(&root);
    let ov = base_overrides(global);
    let cfg = ensure_config(&paths, &ov, true).await?;
    let ctx = EngineCtx::new(root, cfg);

    let question = args.prompt.join(" ");
    let opts = AskOptions {
        from_source: args.from_source,
        save: args.save,
    };
    let progress = TerminalProgress::new(verbosity(global), util::is_interactive());

    // Always clear the spinner before propagating, so an error leaves no artifact.
    let result = engine::ask(&ctx, &question, &opts, &progress).await;
    progress.finish();
    let result = result?;

    println!("\n{}\n", result.answer);
    if let Some(rel) = result.saved_page {
        println!("{} saved to {}", "✓".green(), rel.dimmed());
    }
    Ok(())
}
