"use strict";
/**
 * EMS File Parser v1.3.6
 *
 * Parses CCC ONE EMS export files to extract customer/vehicle data.
 * Supports .veh, .own, .clm, .ad1, .ad2 file formats.
 *
 * IMPORTANT: CCC ONE files contain multiple contacts:
 * - Vehicle Owner (OWNR_*) - Who owns the car being repaired
 * - Insured (INSD_*) - Who is on the insurance policy
 *
 * We ALWAYS prioritize Vehicle Owner because that's who the shop contacts.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractExcelData = extractExcelData;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const logger_1 = require("./logger");
/**
 * Parse a single EMS file and extract key-value pairs
 */
function parseEmsFile(filePath) {
    const data = new Map();
    try {
        const content = fs.readFileSync(filePath, 'utf-8');
        const lines = content.split(/\r?\n/);
        for (const line of lines) {
            // EMS format: KEY=VALUE or KEY:VALUE
            const match = line.match(/^([A-Z0-9_]+)[=:](.*)$/i);
            if (match) {
                const key = match[1].toUpperCase().trim();
                const value = match[2].trim();
                data.set(key, value);
            }
        }
    }
    catch (error) {
        (0, logger_1.log)(`Error parsing ${filePath}: ${error.message}`, 'WARN');
    }
    return data;
}
/**
 * Extract Excel row data from EMS files
 */
function extractExcelData(baseName, watchFolder) {
    try {
        const allData = new Map();
        // Common EMS file extensions (includes DBF address files)
        const extensions = ['.veh', '.own', '.clm', '.est', '.ins', '.ad1', '.ad2'];
        for (const ext of extensions) {
            const filePath = path.join(watchFolder, baseName + ext);
            if (fs.existsSync(filePath)) {
                const fileData = parseEmsFile(filePath);
                fileData.forEach((value, key) => {
                    if (!allData.has(key) || value) {
                        allData.set(key, value);
                    }
                });
            }
        }
        if (allData.size === 0) {
            (0, logger_1.log)(`No EMS data found for ${baseName}`, 'WARN');
            return null;
        }
        // Extract fields - try multiple possible field names
        const getValue = (...keys) => {
            for (const key of keys) {
                const value = allData.get(key.toUpperCase());
                if (value)
                    return value;
            }
            return '';
        };
        // Build Excel row data
        // PRIORITY: Vehicle Owner (OWNR_*) first, then Insured (INSD_*) as fallback
        const excelData = {
            customerName: getValue(
            // Priority 1: Vehicle Owner (OWNR_*) - this is who the shop contacts
            'OWNR_NAME', 'OWNR_FN', 'OWNER_NAME', 'OWNERNAME', 
            // Priority 2: Generic customer
            'CUSTOMER_NAME', 'CUSTOMERNAME', 'NAME', 
            // Priority 3: Insured (INSD_*) - fallback only
            'INSD_NAME', 'INSD_FN', 'INSURED_NAME', 'CLAIMANT_NAME', 'CLM_NAME'),
            phone: getValue(
            // Priority 1: Vehicle Owner phone
            'OWNR_PH1', 'OWNR_PHONE', 'OWNER_PHONE', 'OWNERPHONE', 
            // Priority 2: Generic phone
            'PHONE', 'PHONE_NUMBER', 'HOME_PHONE', 'MOBILE_PHONE', 'WORK_PHONE', 
            // Priority 3: Insured phone - fallback only
            'INSD_PH1', 'INSD_PHONE', 'CLM_PHONE'),
            email: getValue(
            // Priority 1: Vehicle Owner email
            'OWNR_EA', 'OWNR_EMAIL', 'OWNER_EMAIL', 'OWNEREMAIL', 
            // Priority 2: Generic email
            'EMAIL', 'EMAIL_ADDRESS', 'CUSTOMER_EMAIL', 
            // Priority 3: Insured email - fallback only
            'INSD_EA', 'INSD_EMAIL', 'CLM_EMAIL'),
            year: getValue('YEAR', 'VEH_YEAR', 'VEHICLE_YEAR', 'MODEL_YEAR', 'YR'),
            make: getValue('MAKE', 'VEH_MAKE', 'VEHICLE_MAKE', 'MANUFACTURER'),
            model: getValue('MODEL', 'VEH_MODEL', 'VEHICLE_MODEL'),
            vin: getValue('VIN', 'VEH_VIN', 'VEHICLE_VIN', 'VINNO', 'VIN_NUMBER'),
            color: getValue('COLOR', 'VEH_COLOR', 'VEHICLE_COLOR', 'EXT_COLOR', 'EXTERIOR_COLOR'),
            licensePlate: getValue('LICENSE', 'LICENSE_PLATE', 'PLATE', 'TAG', 'REG_NUMBER', 'LIC_PLATE', 'VEH_LICENSE'),
            insuranceCompany: getValue('INSURANCE', 'INSURANCE_COMPANY', 'INS_COMPANY', 'INSURER', 'CARRIER', 'INS_NAME', 'INSURANCE_NAME'),
            checkInDate: getValue('DATE', 'CHECK_IN_DATE', 'CHECKIN_DATE', 'RECEIVE_DATE', 'ARRIVAL_DATE', 'DATE_IN', 'RO_DATE') || new Date().toLocaleDateString(),
        };
        // Validate - need at least VIN or customer name
        if (!excelData.vin && !excelData.customerName) {
            (0, logger_1.log)(`No VIN or customer name found for ${baseName}`, 'WARN');
            return null;
        }
        // Generate VIN if missing (use baseName as fallback)
        if (!excelData.vin) {
            excelData.vin = `UNKNOWN-${baseName}`;
        }
        return excelData;
    }
    catch (error) {
        (0, logger_1.log)(`Error extracting Excel data for ${baseName}: ${error.message}`, 'ERROR');
        return null;
    }
}
//# sourceMappingURL=ems-parser.js.map