import { init_tasks, run_schedule } from './schedule.js';
import { init_paths } from './state.js';
import { now } from '../lib/util.js';
import { debug, err_handler } from './util.js';
import { init_programs, init_stores, run_program } from './program.js';
const GET_INIT_STATE = () => {
    return {
        commits: [],
        error: null,
        output: null,
        status: 'init',
        steps: 0
    };
};
export function eval_witness(state, witness, marker = now()) {
    if (state.output !== null) {
        return state;
    }
    state.error = null;
    try {
        debug('[vm] eval witness data:', witness);
        run_schedule(state, marker);
        if (state.output !== null)
            return state;
        run_program(state, witness);
    }
    catch (err) {
        state.error = err_handler(err);
    }
    state.updated = marker;
    return state;
}
export function eval_schedule(state, marker = now()) {
    if (state.output !== null)
        return state;
    run_schedule(state, marker);
    return state;
}
export function init_vm(config) {
    const head = config.cid;
    const paths = init_paths(config.pathnames, config.programs);
    const programs = init_programs(config.programs);
    const store = init_stores(programs.map(e => e[0]));
    const start = config.activated;
    const tasks = init_tasks(config.schedule);
    const updated = start;
    return { ...GET_INIT_STATE(), head, paths, programs, start, store, tasks, updated };
}
