"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.summarizeTrackOutcome = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const utils_1 = require("../../../../src/utils");
const summarizeTrackOutcomeWithLLM_1 = require("./lib/summarizeTrackOutcomeWithLLM");
const openai_1 = require("../../../../src/lib/llm/openai");
const constants_1 = require("../../../../src/lib/llm/openai/constants");
const index_1 = require("../../lib/getTrackData/index");
const getCareFlowDetails_1 = require("../../lib/getCareFlowDetails");
const lodash_1 = require("lodash");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
exports.summarizeTrackOutcome = {
    key: 'summarizeTrackOutcome',
    category: extensions_core_1.Category.WORKFLOW,
    title: 'Summarize Track Outcome',
    description: 'Summarize the care flow track outcome and activities that led to the outcome',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        var _a, _b;
        // 1. Validate input fields
        const { instructions } = config_1.FieldsValidationSchema.parse(payload.fields);
        const pathway = payload.pathway;
        // 2. Initialize OpenAI model with metadata
        const { model, metadata, callbacks } = await (0, openai_1.createOpenAIModel)({
            settings: {}, // we use built-in API key for OpenAI
            helpers,
            payload,
            modelType: constants_1.OPENAI_MODELS.GPT4o,
            hideDataForTracing: false, // IMPORTANT: set to true if there is a use case that might include PHI 
        });
        const awellSdk = await helpers.awellSdk();
        // Get activity details to find track_id
        const activityId = payload.activity.id;
        const activityDetails = await awellSdk.orchestration
            .query({
            activity: {
                __args: {
                    id: activityId,
                },
                success: true,
                activity: {
                    id: true,
                    context: {
                        track_id: true,
                    },
                },
            },
        });
        const currentActivity = (_a = activityDetails === null || activityDetails === void 0 ? void 0 : activityDetails.activity) === null || _a === void 0 ? void 0 : _a.activity;
        if ((0, lodash_1.isNil)(currentActivity) || !activityDetails.activity.success) {
            throw new Error(`Failed to fetch activity ${activityId}`);
        }
        const trackId = (_b = currentActivity.context) === null || _b === void 0 ? void 0 : _b.track_id;
        if ((0, lodash_1.isNil)(trackId) || trackId.trim() === '') {
            throw new Error('Could not find track ID for the current activity');
        }
        // 3. Get track data including forms and decision path
        const trackData = await (0, index_1.getTrackData)({
            awellSdk,
            pathwayId: pathway.id,
            trackId,
            currentActivityId: payload.activity.id,
        });
        // 4. Generate summary with LLM
        const summary = await (0, summarizeTrackOutcomeWithLLM_1.summarizeTrackOutcomeWithLLM)({
            model,
            trackActivities: JSON.stringify(trackData, null, 2),
            instructions,
            metadata,
            callbacks,
        });
        // Get care flow details for the disclaimer
        const careFlowDetails = await (0, getCareFlowDetails_1.getCareFlowDetails)(awellSdk, pathway.id);
        // Create version string if version is available
        let disclaimerMsg = '';
        if (!(0, lodash_1.isNil)(careFlowDetails.version)) {
            disclaimerMsg = `**Important Notice:** The content provided is an AI-generated summary of version ${careFlowDetails.version} of Care Flow "${careFlowDetails.title}" (ID: ${pathway.id}).`;
        }
        else {
            disclaimerMsg = `**Important Notice:** The content provided is an AI-generated summary of Care Flow "${careFlowDetails.title}" (ID: ${pathway.id}).`;
        }
        const htmlSummary = await (0, utils_1.markdownToHtml)(`${disclaimerMsg}\n\n${summary}`);
        await onComplete({
            data_points: {
                outcomeSummary: htmlSummary,
            },
            events: [
                (0, addEventLog_1.addActivityEventLog)({
                    message: `Processing track data with ${trackData.steps.length} steps and ${trackData.steps.flatMap(step => step.activities).length} total activities (hard limit is 500)`,
                }),
            ],
        });
    },
};
//# sourceMappingURL=summarizeTrackOutcome.js.map