use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::domain::{CordisCoeffects, DynamicPCard};
use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
use crate::types::ContentHash;
use super::token_models::{qualified_record_hash, record_from_canonical_json, TokenMCard};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransitionMCard {
pub card: MCardRecord,
pub transition_id: String,
pub input_places: Vec<String>,
pub output_places: Vec<String>,
pub domain_type: String,
pub codomain_type: String,
pub coeffects: BTreeMap<String, String>,
pub operation_expr: String,
}
impl TransitionMCard {
pub fn default_coeffect_map() -> BTreeMap<String, String> {
let mut m = BTreeMap::new();
for axis in ["filesystem", "network", "random", "sqlite", "time"] {
m.insert(axis.to_string(), "none".to_string());
}
m
}
pub fn create(
transition_id: &str,
input_places: Vec<String>,
output_places: Vec<String>,
domain_type: &str,
codomain_type: &str,
coeffects: Option<BTreeMap<String, String>>,
operation_expr: &str,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<Self, String> {
let coeff = coeffects.unwrap_or_else(Self::default_coeffect_map);
let envelope = json!({
"codomain_type": codomain_type,
"coeffects": coeff,
"domain_type": domain_type,
"input_places": input_places,
"kind": "transition_mcard",
"operation_expr": operation_expr,
"output_places": output_places,
"transition_id": transition_id,
});
let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
Ok(Self {
card,
transition_id: transition_id.to_string(),
input_places,
output_places,
domain_type: domain_type.to_string(),
codomain_type: codomain_type.to_string(),
coeffects: coeff,
operation_expr: operation_expr.to_string(),
})
}
pub fn hash(&self) -> &str {
&self.card.hash
}
pub fn qualified_hash(&self) -> String {
qualified_record_hash(&self.card)
}
pub fn verify(&self) -> bool {
matches!(verify_record(&self.card), RecordVerification::DeclaredOk { .. })
}
pub fn as_dynamic_pcard(&self) -> DynamicPCard {
let services: Vec<String> = self
.coeffects
.iter()
.filter(|(_, mode)| mode.as_str() != "none")
.map(|(k, v)| format!("{k}:{v}"))
.collect();
DynamicPCard {
id: self.transition_id.clone(),
code_hash: ContentHash::parse(&self.card.hash)
.unwrap_or_else(|_| ContentHash::compute(&self.card.content)),
source_uri: format!("mcard://{}", self.qualified_hash()),
coeffects: CordisCoeffects {
required_services: services,
input_schema_uri: Some(self.domain_type.clone()),
output_schema_uri: Some(self.codomain_type.clone()),
required_capabilities: Vec::new(),
},
signature: format!("{} -> {}", self.domain_type, self.codomain_type),
}
}
pub fn fire<F>(
&self,
input_tokens: &[TokenMCard],
transform: F,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<Vec<TokenMCard>, String>
where
F: Fn(&[Value]) -> Value,
{
let algo = algorithm.unwrap_or_else(|| {
if self.card.g_time.starts_with("sha256|") { "sha256" } else { "blake3" }
});
let raw_inputs: Vec<Value> = input_tokens.iter().map(|t| t.payload.clone()).collect();
let out_payload = transform(&raw_inputs);
let out_count = self.output_places.len().max(1);
let mut produced = Vec::with_capacity(out_count);
for idx in 0..out_count {
produced.push(TokenMCard::from_payload(
out_payload.clone(),
&self.codomain_type,
&format!("{}_out_{idx}", self.transition_id),
Some(algo),
timestamp,
)?);
}
Ok(produced)
}
}