use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use schemars::schema_for;
fn write_schema_to_stdout(schema_json: &str) -> Result<(), crate::error::Error> {
io::stdout()
.write_all(schema_json.as_bytes())
.map_err(crate::error::Error::Io)
}
fn write_schema_to_file(path: &Path, schema_json: &str) -> Result<(), crate::error::Error> {
fs::write(path, schema_json).map_err(|e| {
crate::error::Error::Io(io::Error::other(format!(
"Failed to write schema to {}: {e}",
path.display()
)))
})
}
pub fn generate_schema(output: Option<&PathBuf>) -> crate::error::Result<()> {
let schema = schema_for!(crate::config::ConfigFile);
let schema_json =
serde_json::to_string_pretty(&schema).map_err(|e| crate::error::Error::Config {
message: format!("Failed to serialize JSON schema: {e}"),
})?;
output.map_or_else(
|| write_schema_to_stdout(&schema_json),
|path| write_schema_to_file(path, &schema_json),
)
}