use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct GatewayRequest {
pub jsonrpc: String,
pub method: String,
#[serde(default)]
pub params: Option<Value>,
pub id: Value,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct GatewayError {
pub code: i32,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct GatewayResponse {
pub jsonrpc: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<GatewayError>,
pub id: Value,
}
pub struct GatewayRouter {
card_registry: HashMap<String, Value>,
}
impl Default for GatewayRouter {
fn default() -> Self {
Self::new()
}
}
impl GatewayRouter {
pub fn new() -> Self {
Self {
card_registry: HashMap::new(),
}
}
pub fn register_card(&mut self, hash: &str, content: Value) {
self.card_registry.insert(hash.to_string(), content);
}
pub fn dispatch(&self, request: &GatewayRequest) -> GatewayResponse {
if request.jsonrpc != "2.0" {
return GatewayResponse {
jsonrpc: "2.0".to_string(),
result: None,
error: Some(GatewayError {
code: -32600,
message: "Invalid Request: jsonrpc must be '2.0'".to_string(),
data: None,
}),
id: request.id.clone(),
};
}
match request.method.as_str() {
"clm.status" => GatewayResponse {
jsonrpc: "2.0".to_string(),
result: Some(serde_json::json!({
"status": "ready",
"layers": [0, 1, 2, 3, 4, 5],
"registered_cards": self.card_registry.len()
})),
error: None,
id: request.id.clone(),
},
"clm.eval" => {
let expr = request
.params
.as_ref()
.and_then(|p| p.get("expression"))
.and_then(|e| e.as_str())
.unwrap_or("");
let hash = crate::layer0::hash::compute_blake3(expr.as_bytes());
GatewayResponse {
jsonrpc: "2.0".to_string(),
result: Some(serde_json::json!({
"evaluated": expr,
"content_hash": hash,
"success": true
})),
error: None,
id: request.id.clone(),
}
}
"clm.card_get" => {
let hash = request
.params
.as_ref()
.and_then(|p| p.get("hash"))
.and_then(|h| h.as_str())
.unwrap_or("");
if let Some(content) = self.card_registry.get(hash) {
GatewayResponse {
jsonrpc: "2.0".to_string(),
result: Some(content.clone()),
error: None,
id: request.id.clone(),
}
} else {
GatewayResponse {
jsonrpc: "2.0".to_string(),
result: None,
error: Some(GatewayError {
code: -32004,
message: format!("Card not found: {}", hash),
data: None,
}),
id: request.id.clone(),
}
}
}
_ => GatewayResponse {
jsonrpc: "2.0".to_string(),
result: None,
error: Some(GatewayError {
code: -32601,
message: format!("Method not found: {}", request.method),
data: None,
}),
id: request.id.clone(),
},
}
}
}