use crate::agent::persistence::types::{
    AgentRealtime, AgentRuntime, AgentStreamEvent,
};
use crate::error::AiResult;

pub async fn publish_event(
    runtime: &AgentRuntime,
    _realtime: Option<&AgentRealtime>,
    event: &AgentStreamEvent,
) -> AiResult<()> {
    let Some(tx) = &runtime.tx else {
        return Ok(());
    };

    let payload = match serde_json::to_string(event) {
        Ok(p) => p,
        Err(error) => {
            tracing::warn!(error = %error, "agent sse: serialize failed");
            return Ok(());
        }
    };

    if tx.send(payload).is_err() {
        tracing::debug!("agent sse: mpsc send failed, client disconnected");
    }

    Ok(())
}

impl AgentRuntime {
    pub async fn publish(
        &self,
        realtime: Option<&AgentRealtime>,
        event: &AgentStreamEvent,
    ) -> AiResult<()> {
        publish_event(self, realtime, event).await
    }
}
