import { setSpanWithError, tracer } from "../../utils/tracer.js";
import { sanitizeToolsForAISDK } from "../tools/tool-wrapper.js";
import { getDefaultTools } from "../tools/default-tools.js";
import { getFunctionTools } from "../tools/function-tools.js";
import { getMcpTools } from "../tools/mcp-tools.js";
import { getRelationTools } from "../tools/relation-tools.js";
import { buildSystemPrompt } from "./system-prompt.js";
import { SpanStatusCode } from "@opentelemetry/api";

//#region src/domains/run/agents/generation/tool-loading.ts
async function loadToolsAndPrompts(ctx, sessionId, streamRequestId, runtimeContext) {
	const [mcpToolsResult, functionTools, relationTools, defaultTools] = await tracer.startActiveSpan("agent.load_tools", { attributes: {
		"subAgent.name": ctx.config.name,
		"session.id": sessionId || "none"
	} }, async (childSpan) => {
		try {
			const result = await Promise.all([
				getMcpTools(ctx, sessionId, streamRequestId),
				getFunctionTools(ctx, sessionId, streamRequestId),
				Promise.resolve(getRelationTools(ctx, runtimeContext, sessionId)),
				getDefaultTools(ctx, streamRequestId)
			]);
			childSpan.setStatus({ code: SpanStatusCode.OK });
			return result;
		} catch (err) {
			setSpanWithError(childSpan, err instanceof Error ? err : new Error(String(err)));
			throw err;
		} finally {
			childSpan.end();
		}
	});
	const systemPromptResult = await buildSystemPrompt(ctx, runtimeContext, false, {
		mcpResult: mcpToolsResult,
		functionTools,
		relationTools
	});
	const { tools: mcpTools } = mcpToolsResult;
	const systemPrompt = systemPromptResult.prompt;
	const contextBreakdown = systemPromptResult.breakdown;
	return {
		systemPrompt,
		sanitizedTools: sanitizeToolsForAISDK({
			...mcpTools,
			...functionTools,
			...relationTools,
			...defaultTools
		}),
		contextBreakdown
	};
}

//#endregion
export { loadToolsAndPrompts };