use serde::Serialize;
use serde_json::json;
use crate::{Part, evidence_view, kernel::step, serve};
pub fn json<T: Serialize>(value: &T) -> Result<String, String> {
serde_json::to_string_pretty(value)
.map(|text| format!("{text}\n"))
.map_err(|e| e.to_string())
}
pub fn recognise_bytes(bytes: Vec<u8>) -> Result<String, String> {
let (output, _) = serve::recognise_bytes("<bytes>", bytes).map_err(|e| e.to_string())?;
json(&output)
}
pub fn recognise_file(path: &str) -> Result<String, String> {
let (output, _) = serve::recognise_file(path).map_err(|e| e.to_string())?;
json(&output)
}
pub fn evidence(part: &Part, framed: bool) -> Result<String, String> {
json(&evidence_view::document(part, framed).map_err(|e| e.to_string())?)
}
pub fn evidence_file(path: &str, framed: bool) -> Result<String, String> {
evidence(
&step::read_step_file(std::path::Path::new(path)).map_err(|e| e.to_string())?,
framed,
)
.map(|s| s.trim_end_matches('\n').to_owned())
}
pub fn anchor(part: &Part, face: usize) -> Result<String, String> {
if face >= part.faces.len() {
return Err(format!(
"face {face}: out of range ({} faces)",
part.faces.len()
));
}
let anchor = part.face_anchor(face).map_err(|e| e.to_string())?;
json(&json!({"face": face, "point": anchor.point, "uv": anchor.uv}))
}
pub fn fingerprints_file(path: &str) -> Result<String, String> {
let (output, _) = serve::recognise_file(path).map_err(|e| e.to_string())?;
serde_json::to_string_pretty(&output.recognition.fingerprints).map_err(|e| e.to_string())
}
pub fn capabilities() -> String {
serde_json::to_string_pretty(&json!({
"schema_version": "quiddity-rust/capabilities/1",
"package": {"name": "quiddity-rust", "version": env!("CARGO_PKG_VERSION")},
"recognition": crate::recognition::SCHEMA_VERSION,
"evidence": "quiddity-rust/evidence/1",
"fingerprints": crate::correspondence::fingerprint::FINGERPRINT_VERSION,
"inputs": ["step-path", "step-bytes"],
"functions": ["recognise", "evidence", "anchor", "fingerprints", "correspond", "capabilities"],
"pmi_json_import": cfg!(feature = "json-import"),
})).expect("capabilities serialise")
}