use serde::Deserialize;
use serde_json::json;

use super::ToolResult;

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HealthParams {
    pub max_age_days: Option<u64>,
}

pub async fn execute(params: HealthParams) -> ToolResult {
    let max_age_days = params.max_age_days.map(|days| days.clamp(1, 3650));
    let vault = envseal::vault::Vault::open_default().map_err(|e| e.to_string())?;
    let report =
        envseal::secret_health::health_report(&vault, max_age_days).map_err(|e| e.to_string())?;

    let secrets = report
        .secrets
        .iter()
        .map(|secret| {
            let entropy_warnings: Vec<_> = secret
                .entropy_warnings
                .iter()
                .map(|s| {
                    json!({
                        "id": s.id.as_str(),
                        "category": s.category.as_str(),
                        "severity": s.severity.as_str(),
                        "label": s.label,
                        "detail": s.detail,
                        "mitigation": s.mitigation,
                    })
                })
                .collect();
            json!({
                "name": secret.name,
                "needs_rotation": secret.needs_rotation,
                "entropy_warnings": entropy_warnings,
            })
        })
        .collect::<Vec<_>>();

    Ok(json!({
        "total": report.total,
        "stale_count": report.stale_count,
        "weak_count": report.weak_count,
        "healthy": report.is_healthy(),
        "secrets": secrets
    }))
}
