//! Stream event handling — processes `stream_event` payloads from the Claude Code CLI.

/// Handle a single unwrapped stream event (the inner `event` object from a `stream_event` JSON).
///
/// Routes `content_block_delta` text tokens to `token_tx`, thinking tokens to `thinking_tx`,
/// `content_block_start` tool-use names to `activity_tx`, and error messages back to `token_tx`.
pub(super) fn handle_stream_event(
    event: &serde_json::Value,
    token_tx: &tokio::sync::mpsc::UnboundedSender<String>,
    thinking_tx: &tokio::sync::mpsc::UnboundedSender<String>,
    activity_tx: &tokio::sync::mpsc::UnboundedSender<String>,
) {
    let event_type = event.get("type").and_then(|t| t.as_str()).unwrap_or("");

    match event_type {
        "content_block_start" => {
            if let Some(cb) = event.get("content_block")
                && cb.get("type").and_then(|t| t.as_str()) == Some("tool_use")
                && let Some(name) = cb.get("name").and_then(|n| n.as_str())
            {
                let _ = activity_tx.send(name.to_string());
            }
        }
        // Text content streaming — only text_delta, not input_json_delta (tool args)
        "content_block_delta" => {
            if let Some(delta) = event.get("delta") {
                let delta_type = delta.get("type").and_then(|t| t.as_str()).unwrap_or("");
                match delta_type {
                    "text_delta" => {
                        if let Some(text) = delta.get("text").and_then(|t| t.as_str()) {
                            let _ = token_tx.send(text.to_string());
                        }
                    }
                    "thinking_delta" => {
                        if let Some(thinking) = delta.get("thinking").and_then(|t| t.as_str()) {
                            let _ = thinking_tx.send(thinking.to_string());
                        }
                    }
                    _ => {}
                }
            }
        }
        // Log errors via streaming display
        "error" => {
            if let Some(error) = event.get("error") {
                let msg = error
                    .get("message")
                    .and_then(|m| m.as_str())
                    .unwrap_or("unknown error");
                let _ = token_tx.send(format!("\n[error: {msg}]\n"));
            }
        }
        _ => {}
    }
}
