use anyhow::{anyhow, Context, Result};
use serde_json::{json, Value};
use std::time::Duration;
const HTTP_TIMEOUT: Duration = Duration::from_secs(10);
pub async fn handle_send_message(
to: String,
purpose: String,
content: String,
from: Option<String>,
) -> Result<()> {
let addr = trusty_common::read_daemon_addr("trusty-memory")
.context("read daemon address")?
.ok_or_else(|| {
anyhow!(
"trusty-memory daemon is not running — start it with \
`trusty-memory start` and retry"
)
})?;
let base = if addr.starts_with("http://") || addr.starts_with("https://") {
addr
} else {
format!("http://{addr}")
};
let url = format!("{base}/api/v1/messages");
let from_palace = match from {
Some(s) => s,
None => crate::messaging::cwd_palace_slug().context("derive --from palace from cwd")?,
};
let body = json!({
"to_palace": to,
"from_palace": from_palace,
"purpose": purpose,
"content": content,
});
let client = reqwest::Client::builder()
.timeout(HTTP_TIMEOUT)
.connect_timeout(HTTP_TIMEOUT)
.build()
.context("build http client")?;
let resp = client
.post(&url)
.json(&body)
.send()
.await
.context("POST /api/v1/messages")?;
let status = resp.status();
let text = resp.text().await.context("read response body")?;
if !status.is_success() {
return Err(anyhow!("daemon returned {status}: {text}"));
}
let pretty: Value = serde_json::from_str(&text).unwrap_or(Value::String(text));
println!("{}", serde_json::to_string_pretty(&pretty)?);
Ok(())
}