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

const PORT = 5454;
const OUTPUT_FILE = path.join(__dirname, 'collected_data.json');

// Initialize file if not exists
if (!fs.existsSync(OUTPUT_FILE)) {
    fs.writeFileSync(OUTPUT_FILE, '[\n');
}

const server = http.createServer((req, res) => {
    // Enable CORS
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

    if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
    }

    if (req.method === 'POST') {
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });
        req.on('end', () => {
            try {
                const data = JSON.parse(body);
                const entry = {
                    timestamp: new Date().toISOString(),
                    data: data
                };

                // Append to file (pseudo-JSON array)
                // We'll just append object,\n for simplicity and manual reading, 
                // or strict JSON if we seek back.
                // Let's do line-delimited JSON for robustness, or just append to the array structure?
                // Appending to array structure is hard with naive append.
                // Let's do NDJSON (Newline Delimited JSON).
                fs.appendFileSync(OUTPUT_FILE, JSON.stringify(entry) + '\n');

                console.log(`[DataCollector] Saved packet at ${entry.timestamp}`);
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ success: true }));
            } catch (e) {
                console.error('Error parsing JSON', e);
                res.writeHead(400);
                res.end('Invalid JSON');
            }
        });
    } else {
        res.writeHead(404);
        res.end();
    }
});

server.listen(PORT, () => {
    console.log(`Data Collector running on port ${PORT}`);
    console.log(`Output file: ${OUTPUT_FILE}`);
});
