import type { AgentStatus, FlueConversationMessage } from "@flue/react";

export const stripThinkingMarkup = (text: string): string => {
  const withoutCompletedBlocks = text.replaceAll(
    /<think>[\s\S]*?<\/think>/giu,
    ""
  );
  const openTagIndex = withoutCompletedBlocks
    .toLowerCase()
    .lastIndexOf("<think>");
  const visibleText =
    openTagIndex === -1
      ? withoutCompletedBlocks
      : withoutCompletedBlocks.slice(0, openTagIndex);
  return visibleText.replaceAll("</think>", "").trimStart();
};

export const getMessageText = (message: FlueConversationMessage): string =>
  stripThinkingMarkup(
    message.parts
      .filter((part) => part.type === "text")
      .map((part) => part.text)
      .join("\n")
  );

export const isMessageStreaming = (message: FlueConversationMessage): boolean =>
  message.parts.some((part) => {
    if (part.type === "dynamic-tool") {
      return part.state === "input-available";
    }
    return (
      (part.type === "text" || part.type === "reasoning") &&
      part.state === "streaming"
    );
  });

export const getStatusDotClass = (status: AgentStatus): string => {
  if (status === "error") {
    return "bg-destructive";
  }
  if (status === "connecting") {
    return "bg-amber-500";
  }
  return "bg-emerald-500";
};
