use serde_json::Value;
use crate::canonical::{ContentKind, Delta, Event};
use crate::protocol::json::{nonempty, text_of, to_json_string};
use crate::protocol::synth::{next_index, open_text, open_thinking};
use crate::protocol::{DecodeState, OpenBlock};
pub(super) fn part_events(part: &Value, state: &mut DecodeState, out: &mut Vec<Event>) {
if let Some(t) = nonempty(&part["text"]) {
let (index, delta) = if part["thought"].as_bool() == Some(true) {
(
open_thinking(state, out),
Delta::ThinkingDelta(t.to_owned()),
)
} else {
(open_text(state, out), Delta::TextDelta(t.to_owned()))
};
out.push(Event::ContentDelta { index, delta });
}
if let Some(call) = part.get("functionCall").filter(|c| c.is_object()) {
let index = next_index(state);
let kind = ContentKind::ToolUse {
id: format!("call_{index}"), name: text_of(call, "name"),
};
state.open.insert(index, OpenBlock { kind: kind.clone() });
out.push(Event::ContentStart { index, kind });
out.push(Event::ContentDelta {
index,
delta: Delta::JsonDelta(to_json_string(&call["args"])),
});
if let Some(sig) = nonempty(&part["thoughtSignature"]) {
out.push(Event::ContentDelta {
index,
delta: Delta::SignatureDelta(sig.to_owned()),
});
}
}
}