/**
 * Parser for single-line CSV format (7BLOG)
 *
 * Format:
 * STAGE: MODEL,SERIAL,DATE,VERSION,CODE,VALUE1,VALUE2,...
 * Example:
 * FINAL: 7B21,87876-1,05-08-2013,1.984,0651945, 12, 9999, ...
 */

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

/**
 * Parse a 7BLOG CSV file and extract test records
 * @param {string} filePath - Path to the DAT file
 * @param {string} testStation - Test station identifier
 * @returns {Array} Array of parsed records
 */
function parseCsvFile(filePath, testStation = null) {
    const records = [];

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

        for (const line of lines) {
            if (!line) continue;

            // Match pattern: STAGE: MODEL,SERIAL,DATE,...
            const match = line.match(/^([A-Z-]+):\s*([^,]+),([^,]+),(\d{2}-\d{2}-\d{4}),(.*)$/);

            if (match) {
                const [, stage, model, serial, dateStr, rest] = match;

                // Parse date from MM-DD-YYYY to YYYY-MM-DD
                const [month, day, year] = dateStr.split('-');
                const testDate = `${year}-${month}-${day}`;

                // Model number includes the stage prefix for 7B products
                const modelNumber = model.trim();

                records.push({
                    log_type: '7BLOG',
                    model_number: modelNumber,
                    serial_number: serial.trim(),
                    test_date: testDate,
                    test_station: testStation,
                    overall_result: 'PASS', // 7BLOG entries are typically passing records
                    raw_data: line,
                    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 = {
    parseCsvFile,
    extractTestStation
};
