// Run the whole update cycle in business time (see docs/TIME.md). The cron
// that invokes this script does not set TZ; child scripts inherit it.
process.env.TZ = process.env.TZ || 'America/Chicago';

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

// Maintenance switch: `touch .pause-auto-update` in inventory-server/ to make the
// recurring full-update a no-op (e.g. during a long manual full re-import or a
// snapshot rebuild). Remove the file to resume.
const PAUSE_FILE = path.join(__dirname, '..', '.pause-auto-update');

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']
        });

        let output = '';

        child.stdout.on('data', (data) => {
            const lines = data.toString().split('\n');
            lines.filter(line => line.trim()).forEach(line => {
                console.log(line); // Pass through the (usually JSON) output
                output += line + '\n';
            });
        });

        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 fullUpdate() {
    if (fs.existsSync(PAUSE_FILE)) {
        outputProgress({
            status: 'complete',
            operation: 'Full update skipped',
            message: `Auto-update is paused (${PAUSE_FILE} exists) — remove the file to resume`
        });
        return;
    }
    try {
        // Step 1: Import from Production
        outputProgress({
            operation: 'Starting full update',
            message: 'Step 1/2: 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 2: Calculate Metrics
        outputProgress({
            operation: 'Starting metrics calculation',
            message: 'Step 2/2: Calculating metrics...'
        });
        await runScript(path.join(__dirname, 'calculate-metrics-new.js'));
        outputProgress({
            status: 'complete',
            operation: 'Metrics step complete',
            message: 'Metrics calculation finished'
        });

        // Final completion message
        outputProgress({
            status: 'complete',
            operation: 'Full update complete',
            message: 'Successfully completed all steps: import and metrics calculation'
        });
    } catch (error) {
        outputProgress({
            status: 'error',
            operation: 'Full update failed',
            error: error.message,
            stack: error.stack
        });
        process.exit(1);
    }
}

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

module.exports = fullUpdate; 