//! `hephaes status` — configuration, wiki, and drift overview (offline).

use super::{base_overrides, repo_root, wiki_abs};
use crate::cli::{GlobalArgs, StatusArgs};
use crate::config::{self, Paths, DEFAULT_WIKI_DIR};
use crate::repo::diff;
use crate::state::Manifest;
use crate::wiki::{index, log};
use anyhow::Result;
use owo_colors::OwoColorize;

pub async fn run(global: &GlobalArgs, args: StatusArgs) -> Result<()> {
    let root = repo_root(args.path.clone())?;
    let paths = Paths::new(&root);
    let ov = base_overrides(global);
    let resolved = config::resolve(&paths, &ov)?;

    println!("{}", "hephaes status".bold());
    println!("repository: {}", root.display());

    match &resolved {
        Some(cfg) => {
            println!(
                "provider:   {} (model: {})",
                cfg.provider.as_str(),
                cfg.model.as_deref().unwrap_or("default")
            );
        }
        None => println!("provider:   {}", "not configured".yellow()),
    }

    let wiki_dir = resolved
        .as_ref()
        .map(|c| c.wiki_dir.clone())
        .unwrap_or_else(|| DEFAULT_WIKI_DIR.to_string());
    let wiki = resolved
        .as_ref()
        .map(|c| wiki_abs(&root, c))
        .unwrap_or_else(|| root.join(&wiki_dir));

    if wiki.exists() {
        let pages = index::list_pages(&wiki).len();
        println!("wiki:       {wiki_dir}/ ({pages} page(s))");
    } else {
        println!("wiki:       {} (run `hephaes init`)", "absent".yellow());
    }

    let manifest = Manifest::load(&paths.manifest);
    let head = diff::head_commit(&root);
    if !manifest.sources.is_empty() {
        println!(
            "manifest:   {} source(s), last built at {}",
            manifest.sources.len(),
            manifest.last_commit.as_deref().unwrap_or("?")
        );
        if let (Some(h), Some(last)) = (&head, &manifest.last_commit) {
            if h != last {
                println!(
                    "            {} HEAD is {h}; run `hephaes update`",
                    "drift:".yellow()
                );
            } else {
                println!("            {} up to date with HEAD", "✓".green());
            }
        }
    } else {
        println!("manifest:   {}", "none".yellow());
    }

    if wiki.exists() {
        let recent = log::tail(&wiki, 5);
        if !recent.is_empty() {
            println!("\nrecent log:");
            for e in recent {
                println!("  {e}");
            }
        }
    }
    Ok(())
}
