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

use super::{common, ToolResult};

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CheckParams {
    #[serde(default = "default_file")]
    pub file: String,
}

fn default_file() -> String {
    ".envseal".to_string()
}

pub async fn execute(params: CheckParams) -> ToolResult {
    common::validate_bounded_string(&params.file, "file", common::MAX_STRING_LENGTH)?;
    let root = envseal::ops::vault_root().map_err(|e| e.to_string())?;
    let file = common::validate_path_within_cwd(&params.file, "file")?;
    common::open_readonly_nofollow(&file, "file")?;
    let result = envseal::ops::check_envseal_file(&root, &file).map_err(|e| e.to_string())?;

    Ok(json!({
        "satisfied": result.satisfied.iter().map(|m| json!({"env_var": m.env_var, "secret_name": m.secret_name})).collect::<Vec<_>>(),
        "missing": result.missing.iter().map(|m| json!({"env_var": m.env_var, "secret_name": m.secret_name})).collect::<Vec<_>>()
    }))
}
