use serde_json::Value;
use super::token_models::TokenMCard;
pub fn reify_pcard_descriptor(
descriptor: &Value,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<TokenMCard, String> {
let schema = descriptor.get("schema").and_then(|v| v.as_str()).unwrap_or("");
if schema != "clm://layer1/pcard_descriptor/v1" {
return Err(format!("Unsupported PCard descriptor schema: {schema}"));
}
if descriptor.get("closure").is_some() || descriptor.get("ambient_capability").is_some() {
return Err("Non-serializable closure or ambient capability rejected".to_string());
}
let id = descriptor.get("id").and_then(|v| v.as_str()).unwrap_or("pcard_0");
TokenMCard::from_payload(
descriptor.clone(),
"clm://layer1/pcard_descriptor/v1",
&format!("tok_desc_{id}"),
algorithm,
timestamp,
)
}
pub fn reflect_pcard_descriptor(token: &TokenMCard, registered_ops: &[&str]) -> Result<Value, String> {
if token.color_type != "clm://layer1/pcard_descriptor/v1" {
return Err(format!("Unsupported token color_type for descriptor reflection: {}", token.color_type));
}
let schema = token.payload.get("schema").and_then(|v| v.as_str()).unwrap_or("");
if schema != "clm://layer1/pcard_descriptor/v1" {
return Err(format!("Unsupported PCard descriptor schema: {schema}"));
}
let variant = token.payload.get("variant").and_then(|v| v.as_str()).unwrap_or("");
if variant == "dynamic" {
let op = token.payload.get("operation_id").and_then(|v| v.as_str()).unwrap_or("");
if !registered_ops.contains(&op) {
return Err(format!("Unregistered operation_id rejected: {op}"));
}
} else if variant != "primitive" && variant != "boolean" {
return Err(format!("Unsupported PCard variant: {variant}"));
}
Ok(token.payload.clone())
}