"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updatePatientTags = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
const client_1 = require("../../client");
const config_1 = require("./config");
const updateTags_1 = require("./updateTags");
const getTagsFromLLM_1 = require("./lib/getTagsFromLLM/getTagsFromLLM");
const createOpenAIModel_1 = require("../../../../src/lib/llm/openai/createOpenAIModel");
const constants_1 = require("../../../../src/lib/llm/openai/constants");
/**
 * Awell Action: Update Patient Tags
 *
 * Takes existing tags and instructions, uses LLM to:
 * 1. Generate updated list of tags
 * 2. Provide explanation for changes
 * 3. Update tags in Elation
 */
exports.updatePatientTags = {
    key: 'updatePatientTags',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: '✨ Update Patient Tags',
    description: 'Update patient tags in Elation.',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        // 1. Validate input and initialize API client
        const { instructions, patientId } = config_1.FieldsValidationSchema.parse(payload.fields);
        const api = (0, client_1.makeAPIClient)(payload.settings);
        // 2. Get existing tags
        const { tags } = await api.getPatient(patientId);
        const existingTags = tags !== null && tags !== void 0 ? tags : [];
        // 3. Initialize OpenAI model with metadata and callbacks
        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,
        });
        // 4. Generate updated tags
        const { validatedTags, explanation } = await (0, getTagsFromLLM_1.getTagsFromLLM)({
            model,
            existingTags,
            instructions,
            metadata,
            callbacks,
        });
        // 5. Update tags in Elation
        await (0, updateTags_1.updateElationTags)(api, patientId, validatedTags);
        // 6. Complete action with results
        await onComplete({
            data_points: {
                updatedTags: validatedTags.join(', '),
                explanation,
            },
            events: [
                (0, addEventLog_1.addActivityEventLog)({
                    message: `Previous patient tags: ${(existingTags === null || existingTags === void 0 ? void 0 : existingTags.length) > 0 ? existingTags === null || existingTags === void 0 ? void 0 : existingTags.join(', ') : 'No tags'}\nUpdated patient tags: ${validatedTags.join(', ')}\nExplanation: ${explanation}`,
                }),
            ],
        });
    },
};
//# sourceMappingURL=updatePatientTags.js.map