const path = require('path');
const { spawn } = require('child_process');

function outputProgress(data) {
    if (!data.status) {
        data = {
            status: 'running',
            ...data
        };
    }
    console.log(JSON.stringify(data));
}

function runScript(scriptPath) {
    return new Promise((resolve, reject) => {
        const child = spawn('node', [scriptPath], {
            stdio: ['inherit', 'pipe', 'pipe'],
            env: {
                ...process.env,
                PGHOST: process.env.DB_HOST,
                PGUSER: process.env.DB_USER,
                PGPASSWORD: process.env.DB_PASSWORD,
                PGDATABASE: process.env.DB_NAME,
                PGPORT: process.env.DB_PORT || '5432'
            }
        });

        let output = '';

        child.stdout.on('data', (data) => {
            const lines = data.toString().split('\n');
            lines.filter(line => line.trim()).forEach(line => {
                try {
                    console.log(line); // Pass through the JSON output
                    output += line + '\n';
                } catch (e) {
                    console.log(line); // If not JSON, just log it directly
                }
            });
        });

        child.stderr.on('data', (data) => {
            console.error(data.toString());
        });

        child.on('close', (code) => {
            if (code !== 0) {
                reject(new Error(`Script ${scriptPath} exited with code ${code}`));
            } else {
                resolve(output);
            }
        });

        child.on('error', (err) => {
            reject(err);
        });
    });
}

async function fullReset() {
    try {
        // Step 1: Reset Database
        outputProgress({
            operation: 'Starting full reset',
            message: 'Step 1/3: Resetting database...'
        });
        await runScript(path.join(__dirname, 'reset-db.js'));
        outputProgress({
            status: 'complete',
            operation: 'Database reset step complete',
            message: 'Database reset finished, moving to import...'
        });

        // Step 2: Import from Production
        outputProgress({
            operation: 'Starting import',
            message: 'Step 2/3: Importing from production...'
        });
        await runScript(path.join(__dirname, 'import-from-prod.js'));
        outputProgress({
            status: 'complete',
            operation: 'Import step complete',
            message: 'Import finished, moving to metrics calculation...'
        });

        // Step 3: Calculate Metrics
        outputProgress({
            operation: 'Starting metrics calculation',
            message: 'Step 3/3: Calculating metrics...'
        });
        await runScript(path.join(__dirname, 'calculate-metrics-new.js'));
        
        // Final completion message
        outputProgress({
            status: 'complete',
            operation: 'Full reset complete',
            message: 'Successfully completed all steps: database reset, import, and metrics calculation'
        });
    } catch (error) {
        outputProgress({
            status: 'error',
            operation: 'Full reset failed',
            error: error.message,
            stack: error.stack
        });
        process.exit(1);
    }
}

// Run if called directly
if (require.main === module) {
    fullReset();
}

module.exports = fullReset; 