//! MCP tool for the on-demand build-directory GC pass (story 1199).

use serde_json::json;

use crate::http::context::AppContext;

/// MCP tool handler for `gc` — runs a build-directory GC pass on demand and
/// returns bytes reclaimed, duration, and which directories were reclaimed
/// or skipped (raced/errored).
pub(crate) async fn tool_gc(ctx: &AppContext) -> Result<String, String> {
    let project_root = ctx.services.agents.get_project_root(&ctx.state)?;
    let report = crate::service::gc::io::run_gc_pass(&project_root).await;

    serde_json::to_string_pretty(&json!({
        "bytes_reclaimed": report.bytes_reclaimed,
        "reclaimed": report.reclaimed,
        "skipped": report.skipped,
        "duration_secs": report.duration.as_secs_f64(),
    }))
    .map_err(|e| format!("Serialization error: {e}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::test_helpers::test_ctx;

    #[tokio::test]
    async fn tool_gc_returns_zero_bytes_for_empty_project() {
        let tmp = tempfile::tempdir().unwrap();
        let ctx = test_ctx(tmp.path());
        let result = tool_gc(&ctx).await.expect("tool_gc must not fail");
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["bytes_reclaimed"].as_u64(), Some(0));
        assert!(parsed["reclaimed"].as_array().unwrap().is_empty());
    }
}
