"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFaxDocumentWithOCR = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const dataPoints_1 = require("./config/dataPoints");
const fields_1 = require("./config/fields");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
const validatePayloadAndCreateSdk_1 = require("../../lib/validatePayloadAndCreateSdk");
const validatePayloadAndCreateSdk_2 = require("../../../landingAi/lib/validatePayloadAndCreateSdk");
const client_1 = require("../../../landingAi/lib/api/client");
const lodash_1 = require("lodash");
exports.getFaxDocumentWithOCR = {
    key: 'getFaxDocumentWithOCR',
    category: extensions_core_1.Category.DOCUMENT_MANAGEMENT,
    title: 'Get fax document with OCR',
    description: 'Get fax document with WestFax and extract structured data with OCR',
    fields: config_1.fields,
    dataPoints: dataPoints_1.dataPoints,
    previewable: false,
    onActivityCreated: async (payload, onComplete, onError) => {
        const { fields, westFaxSdk } = await (0, validatePayloadAndCreateSdk_1.validatePayloadAndCreateSdk)({
            fieldsSchema: fields_1.FieldsValidationSchema,
            payload,
        });
        const activityEventLog = [];
        const response = await westFaxSdk.getFaxDocument({
            Cookies: false,
            FaxIds1: {
                Id: fields.faxId,
            },
            format: 'pdf',
        });
        if (!response.data.Success) {
            await onError({
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `Error getting fax document:\n${JSON.stringify(response.data, null, 2)}`,
                    }),
                ],
            });
            return;
        }
        if (response.data.Result.length === 0) {
            await onError({
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: 'No fax document found',
                    }),
                ],
            });
            return;
        }
        if (response.data.Result.length > 1) {
            await onError({
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: 'More than one fax document found',
                    }),
                ],
            });
            return;
        }
        const faxDocument = response.data.Result[0];
        if (faxDocument.FaxFiles[0].FileContents.length === 0) {
            activityEventLog.push((0, addEventLog_1.addActivityEventLog)({
                message: 'No fax file was found',
            }));
        }
        if (faxDocument.FaxFiles[0].FileContents.length > 1) {
            activityEventLog.push((0, addEventLog_1.addActivityEventLog)({
                message: 'More than 1 fax file was found, only storing the first one',
            }));
        }
        const landingAiSdk = new client_1.LandingAiApiClient({
            baseUrl: validatePayloadAndCreateSdk_2.baseUrl,
            apiKey: fields.ocrProviderApiKey,
        });
        const { data } = await landingAiSdk.agenticDocumentAnalysis({
            input: {
                body: {
                    image: null,
                    pdf: faxDocument.FaxFiles[0].FileContents, // Base64 encoded pdf file
                    include_marginalia: true,
                    include_metadata_in_markdown: true,
                    fields_schema: !(0, lodash_1.isNil)(fields.fieldsSchema)
                        ? JSON.stringify(fields.fieldsSchema)
                        : null,
                },
            },
            mode: 'base64EncodedFile',
        });
        if (data.errors.length > 0) {
            await onError({
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `OCR Error:\n${JSON.stringify(data.errors, null, 2)}`,
                    }),
                ],
            });
            return;
        }
        if (data.extraction_error !== null) {
            await onError({
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `OCR Error:\n${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,
                direction: faxDocument.Direction,
                date: faxDocument.Date,
                status: faxDocument.Status,
                format: faxDocument.Format,
                pageCount: String(faxDocument.PageCount),
            },
        });
    },
};
//# sourceMappingURL=getFaxDocumentWithOCR.js.map