use crate::error::{Context, Result};
use crate::provenance::{ProvenanceEntry, ProvenanceLog};
use crate::vcs::VcsManager;
#[derive(Debug, Clone, serde::Serialize)]
pub struct WhyInfo {
pub file: String,
pub line: Option<usize>,
pub commit: String,
pub timestamp: i64,
pub message: String,
pub operation: Option<String>,
pub agent_id: Option<String>,
pub prompt: Option<String>,
}
pub fn parse_target(target: &str) -> (String, Option<usize>) {
match target.rsplit_once(':') {
Some((path, suffix)) if !path.is_empty() => match suffix.parse::<usize>() {
Ok(n) if n > 0 => (path.to_string(), Some(n)),
_ => (target.to_string(), None),
},
_ => (target.to_string(), None),
}
}
pub async fn lookup_why(
manager: &VcsManager,
provenance: &ProvenanceLog,
target: &str,
) -> Result<WhyInfo> {
let (file, line) = parse_target(target);
let branch = manager.get_current_branch().await?;
let history = manager.get_commit_history(&branch, usize::MAX)?;
let commit_info = if let Some(line_no) = line {
let annotations = manager.blame(&file)?;
let short = annotations
.iter()
.find(|(l, _, _)| *l == line_no)
.map(|(_, c, _)| c.clone())
.ok_or_else(|| format!("Line {} not found in '{}'", line_no, file))?;
history
.iter()
.find(|c| c.hash.starts_with(&short))
.cloned()
.ok_or_else(|| format!("Commit '{}' not found in history", short))?
} else {
let file_hist = manager.file_log(&file)?;
let (newest, _, _) = file_hist
.first()
.cloned()
.ok_or_else(|| format!("No history found for '{}'", file))?;
history
.iter()
.find(|c| c.hash == newest)
.cloned()
.ok_or_else(|| format!("Commit '{}' not found in history", newest))?
};
let entry: Option<ProvenanceEntry> = provenance.get(&commit_info.hash).cloned();
Ok(WhyInfo {
operation: entry.as_ref().map(|e| e.operation.clone()),
agent_id: entry.as_ref().and_then(|e| e.agent_id.clone()),
prompt: entry.as_ref().and_then(|e| e.prompt.clone()),
file,
line,
commit: commit_info.hash,
timestamp: commit_info.timestamp,
message: commit_info.message,
})
}
pub async fn why_command(target: String) -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let provenance = ProvenanceLog::load(¤t_dir)?;
let info = lookup_why(&git_manager, &provenance, &target).await?;
let short = &info.commit[..7.min(info.commit.len())];
let location = match info.line {
Some(l) => format!("{}:{}", info.file, l),
None => info.file.clone(),
};
println!("File: {}", location);
println!("Commit: {} ({})", short, format_ts(info.timestamp));
println!("Message: {}", info.message.lines().next().unwrap_or(""));
match &info.operation {
Some(op) => println!("Operation: {}", op),
None => println!("Operation: (unrecorded)"),
}
match &info.agent_id {
Some(a) => println!("Agent: {}", a),
None => println!("Agent: (unrecorded)"),
}
match &info.prompt {
Some(p) => println!("Prompt: {}", p),
None => println!("Prompt: (not captured — save with --prompt to record intent)"),
}
Ok(())
}
fn format_ts(ts: i64) -> String {
let secs = ts.max(0) as u64;
let days = secs / 86400;
let time = secs % 86400;
let z = days as i64 + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!(
"{:04}-{:02}-{:02} {:02}:{:02}",
y,
m,
d,
time / 3600,
(time % 3600) / 60
)
}