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

async function generatePincodeData() {
    const csvPath = path.join(__dirname, '..', '..', 'PINCODES.csv');
    const outPath = path.join(__dirname, '..', '..', 'assets', 'js', 'pincode-data.js');

    if (!fs.existsSync(csvPath)) {
        console.error('PINCODES.csv not found at ' + csvPath);
        return;
    }

    const fileStream = fs.createReadStream(csvPath);
    const rl = readline.createInterface({
        input: fileStream,
        crlfDelay: Infinity
    });

    const pincodeMap = {};
    let isFirstLine = true;

    console.log('Reading PINCODES.csv...');

    for await (const line of rl) {
        if (isFirstLine) {
            isFirstLine = false;
            continue;
        }

        const parts = line.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
        if (!parts || parts.length < 4) continue;

        const pincode = parts[0].replace(/"/g, '').trim();
        const state = parts[1].replace(/"/g, '').trim();
        const city = parts[2].replace(/"/g, '').trim();
        const areaRaw = parts[3].replace(/"/g, '').trim();

        if (!pincodeMap[pincode]) {
            pincodeMap[pincode] = { s: state, c: city, a: [] };
        }

        const areas = areaRaw.split(',').map(a => a.trim()).filter(a => a);
        areas.forEach(a => {
            if (!pincodeMap[pincode].a.includes(a)) {
                pincodeMap[pincode].a.push(a);
            }
        });
    }

    console.log(`Parsed ${Object.keys(pincodeMap).length} unique pincodes.`);

    // sorting areas
    for (const p in pincodeMap) {
        pincodeMap[p].a.sort();
    }

    const content = `// Auto-generated Pincode Data
const PINCODE_DATA = ${JSON.stringify(pincodeMap)};
`;

    fs.writeFileSync(outPath, content);
    console.log('Successfully generated ' + outPath);
}

generatePincodeData();
