import type { AssistantBlock, ContentBlock } from "../types/message";
import { extractContent } from "./toolCall";

/** Extract thinking/text blocks in RPC order (toolCall blocks excluded — CLI renders those separately). */
export function extractAssistantBlocks(content: string | ContentBlock[] | undefined): AssistantBlock[] {
	if (!content) return [];
	if (typeof content === "string") {
		const text = content.trim();
		return text ? [{ type: "text", content: text }] : [];
	}
	if (!Array.isArray(content)) return [];

	const blocks: AssistantBlock[] = [];
	for (const block of content) {
		if (block.type === "thinking") {
			const thinking = (block.thinking ?? "").trim();
			if (thinking) blocks.push({ type: "thinking", content: thinking });
		} else if (block.type === "text") {
			const text = (block.text ?? "").trim();
			if (text) blocks.push({ type: "text", content: text });
		}
	}
	return blocks;
}

export function assistantPlainText(blocks: AssistantBlock[]): string {
	return blocks
		.filter((b) => b.type === "text")
		.map((b) => b.content)
		.join("\n\n");
}

export function hasThinkingBlock(blocks: AssistantBlock[]): boolean {
	return blocks.some((b) => b.type === "thinking" && b.content.trim());
}

export function hasTextBlock(blocks: AssistantBlock[]): boolean {
	return blocks.some((b) => b.type === "text" && b.content.trim());
}

/** Resolve display blocks from a chat message (supports legacy thinking role). */
export function resolveAssistantBlocks(message: {
	role: string;
	content: string;
	blocks?: AssistantBlock[];
}): AssistantBlock[] {
	if (message.blocks?.length) return message.blocks;
	if (message.role === "thinking" && message.content.trim()) {
		return [{ type: "thinking", content: message.content.trim() }];
	}
	if (message.role === "assistant" && message.content.trim()) {
		return [{ type: "text", content: message.content.trim() }];
	}
	return [];
}

export function legacyContentToBlocks(content: string | ContentBlock[] | undefined): AssistantBlock[] {
	if (Array.isArray(content)) return extractAssistantBlocks(content);
	const text = extractContent(content);
	return text ? [{ type: "text", content: text }] : [];
}
