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

use super::{common, ToolResult};

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EnvParams {
    pub file: Option<String>,
}

pub async fn execute(params: EnvParams) -> ToolResult {
    let root = envseal::ops::vault_root().map_err(|e| e.to_string())?;
    let cwd = std::env::current_dir().map_err(|e| e.to_string())?;
    let result = if let Some(file) = params.file {
        common::validate_bounded_string(&file, "file", common::MAX_STRING_LENGTH)?;
        let file_path = common::validate_path_within_cwd(&file, "file")?;
        common::open_readonly_nofollow(&file_path, "file")?;
        envseal::ops::check_envseal_file(&root, &file_path).map_err(|e| e.to_string())?
    } else {
        envseal::ops::env_dry_run(&root, &cwd).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, "present": true})).collect::<Vec<_>>(),
        "missing": result.missing.iter().map(|m| json!({"env_var": m.env_var, "secret_name": m.secret_name, "present": false})).collect::<Vec<_>>()
    }))
}
