import { 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 INIT_STATE = {
    commits: [],
    error: null,
    result: null,
    status: 'init',
    steps: 0,
    store: []
};
export function eval_witness(state, witness, marker = now()) {
    if (state.result !== null) {
        return { state };
    }
    let error;
    try {
        debug('[vm] eval witness data:', witness);
        run_schedule(state, marker);
        if (state.result !== null)
            return { state };
        run_program(state, witness);
    }
    catch (err) {
        error = err_handler(err);
    }
    state.updated = marker;
    return { error, state };
}
export function eval_schedule(state, marker = now()) {
    if (state.result !== null)
        return state;
    run_schedule(state, marker);
    return state;
}
export function init_vm(config) {
    const head = config.cid;
    const paths = init_paths(config.paths, config.programs);
    const programs = init_programs(config.programs);
    const store = init_stores(programs.map(e => e[0]));
    const start = config.published;
    const tasks = config.schedule.sort((a, b) => a[0] - b[0]);
    const updated = start;
    return { ...INIT_STATE, head, paths, programs, start, store, tasks, updated };
}
