"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.medicationFromImage = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const lib_1 = require("../../lib");
const config_1 = require("./config");
const api_1 = require("../../lib/api");
const medicationExtractorApi_1 = require("../../lib/api/medicationExtractorApi");
const lodash_1 = require("lodash");
exports.medicationFromImage = {
    key: 'medicationFromImage',
    category: extensions_core_1.Category.WORKFLOW,
    title: 'Extract medication from image (Beta)',
    description: 'Generates structured medication list from picture ',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        const { fields: { imageUrl }, pathway: { id: pathwayId }, activity: { id: activityId }, } = await (0, lib_1.validatePayloadAndCreateSdk)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        try {
            const medicationExtractorApi = new api_1.MedicationExtractorApi();
            const data = await medicationExtractorApi.extractMedicationFromImage({
                imageUrl,
                context: { pathwayId, activityId },
            });
            const medicationAsText = data.medications
                .map((medication) => {
                return Object.entries(medication)
                    .map(([key, value]) => {
                    return `${(0, lodash_1.startCase)(key)}: ${value}`;
                })
                    .join('\n');
            })
                .join('\n\n-------\n\n');
            await onComplete({
                data_points: {
                    data: JSON.stringify({
                        medications: data.medications,
                    }),
                    medicationAsText,
                },
            });
        }
        catch (error) {
            if (error instanceof medicationExtractorApi_1.FetchError) {
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: {
                                en: `${error.statusCode} (${error.statusText}): ${error.responseBody}`,
                            },
                            error: {
                                category: 'SERVER_ERROR',
                                message: `${error.statusCode} (${error.statusText}): ${error.responseBody}`,
                            },
                        },
                    ],
                });
                return;
            }
            // Other errors are handled in extensions-server
            throw error;
        }
    },
};
//# sourceMappingURL=medicationFromImage.js.map