"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.summarizeForm = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const summarizeFormWithLLM_1 = require("../../lib/summarizeFormWithLLM");
const detectLanguageWithLLM_1 = require("../../lib/detectLanguageWithLLM");
const createOpenAIModel_1 = require("../../../../src/lib/llm/openai/createOpenAIModel");
const constants_1 = require("../../../../src/lib/llm/openai/constants");
const config_1 = require("./config");
const getFormResponseText_1 = require("../../lib/getFormResponseText");
const awell_1 = require("../../../../src/lib/awell");
const utils_1 = require("../../../../src/utils");
const getCareFlowDetails_1 = require("../../lib/getCareFlowDetails");
const lodash_1 = require("lodash");
/**
 * Awell Action: Form Summarization
 *
 * Takes form responses and preferences as input, uses LLM to:
 * 1. Generate a concise summary in specified format and language
 * 2. Includes appropriate disclaimer
 *
 * Supports configurable scope (Step or Track) and form selection (Latest or All),
 * matching the behavior of the listFormAnswers action.
 *
 * @returns HTML-formatted summary
 */
exports.summarizeForm = {
    key: 'summarizeForm',
    category: extensions_core_1.Category.WORKFLOW,
    title: 'Summarize Form',
    description: 'Summarize form responses with AI. Defaults to the latest form in the current step, but can summarize all forms in the step or across the track.',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        // 1. Validate input fields
        const { scope, formSelection, summaryFormat, language, additionalInstructions, } = config_1.FieldsValidationSchema.parse(payload.fields);
        // 2. Initialize OpenAI model with metadata
        const { model, metadata, callbacks } = await (0, createOpenAIModel_1.createOpenAIModel)({
            settings: {}, // we use built-in API key for OpenAI
            helpers,
            payload,
            modelType: constants_1.OPENAI_MODELS.GPT4o,
            hideDataForTracing: true, // Hide input and output data when tracing
        });
        const awellSdk = await helpers.awellSdk();
        // Get care flow details for the disclaimer
        const careFlowDetails = await (0, getCareFlowDetails_1.getCareFlowDetails)(awellSdk, payload.pathway.id);
        // 3. Get form data based on scope and formSelection
        let formData;
        if (scope === 'Step') {
            if (formSelection === 'Latest') {
                // Single latest form in step (original behavior)
                const { formDefinition, formResponse } = await (0, awell_1.getLatestFormInCurrentStep)({
                    awellSdk,
                    pathwayId: payload.pathway.id,
                    activityId: payload.activity.id,
                });
                const { result } = (0, getFormResponseText_1.getFormResponseText)({
                    formDefinition,
                    formResponse,
                });
                formData = result;
            }
            else {
                // All forms in step
                const formsData = await (0, awell_1.getAllFormsInCurrentStep)({
                    awellSdk,
                    pathwayId: payload.pathway.id,
                    activityId: payload.activity.id,
                });
                const { result } = (0, getFormResponseText_1.getResponsesForAllForms)({ formsData });
                formData = result;
            }
        }
        else {
            // scope === 'Track'
            const allFormsInTrack = await (0, awell_1.getFormsInTrack)({
                awellSdk,
                pathwayId: payload.pathway.id,
                activityId: payload.activity.id,
            });
            if (formSelection === 'Latest') {
                // Latest form in track
                if (allFormsInTrack.length === 0) {
                    formData = '';
                }
                else {
                    const latestForm = allFormsInTrack[allFormsInTrack.length - 1];
                    const { result } = (0, getFormResponseText_1.getFormResponseText)({
                        formDefinition: latestForm.formDefinition,
                        formResponse: latestForm.formResponse,
                    });
                    formData = result;
                }
            }
            else {
                // All forms in track
                const { result } = (0, getFormResponseText_1.getResponsesForAllForms)({
                    formsData: allFormsInTrack,
                });
                formData = result;
            }
        }
        if (formData === '') {
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: {
                            en: `No completed form found in the current ${scope.toLowerCase()}`,
                        },
                        error: {
                            category: 'WRONG_INPUT',
                            message: `No completed form found in the current ${scope.toLowerCase()}`,
                        },
                    },
                ],
            });
            return;
        }
        // Create disclaimer message based on version availability
        let disclaimerMessage = '';
        if (!(0, lodash_1.isNil)(careFlowDetails.version)) {
            disclaimerMessage = `**Important Notice:** The content provided is an AI-generated summary of form responses of version ${careFlowDetails.version} of Care Flow "${careFlowDetails.title}" (ID: ${payload.pathway.id}).`;
        }
        else {
            disclaimerMessage = `**Important Notice:** The content provided is an AI-generated summary of form responses of Care Flow "${careFlowDetails.title}" (ID: ${payload.pathway.id}).`;
        }
        let summaryLanguage = language;
        if (language === 'Default') {
            try {
                summaryLanguage = await (0, detectLanguageWithLLM_1.detectLanguageWithLLM)({
                    model,
                    text: formData,
                    metadata,
                    callbacks,
                });
            }
            catch (error) {
                // If language detection fails, keep using 'Default'
                summaryLanguage = 'Default';
            }
        }
        // 4. Generate summary
        const summary = await (0, summarizeFormWithLLM_1.summarizeFormWithLLM)({
            model,
            formData,
            summaryFormat,
            language: summaryLanguage,
            disclaimerMessage,
            additionalInstructions,
            metadata,
            callbacks,
        });
        // 5. Format and return results
        const htmlSummary = await (0, utils_1.markdownToHtml)(summary);
        await onComplete({
            data_points: {
                summary: htmlSummary,
            },
        });
    },
};
//# sourceMappingURL=summarizeForm.js.map