export class AgentVariables {
    _variables = new Map();
    _funcCounters = new Map();
    _saveThreshold = 1250;
    onVariableSet;
    static Prefix = '${';
    static Suffix = '}';
    constructor(config) {
        if (config?.saveThreshold) {
            this._saveThreshold = config.saveThreshold;
        }
        if (config?.onVariableSet) {
            this.onVariableSet = config.onVariableSet;
        }
    }
    static hasSyntax(name) {
        return name.startsWith(AgentVariables.Prefix) && name.endsWith(AgentVariables.Suffix);
    }
    static stripSyntax(name) {
        return name.substring(AgentVariables.Prefix.length, name.length - AgentVariables.Suffix.length);
    }
    get saveThreshold() {
        return this._saveThreshold;
    }
    get(name) {
        if (AgentVariables.hasSyntax(name)) {
            name = AgentVariables.stripSyntax(name);
        }
        return this._variables.get(name);
    }
    async set(name, value) {
        if (AgentVariables.hasSyntax(name)) {
            name = AgentVariables.stripSyntax(name);
        }
        this._variables.set(name, value);
        if (this.onVariableSet) {
            await this.onVariableSet(name, value);
        }
    }
    read(name, index, count) {
        if (AgentVariables.hasSyntax(name)) {
            name = AgentVariables.stripSyntax(name);
        }
        const variable = this._variables.get(name);
        if (variable) {
            return variable.substring(index, count);
        }
        return '';
    }
    async save(funcName, result) {
        const count = (this._funcCounters.get(funcName) || 0) + 1;
        const varName = `${funcName}_${count}`;
        this._funcCounters.set(funcName, count);
        await this.set(varName, result);
        return varName;
    }
    shouldSave(value, saveThreshold) {
        const threshold = saveThreshold || this._saveThreshold;
        if (threshold < 0) {
            return false;
        }
        return value.length >= threshold;
    }
}
