"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 SRFax and extract structured data with OCR',
    fields: config_1.fields,
    dataPoints: dataPoints_1.dataPoints,
    previewable: true,
    onActivityCreated: async (payload, onComplete, onError) => {
        const { fields, srfaxSdk } = await (0, validatePayloadAndCreateSdk_1.validatePayloadAndCreateSdk)({
            fieldsSchema: fields_1.FieldsValidationSchema,
            payload,
        });
        const activityEventLog = [];
        const retrieve = await srfaxSdk.retrieveFax({
            faxDetailsId: fields.faxId,
            direction: 'IN',
        });
        if (retrieve.status !== 'Success' || !retrieve.result) {
            await onError({
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `Error getting fax document:\n${JSON.stringify(retrieve.raw, null, 2)}`,
                    }),
                ],
            });
            return;
        }
        let direction = 'IN';
        let date = undefined;
        let pageCount = undefined;
        let status = undefined;
        const format = 'PDF';
        try {
            const inbox = await srfaxSdk.getFaxInboxAll();
            if (inbox.status === 'Success' && Array.isArray(inbox.result)) {
                const match = inbox.result.find((i) => {
                    if (typeof (i === null || i === void 0 ? void 0 : i.FileName) === 'string' && i.FileName.includes('|')) {
                        const id = i.FileName.split('|')[1];
                        return id === fields.faxId;
                    }
                    return false;
                });
                if (match) {
                    date = match.Date;
                    pageCount = String(match.Pages);
                    status = match.ReceiveStatus;
                }
            }
        }
        catch (_e) { }
        if (retrieve.result.length === 0) {
            activityEventLog.push((0, addEventLog_1.addActivityEventLog)({
                message: 'No fax file was found',
            }));
        }
        const landingAiSdk = new client_1.LandingAiApiClient({
            baseUrl: validatePayloadAndCreateSdk_2.baseUrl,
            apiKey: fields.ocrProviderApiKey,
        });
        const { data } = await landingAiSdk.agenticDocumentAnalysis({
            input: {
                body: {
                    image: null,
                    pdf: retrieve.result,
                    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,
                date,
                status,
                format,
                pageCount,
            },
        });
    },
};
//# sourceMappingURL=getFaxDocumentWithOCR.js.map