//! `cordance doctrine <topic>` — query engineering-doctrine by topic.

use anyhow::{bail, Result};
use camino::Utf8PathBuf;

pub fn run(topic: &str, doctrine_root: &Utf8PathBuf) -> Result<()> {
    let idx = cordance_doctrine::load_doctrine_or_default(doctrine_root);
    let all_entries: Vec<_> = idx
        .principles
        .iter()
        .chain(idx.patterns.iter())
        .chain(idx.checklists.iter())
        .chain(idx.tooling.iter())
        .collect();
    let matches: Vec<_> = all_entries
        .iter()
        .filter(|e| e.topic.contains(topic) || topic.contains(&e.topic))
        .collect();
    if matches.is_empty() {
        bail!("No doctrine entry found for topic '{topic}'");
    }
    for m in matches {
        println!("Topic: {}", m.topic);
        println!("Path:  {}", m.path);
        // Use `.get(..8)` to avoid panicking when the hash is empty or
        // shorter than eight bytes (e.g. when the walker recorded a
        // BlockedSurface or hash-failed file).
        let sha_prefix = m.sha256.get(..8).unwrap_or(m.sha256.as_str());
        println!("SHA:   {sha_prefix}");
        println!();
    }
    Ok(())
}
