"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.runScheduler = runScheduler;
const db_1 = require("./db");
function evaluateCondition(cond, context) {
    try {
        const fn = new Function("context", `with(context) { return ${cond}; }`);
        return fn(context);
    }
    catch (err) {
        console.error("Error evaluating condition", err);
        return false;
    }
}
async function runScheduler() {
    const now = new Date().toISOString();
    const due = await (0, db_1.getDueSchedules)(now);
    for (const job of due) {
        let onchainConditionMet = true;
        if (job.onChainTrigger) {
            const context = await fetchEventContext(job.onChainTrigger);
            onchainConditionMet = evaluateCondition(job.onChainTrigger.condition, context);
        }
        if (onchainConditionMet) {
            try {
                (0, db_1.updateScheduleStatus)(job.id, "running");
                // === CALL TOOL HERE ===
                // await yourToolExecutor(job);
                (0, db_1.updateScheduleStatus)(job.id, "done");
            }
            catch (err) {
                console.error("Error running job", job.id, err);
                (0, db_1.updateScheduleStatus)(job.id, "error");
            }
        }
    }
}
async function fetchEventContext(trigger) {
    // Stub: connect to blockchain, fetch latest matching event
    return { price: 1.10 }; // mock context
}
