const MAX_RETAINED_OUTPUT = 256;
export function createStore() {
    let state = {
        output: [],
        stats: {
            status: "idle",
            iterations: 0,
            tokensIn: 0,
            tokensOut: 0,
            elapsedMs: 0
        }
    };
    const listeners = new Set();
    function notify() {
        for (const listener of listeners) {
            listener();
        }
    }
    function getState() {
        return state;
    }
    function appendOutput(item) {
        const next = state.output.length >= MAX_RETAINED_OUTPUT
            ? [...state.output.slice(state.output.length - MAX_RETAINED_OUTPUT + 1), item]
            : [...state.output, item];
        state = { ...state, output: next };
        notify();
    }
    function updateStats(partial) {
        state = {
            ...state,
            stats: {
                ...state.stats,
                ...partial
            }
        };
        notify();
    }
    function onChange(handler) {
        listeners.add(handler);
        return () => {
            listeners.delete(handler);
        };
    }
    return {
        getState,
        appendOutput,
        updateStats,
        onChange
    };
}
