use crate::layer0::vocabulary_types::{TYPE_URI_CLM_TYPE};
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::cpn::mcard_token::{check_type_expr, PlaceMCard, TokenMCard};
use crate::domain::BailVerdict;
pub const VIRTUAL_BOTTOM: &str = "__bot__";
pub const VIRTUAL_TOP: &str = "__top__";
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum PlaceRole {
InitialBottom,
Intermediate,
Exception,
TerminalTop,
}
impl PlaceRole {
pub fn as_str(&self) -> &'static str {
match self {
Self::InitialBottom => "InitialBottom",
Self::Intermediate => "Intermediate",
Self::Exception => "Exception",
Self::TerminalTop => "TerminalTop",
}
}
}
fn normalize_type_uri(type_uri: Option<&str>, fallback_expr: &str) -> String {
let Some(raw) = type_uri else {
return fallback_expr.to_string();
};
let cleaned = raw.trim();
let suffix_opt = cleaned
.strip_prefix(crate::layer0::vocabulary::HANDLE_CLM_TYPES)
.or_else(|| cleaned.strip_prefix(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE));
if let Some(suffix) = suffix_opt {
let low = suffix.trim().to_lowercase();
return match low.as_str() {
"any" => "any".to_string(),
"int" | "integer" => "int".to_string(),
"str" | "string" => "str".to_string(),
"structured" | "dict" => "structured".to_string(),
"exception-token" | "exception" => "exception".to_string(),
_ => low,
};
}
cleaned.to_string()
}
pub fn format_canonical_type_uri(type_expr: &str) -> String {
let normalized = normalize_type_uri(Some(type_expr), type_expr);
if normalized.starts_with(crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE) {
normalized
} else {
format!("{TYPE_URI_CLM_TYPE}{normalized}")
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlaceTypeBinding {
pub place: PlaceMCard,
pub role: PlaceRole,
pub type_uri: Option<String>,
pub required_identity_prefix: Option<String>,
}
impl PlaceTypeBinding {
pub fn new(
place: PlaceMCard,
role: PlaceRole,
type_uri: Option<String>,
required_identity_prefix: Option<String>,
) -> Self {
Self { place, role, type_uri, required_identity_prefix }
}
pub fn effective_type_expr(&self) -> String {
normalize_type_uri(self.type_uri.as_deref(), &self.place.type_expr)
}
pub fn validate_token(
&self,
token: &TokenMCard,
author_did: Option<&str>,
current_occupancy: usize,
) -> BailVerdict {
if !token.verify() {
return BailVerdict::Bail {
reason: format!("Token '{}' failed MCardRecord verification", token.token_id),
invariant_code: "INV-508-VERIFY".to_string(),
context_dump: json!({ "token_id": token.token_id }),
};
}
if let Some(prefix) = &self.required_identity_prefix {
let ok = author_did.is_some_and(|did| did.starts_with(prefix));
if !ok {
return BailVerdict::Bail {
reason: format!("MISU Meet Law (verifyIdentity ⊓ φ) failed on place '{}'", self.place.place_id),
invariant_code: "INV-508-MISU".to_string(),
context_dump: json!({ "place_id": self.place.place_id, "expected_prefix": prefix }),
};
}
}
if let Some(cap) = self.place.capacity {
if current_occupancy >= cap {
return BailVerdict::Bail {
reason: format!("Place '{}' capacity {} exceeded", self.place.place_id, cap),
invariant_code: "INV-508-CAP".to_string(),
context_dump: json!({ "place_id": self.place.place_id, "capacity": cap }),
};
}
}
let eff = self.effective_type_expr();
if !check_type_expr(&token.payload, &token.color_type, &eff) {
return BailVerdict::Bail {
reason: format!(
"Token '{}' (color '{}') rejected by place '{}' type guard '{}'",
token.token_id, token.color_type, self.place.place_id, eff
),
invariant_code: "INV-508-TYPE".to_string(),
context_dump: json!({ "place_id": self.place.place_id, "expected": eff, "actual": token.color_type }),
};
}
self.place.evaluate_guard(token, current_occupancy)
}
}