"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.documentExtraction = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const validatePayloadAndCreateSdk_1 = require("../../lib/validatePayloadAndCreateSdk");
const config_1 = require("./config");
const lodash_1 = require("lodash");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
exports.documentExtraction = {
    key: 'documentExtraction',
    category: extensions_core_1.Category.DOCUMENT_MANAGEMENT,
    title: 'Document extraction',
    description: 'Extract structured data from documents and images',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        const { fields, landingAiSdk } = await (0, validatePayloadAndCreateSdk_1.validatePayloadAndCreateSdk)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        const { data } = await landingAiSdk.agenticDocumentAnalysis({
            input: {
                body: {
                    image: fields.fileType === 'image' ? fields.fileUrl : null,
                    pdf: fields.fileType === 'pdf' ? fields.fileUrl : null,
                    include_marginalia: true,
                    include_metadata_in_markdown: true,
                    fields_schema: !(0, lodash_1.isNil)(fields.fieldsSchema)
                        ? JSON.stringify(fields.fieldsSchema)
                        : null,
                },
            },
            mode: 'remoteFile',
        });
        if (data.errors.length > 0) {
            await onError({
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: JSON.stringify(data.errors, null, 2),
                    }),
                ],
            });
            return;
        }
        if (data.extraction_error !== null) {
            await onError({
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: data.extraction_error,
                    }),
                ],
            });
            return;
        }
        await onComplete({
            data_points: {
                markdown: data.data.markdown,
                chunks: JSON.stringify(data.data.chunks),
                extractedDataBasedOnSchema: !(0, lodash_1.isNil)(data.data.extracted_schema)
                    ? JSON.stringify(data.data.extracted_schema)
                    : undefined,
                extractedMetadata: !(0, lodash_1.isNil)(data.data.extraction_metadata)
                    ? JSON.stringify(data.data.extraction_metadata)
                    : undefined,
            },
        });
    },
};
//# sourceMappingURL=documentExtraction.js.map