import { resolveGenerationResponse } from "../agent-types.js";
import { setupStreamParser } from "./stream-parser.js";

//#region src/domains/run/agents/streaming/stream-handler.ts
async function handleStreamGeneration(ctx, streamResult, sessionId, contextId, hasStructuredOutput) {
	const parser = setupStreamParser(ctx, sessionId, contextId);
	if (hasStructuredOutput) {
		for await (const delta of streamResult.partialOutputStream) if (delta) await parser.processObjectDelta(delta);
	} else await processStreamEvents(streamResult, parser);
	await parser.finalize();
	const resolved = await resolveGenerationResponse(streamResult);
	const collectedParts = parser.getCollectedParts();
	return {
		...resolved,
		...collectedParts.length > 0 && { formattedContent: { parts: collectedParts.map((part) => ({
			kind: part.kind,
			...part.kind === "text" && { text: part.text },
			...part.kind === "data" && { data: part.data }
		})) } }
	};
}
async function processStreamEvents(streamResult, parser) {
	for await (const event of streamResult.fullStream) switch (event.type) {
		case "text-delta":
			await parser.processTextChunk(event.text);
			break;
		case "tool-call":
			parser.markToolResult();
			break;
		case "tool-result":
			parser.markToolResult();
			break;
		case "finish":
			if (event.finishReason === "tool-calls") parser.markToolResult();
			break;
		case "error": {
			if (event.error instanceof Error) throw event.error;
			const errorMessage = event.error?.error?.message ?? JSON.stringify(event.error) ?? "Unknown streaming error";
			throw new Error(errorMessage);
		}
	}
}

//#endregion
export { handleStreamGeneration, processStreamEvents };