export default function parseGrokStream(text) {
  const result = {
    conversationId: null,
    userChatItemId: null,
    agentChatItemId: null,
    message: "",
    reasoning: "",
    softStop: false,
    followUpSuggestions: [],
    webResults: [],
    citations: [],
    images: [],
    cards: [],
    requestEntities: null,
    responseEntities: null,
    chunks: [],
  };

  for (const line of String(text).split("\n")) {
    const trimmed = line.trim();
    if (!trimmed) continue;

    let obj;
    try {
      obj = JSON.parse(trimmed);
    } catch {
      continue;
    }
    result.chunks.push(obj);

    if (obj.conversationId && !obj.result) {
      result.conversationId = obj.conversationId;
      result.userChatItemId = obj.userChatItemId ?? result.userChatItemId;
      result.agentChatItemId = obj.agentChatItemId ?? result.agentChatItemId;
      continue;
    }

    const r = obj.result;
    if (!r) continue;

    if (r.responseChatItemId) result.agentChatItemId = r.responseChatItemId;
    if (r.isSoftStop) result.softStop = true;
    if (Array.isArray(r.followUpSuggestions)) {
      result.followUpSuggestions.push(...r.followUpSuggestions);
    }
    if (Array.isArray(r.citations)) result.citations.push(...r.citations);
    if (Array.isArray(r.webResults)) result.webResults.push(...r.webResults);
    if (Array.isArray(r.cards)) result.cards.push(...r.cards);
    if (r.requestEntities) result.requestEntities = r.requestEntities;
    if (r.responseEntities) result.responseEntities = r.responseEntities;

    const image = r.imageAttachment || r.attachment || r.generatedImage;
    if (image) result.images.push(image);

    if (typeof r.message === "string") {
      if (r.isThinking || r.messageTag === "header") {
        result.reasoning += r.message;
      } else if (r.messageTag === "final" || (!r.messageTag && r.message)) {
        result.message += r.message;
      }
    }
  }

  return result;
}
