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

const inputFile = process.argv[2];
const outputFile = process.argv[3];

if (!inputFile || !outputFile) {
    console.error("Usage: node convert_salary.js <input> <output>");
    process.exit(1);
}

const content = fs.readFileSync(inputFile, 'latin1');
const lines = content.split(/\r?\n/);

const entries = [];
const regex = /^(\d+)\s+([A-Z0-9]+)\s+(.+?)\s+((?:\d{1,3}(?:\.\d{3})*(?:,\d{2})?\s+)+)/;

for (const line of lines) {
    const match = line.trim().match(regex);
    if (match) {
        const code = match[2];
        let description = match[3].trim();
        const numbersPart = match[4].trim();

        // Split numbers by whitespace
        const numbers = numbersPart.split(/\s+/).map(n => parseFloat(n.replace(/\./g, '').replace(',', '.')));

        if (numbers.length >= 2) {
            const baseSalary = numbers[0];
            const subsidy = numbers[1];
            const gross = baseSalary + subsidy; // Calculate Gross sum

            entries.push({
                code: code,
                name: description,
                baseSalary: baseSalary.toFixed(2),
                subsidy: subsidy.toFixed(2),
                gross: gross.toFixed(2)
            });
        } else if (numbers.length === 1) {
            // Only base
            entries.push({
                code: code,
                name: description,
                baseSalary: numbers[0].toFixed(2),
                subsidy: "0.00",
                gross: numbers[0].toFixed(2)
            });
        }
    }
}

console.log(`Parsed ${entries.length} entries.`);
fs.writeFileSync(outputFile, JSON.stringify(entries, null, 2));
