//! `relicario status` — vault-level summary (counts, last commit, last backup).

use anyhow::Result;

pub fn cmd_status() -> Result<()> {
    let vault = crate::session::UnlockedVault::unlock_interactive()?;
    let root = vault.root().to_path_buf();
    let manifest = vault.load_manifest()?;

    let total_items = manifest.items.len();
    let trashed_items = manifest.items.values().filter(|e| e.trashed_at.is_some()).count();
    let active_items = total_items - trashed_items;

    let (attachment_count, attachment_bytes) = manifest.items.values()
        .flat_map(|e| e.attachment_summaries.iter())
        .fold((0u64, 0u64), |(c, b), s| (c + 1, b + s.size));

    let last_commit = crate::helpers::git_command(&root, &[
        "log", "-1", "--pretty=format:%h %s",
    ]).output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|| "(no commits)".into());

    // Last backup age (read from marker written by cmd_backup_export).
    let last_backup_path = vault.root().join(".relicario").join("last_backup");
    let last_backup_str = if last_backup_path.exists() {
        let line = std::fs::read_to_string(&last_backup_path)
            .unwrap_or_default()
            .trim()
            .to_string();
        // Parse the ISO-8601 we wrote in cmd_backup_export.
        match chrono::DateTime::parse_from_rfc3339(&line) {
            Ok(then) => {
                let now = relicario_core::now_unix();
                let age = now - then.timestamp();
                crate::helpers::humanize_age(age.max(0))
            }
            Err(_) => "unknown".to_string(),
        }
    } else {
        "never".to_string()
    };

    println!("Vault:    {}", root.display());
    println!("Items:    {total_items} total ({active_items} active, {trashed_items} trashed)");
    println!("Attachments: {attachment_count} ({attachment_bytes} bytes)");
    println!("Last commit: {last_commit}");
    println!("Last export: {last_backup_str}");
    Ok(())
}
