//! `relicario edit <query>` — interactive per-type field editing with history capture.

use std::path::PathBuf;

use anyhow::Result;

use crate::prompt::{prompt_keep, prompt_keep_opt};

pub fn cmd_edit(query: String, totp_qr: Option<PathBuf>) -> Result<()> {
    use relicario_core::time::now_unix;
    use relicario_core::ItemCore;

    let vault = crate::session::UnlockedVault::unlock_interactive()?;
    let mut manifest = vault.load_manifest()?;
    let entry = super::resolve_query(&manifest, &query)?;
    let id = entry.id.clone();
    let _ = entry;
    let mut item = vault.load_item(&id)?;

    eprintln!("Editing: {} ({})  — leave a prompt blank to keep the current value.",
              item.title, item.id.as_str());

    if let Some(v) = prompt_keep("Title", &item.title)? { item.title = v; }
    if let Some(v) = prompt_keep_opt("Group", item.group.as_deref())? { item.group = Some(v); }
    if let Some(v) = prompt_keep_opt("Tags (comma-separated)", Some(&item.tags.join(",")))? {
        item.tags = v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
    }

    let history = &mut item.field_history;
    match &mut item.core {
        ItemCore::Login(l)      => crate::commands::item_build::edit_login(l, history, totp_qr)?,
        ItemCore::SecureNote(n) => crate::commands::item_build::edit_secure_note(n, history)?,
        ItemCore::Identity(i)   => crate::commands::item_build::edit_identity(i)?,
        ItemCore::Card(c)       => crate::commands::item_build::edit_card(c, history)?,
        ItemCore::Key(k)        => crate::commands::item_build::edit_key(k, history)?,
        ItemCore::Document(_)   => crate::commands::item_build::edit_document_message(),
        ItemCore::Totp(t)       => crate::commands::item_build::edit_totp(t, history)?,
    }

    item.modified = now_unix();
    vault.save_item(&item)?;
    manifest.upsert(&item);
    vault.after_manifest_change(&manifest)?;
    super::commit_paths(&vault, &format!("edit: {} ({})", crate::helpers::sanitize_for_commit(&item.title), item.id.as_str()),
                 &[&format!("items/{}.enc", item.id.as_str()), "manifest.enc"])?;
    eprintln!("Updated {}", item.id.as_str());
    Ok(())
}
