/**
 * Parser for SHT (Test Data Sheet) files
 *
 * Format:
 * DATAFORTH CORPORATION ...
 * ...
 * TEST DATA SHEET
 * ~~~~~~~~~~~~~~~~~~~~~~~
 * Date: MM-DD-YYYY
 * Model: MODEL_NUMBER
 * SN:    SERIAL-NUM
 *
 *        Parameter         Measured Value      Specification      Status
 * =======================  ===============   ====================  ======
 * Supply Current              12.0 mA               <  30 mA        PASS
 * ...
 */

const fs = require('fs');
const path = require('path');

/**
 * Parse an SHT file and extract the test record
 * @param {string} filePath - Path to the SHT file
 * @param {string} testStation - Test station identifier
 * @returns {Array} Array with single parsed record (or empty if parse fails)
 */
function parseShtFile(filePath, testStation = null) {
    const records = [];

    try {
        const content = fs.readFileSync(filePath, 'utf8');
        const lines = content.split('\n');

        let date = null;
        let model = null;
        let serial = null;
        let hasFailure = false;

        for (const line of lines) {
            // Extract date
            const dateMatch = line.match(/^Date:\s*(\d{2}-\d{2}-\d{4})/);
            if (dateMatch) {
                const [month, day, year] = dateMatch[1].split('-');
                date = `${year}-${month}-${day}`;
            }

            // Extract model
            const modelMatch = line.match(/^Model:\s*(\S+)/);
            if (modelMatch) {
                model = modelMatch[1].trim();
            }

            // Extract serial number
            const snMatch = line.match(/^SN:\s*(\S+)/);
            if (snMatch) {
                serial = snMatch[1].trim();
            }

            // Check for FAIL status
            if (/\bFAIL\b/i.test(line)) {
                hasFailure = true;
            }
        }

        if (date && model && serial) {
            records.push({
                log_type: 'SHT',
                model_number: model,
                serial_number: serial,
                test_date: date,
                test_station: testStation,
                overall_result: hasFailure ? 'FAIL' : 'PASS',
                raw_data: content,
                source_file: filePath
            });
        }
    } catch (err) {
        console.error(`Error parsing ${filePath}: ${err.message}`);
    }

    return records;
}

/**
 * Extract test station from file path
 */
function extractTestStation(filePath) {
    const match = filePath.match(/TS-\d+[LR]/i);
    return match ? match[0].toUpperCase() : null;
}

module.exports = {
    parseShtFile,
    extractTestStation
};
