import { nativeTypeReplacer, nativeTypeReviver } from "../revivers/index.js";
export class GlobalStore {
    store = {};
    initializedModules = new Set();
    get(moduleId, varName) {
        return this.store[moduleId]?.[varName];
    }
    set(moduleId, varName, value) {
        if (!this.store[moduleId])
            this.store[moduleId] = {};
        this.store[moduleId][varName] = value;
    }
    isInitialized(moduleId) {
        return this.initializedModules.has(moduleId);
    }
    markInitialized(moduleId) {
        this.initializedModules.add(moduleId);
    }
    toJSON() {
        return JSON.parse(JSON.stringify({
            store: this.store,
            initializedModules: [...this.initializedModules],
        }, nativeTypeReplacer), nativeTypeReviver);
    }
    getTokenStats() {
        return this.get(GlobalStore.INTERNAL_MODULE, "__tokenStats");
    }
    restoreTokenStats(stats) {
        this.set(GlobalStore.INTERNAL_MODULE, "__tokenStats", stats);
    }
    static INTERNAL_MODULE = "__internal";
    static withTokenStats() {
        const gs = new GlobalStore();
        gs.set(GlobalStore.INTERNAL_MODULE, "__tokenStats", {
            usage: {
                inputTokens: 0,
                outputTokens: 0,
                cachedInputTokens: 0,
                totalTokens: 0,
            },
            cost: {
                inputCost: 0,
                outputCost: 0,
                totalCost: 0,
                currency: "USD",
            },
        });
        return gs;
    }
    static tokenStatsFromJSON(json) {
        const tokenStats = json.store?.[GlobalStore.INTERNAL_MODULE]?.["__tokenStats"];
        if (!tokenStats)
            return { totalTokens: 0, totalCost: 0 };
        return {
            totalTokens: tokenStats.usage?.totalTokens ?? 0,
            totalCost: tokenStats.cost?.totalCost ?? 0,
        };
    }
    static fromJSON(json) {
        const gs = new GlobalStore();
        gs.store = json.store || {};
        gs.initializedModules = new Set(json.initializedModules || []);
        return gs;
    }
}
