const memory = require('./memory.js'); // Scheduler memory

module.exports = async function() {
    try {
        // Load tasks from tasks.json into memory
        // Active tasks will automatically start their timers
        memory.loadTasks();

        // Build the return object with task status
        const tasksStatus = {};
        const allTasks = memory.getAllTasks();
        for (const name in allTasks) {
            const t = allTasks[name];
            tasksStatus[name] = {
                active: t.active,
                oneTime: t.oneTime,
                intervalInSec: t.intervalInSec,
                lastRun: t.lastRun,
                nextRun: t.nextRun,
                error: t.error,
                action: t.action
            };
        }

        return {
            online: true,    // service is running
            tasks: tasksStatus
        };
    } catch (err) {
        console.error('Failed to start scheduler service:', err);
        return {
            online: false,
            tasks: {}
        };
    }
};