import type { ChatMessage, SessionHistoryPayload } from "../types/message";
import { nextMessageId } from "./format";
import {
	assistantPlainText,
	extractAssistantBlocks,
} from "./assistantBlocks";
import {
	extractContent,
	extractImages,
	formatToolCall,
	formatToolResult,
	getToolCalls,
	upsertToolCallMessage,
} from "./toolCall";

function appendAssistantTurn(m: { content?: string | unknown[] }, result: ChatMessage[]): void {
	const blocks = extractAssistantBlocks(m.content as string | undefined);
	const toolCalls = getToolCalls(m.content as string | undefined);

	if (blocks.length > 0) {
		result.push({
			id: nextMessageId(),
			role: "assistant",
			blocks,
			content: assistantPlainText(blocks),
		});
	}

	for (const tc of toolCalls) {
		const tid = tc.toolCallId || tc.id;
		const tidStr = tid ? String(tid) : undefined;
		upsertToolCallMessage(result, {
			id: tidStr ? `tool-${tidStr}` : nextMessageId(),
			role: "tool_call",
			content: formatToolCall(tc),
			toolCallId: tidStr,
		});
	}
}

export function buildHistoryMessages(payload: SessionHistoryPayload): ChatMessage[] {
	const result: ChatMessage[] = [];
	for (const m of payload.messages || []) {
		if (m.role === "user") {
			const text = extractContent(m.content);
			const images = extractImages(m.content);
			if (text || images.length) {
				result.push({
					id: nextMessageId(),
					role: "user",
					content: text,
					...(images.length ? { images } : {}),
				});
			}
		} else if (m.role === "assistant") {
			appendAssistantTurn(m, result);
		} else if (m.role === "toolResult" || m.role === "tool") {
			const text = formatToolResult({ content: m.content });
			if (text.trim()) {
				const tid = m.toolCallId ? String(m.toolCallId) : undefined;
				upsertToolCallMessage(result, {
					id: tid ? `tool-${tid}` : nextMessageId(),
					role: "tool_call",
					content: `✅ tool\n${text}`,
					toolCallId: tid,
				});
			}
		} else if (m.role === "bashExecution") {
			const output = typeof m.output === "string" ? m.output : "";
			result.push({
				id: nextMessageId(),
				role: "user",
				content: m.excludeFromContext ? `!!${m.command}` : `!${m.command}`,
			});
			result.push({
				id: nextMessageId(),
				role: "bash",
				content: output,
				bashCommand: m.command,
				bashExitCode: m.exitCode,
				bashExcludeFromContext: m.excludeFromContext,
			});
		} else if (m.role === "compactionSummary") {
			const summary = typeof m.summary === "string" ? m.summary : extractContent(m.content);
			if (summary.trim()) {
				result.push({ id: nextMessageId(), role: "compaction_summary", content: summary });
			}
		} else if (m.role === "branchSummary") {
			const summary = typeof m.summary === "string" ? m.summary : extractContent(m.content);
			if (summary.trim()) {
				result.push({ id: nextMessageId(), role: "branch_summary", content: summary });
			}
		}
	}
	return result;
}

export function extractThinkingFromMessage(m: { content?: string | unknown[] }): string {
	return extractAssistantBlocks(m.content as string | undefined)
		.filter((b) => b.type === "thinking")
		.map((b) => b.content)
		.join("\n\n");
}
