import { DIALOG_TYPES } from "../dialogs/agentDialogTypes";
export function buildQuestionnaireDialogFromTranscript(input) {
    const { messages, pendingDialog, agentId } = input;
    if (pendingDialog.dialogType !== DIALOG_TYPES.QUESTIONNAIRE ||
        !pendingDialog.callbackId) {
        return null;
    }
    const toolCall = findPendingQuestionnaireToolCall(messages);
    if (!toolCall) {
        return null;
    }
    const parsedArguments = parseJsonObject(toolCall.functionArguments);
    const parameterSource = parseJsonObject(parsedArguments?.parameters) ?? parsedArguments;
    const questions = Array.isArray(parameterSource?.questions)
        ? parameterSource.questions
        : null;
    if (!questions || questions.length === 0) {
        return null;
    }
    const { title: _title, description: _description, ...parameters } = parameterSource ?? {};
    return {
        request: {
            dialogType: DIALOG_TYPES.QUESTIONNAIRE,
            callbackId: pendingDialog.callbackId,
            agentId,
            toolCallId: toolCall.toolCallId,
            title: stringOrNull(parsedArguments?.title) ??
                pendingDialog.title ??
                "Questionnaire",
            description: stringOrNull(parsedArguments?.description) ?? undefined,
            parameters: {
                ...parameters,
                questions,
            },
        },
    };
}
function findPendingQuestionnaireToolCall(messages) {
    for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex--) {
        const toolCalls = messages[messageIndex]?.toolCalls ?? [];
        for (let toolIndex = toolCalls.length - 1; toolIndex >= 0; toolIndex--) {
            const toolCall = toolCalls[toolIndex];
            if (!toolCall)
                continue;
            if (normalizeToolName(toolCall.functionName) !== "ask-questionnaire") {
                continue;
            }
            if (toolCall.isCompleted ||
                toolCall.functionResult ||
                toolCall.functionError) {
                continue;
            }
            return toolCall;
        }
    }
    return null;
}
function normalizeToolName(functionName) {
    return (functionName || "")
        .replace(/\s*\((?:approved|rejected|pending approval)\)\s*$/i, "")
        .trim()
        .toLowerCase();
}
function parseJsonObject(value) {
    if (!value) {
        return null;
    }
    if (typeof value === "object" && !Array.isArray(value)) {
        return value;
    }
    if (typeof value !== "string") {
        return null;
    }
    try {
        const parsed = JSON.parse(value);
        return parsed && typeof parsed === "object" && !Array.isArray(parsed)
            ? parsed
            : null;
    }
    catch {
        return null;
    }
}
function stringOrNull(value) {
    return typeof value === "string" && value.trim() ? value : null;
}
//# sourceMappingURL=agentQuestionnaireTranscriptRecovery.js.map