"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPlanningResponse = extractPlanningResponse;
exports.extractAgentResponseText = extractAgentResponseText;
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const SEND_RESPONSE_TOOL = 'send_response';
function extractPlanningResponse(messages, artifacts) {
    let responseText = '';
    let planContent;
    for (const message of messages) {
        if (message.role !== mablApi_1.MessageRole.Model) {
            continue;
        }
        for (const part of message.parts ?? []) {
            responseText += extractFromToolCall(part);
            const toolOutputResult = extractFromToolOutput(part);
            responseText += toolOutputResult.text;
            if (!planContent && toolOutputResult.planContent) {
                planContent = toolOutputResult.planContent;
            }
        }
    }
    let testInformation;
    for (const artifact of artifacts ?? []) {
        if (artifact.name === 'test_information') {
            const value = getInlineArtifactValue(artifact);
            if (value) {
                testInformation = value;
            }
        }
        if (!planContent && artifact.name === 'agent_files') {
            const value = getInlineArtifactValue(artifact);
            if (value?.files?.['test-outline.md']) {
                planContent = value.files['test-outline.md'];
            }
        }
    }
    return { responseText: responseText.trim(), planContent, testInformation };
}
function extractAgentResponseText(messages) {
    return extractPlanningResponse(messages).responseText;
}
function extractFromToolCall(part) {
    if (part.type !== mablApi_1.MessagePartType.ToolCall || part.name !== SEND_RESPONSE_TOOL) {
        return '';
    }
    const message = part.input?.json?.message;
    return typeof message === 'string' ? message : '';
}
function extractFromToolOutput(part) {
    if (part.tool_name !== SEND_RESPONSE_TOOL || !part.output) {
        return { text: '', planContent: undefined };
    }
    let text = '';
    for (const item of part.output.content ?? []) {
        if (item.type === mablApi_1.ToolOutputContentItemType.Text && item.text) {
            text += item.text;
        }
    }
    let planContent;
    const outputRecord = part.output;
    const linkedArtifact = outputRecord.linked_artifact;
    if (linkedArtifact?.artifact_data?.value) {
        const value = linkedArtifact.artifact_data.value;
        planContent = typeof value === 'string' ? value : JSON.stringify(value, undefined, 2);
    }
    return { text, planContent };
}
function getInlineArtifactValue(artifact) {
    const inline = artifact;
    return inline.artifact_data?.value;
}
