import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { dirname, join } from "path";
import lockfile from "proper-lockfile";
import { CONFIG_DIR_NAME, getAgentDir } from "../config.js";
import { COMPACTION_KEEP_RECENT_TOKENS, COMPACTION_RESERVE_TOKENS, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, } from "./constants.js";
/** Deep merge settings: project/overrides take precedence, nested objects merge recursively */
function deepMergeSettings(base, overrides) {
    const result = { ...base };
    for (const key of Object.keys(overrides)) {
        const overrideValue = overrides[key];
        const baseValue = base[key];
        if (overrideValue === undefined) {
            continue;
        }
        // For nested objects, merge recursively
        if (typeof overrideValue === "object" &&
            overrideValue !== null &&
            !Array.isArray(overrideValue) &&
            typeof baseValue === "object" &&
            baseValue !== null &&
            !Array.isArray(baseValue)) {
            result[key] = { ...baseValue, ...overrideValue };
        }
        else {
            // For primitives and arrays, override value wins
            result[key] = overrideValue;
        }
    }
    return result;
}
class FileSettingsStorage {
    constructor(cwd = process.cwd(), agentDir = getAgentDir()) {
        this.globalSettingsPath = join(agentDir, "settings.json");
        this.projectSettingsPath = join(cwd, CONFIG_DIR_NAME, "settings.json");
    }
    acquireLockSyncWithRetry(path) {
        const maxAttempts = 10;
        const delayMs = 20;
        let lastError;
        for (let attempt = 1; attempt <= maxAttempts; attempt++) {
            try {
                return lockfile.lockSync(path, { realpath: false });
            }
            catch (error) {
                const code = typeof error === "object" && error !== null && "code" in error
                    ? String(error.code)
                    : undefined;
                if (code !== "ELOCKED" || attempt === maxAttempts) {
                    throw error;
                }
                lastError = error;
                const start = Date.now();
                while (Date.now() - start < delayMs) {
                    // Sleep synchronously to avoid changing callers to async.
                }
            }
        }
        throw lastError ?? new Error("Failed to acquire settings lock");
    }
    withLock(scope, fn) {
        const path = scope === "global" ? this.globalSettingsPath : this.projectSettingsPath;
        const dir = dirname(path);
        let release;
        try {
            // Only create directory and lock if file exists or we need to write
            const fileExists = existsSync(path);
            if (fileExists) {
                release = this.acquireLockSyncWithRetry(path);
            }
            const current = fileExists ? readFileSync(path, "utf-8") : undefined;
            const next = fn(current);
            if (next !== undefined) {
                // Only create directory when we actually need to write
                if (!existsSync(dir)) {
                    mkdirSync(dir, { recursive: true });
                }
                if (!release) {
                    release = this.acquireLockSyncWithRetry(path);
                }
                writeFileSync(path, next, "utf-8");
            }
        }
        finally {
            if (release) {
                release();
            }
        }
    }
}
class InMemorySettingsStorage {
    withLock(scope, fn) {
        const current = scope === "global" ? this.global : this.project;
        const next = fn(current);
        if (next !== undefined) {
            if (scope === "global") {
                this.global = next;
            }
            else {
                this.project = next;
            }
        }
    }
}
export class SettingsManager {
    constructor(storage, initialGlobal, initialProject, globalLoadError = null, projectLoadError = null, initialErrors = []) {
        this.modifiedFields = new Set(); // Track global fields modified during session
        this.modifiedNestedFields = new Map(); // Track global nested field modifications
        this.modifiedProjectFields = new Set(); // Track project fields modified during session
        this.modifiedProjectNestedFields = new Map(); // Track project nested field modifications
        this.globalSettingsLoadError = null; // Track if global settings file had parse errors
        this.projectSettingsLoadError = null; // Track if project settings file had parse errors
        this.writeQueue = Promise.resolve();
        this.storage = storage;
        this.globalSettings = initialGlobal;
        this.projectSettings = initialProject;
        this.globalSettingsLoadError = globalLoadError;
        this.projectSettingsLoadError = projectLoadError;
        this.errors = [...initialErrors];
        this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);
    }
    /** Create a SettingsManager that loads from files */
    static create(cwd = process.cwd(), agentDir = getAgentDir()) {
        const storage = new FileSettingsStorage(cwd, agentDir);
        return SettingsManager.fromStorage(storage);
    }
    /** Create a SettingsManager from an arbitrary storage backend */
    static fromStorage(storage) {
        const globalLoad = SettingsManager.tryLoadFromStorage(storage, "global");
        const projectLoad = SettingsManager.tryLoadFromStorage(storage, "project");
        const initialErrors = [];
        if (globalLoad.error) {
            initialErrors.push({ scope: "global", error: globalLoad.error });
        }
        if (projectLoad.error) {
            initialErrors.push({ scope: "project", error: projectLoad.error });
        }
        return new SettingsManager(storage, globalLoad.settings, projectLoad.settings, globalLoad.error, projectLoad.error, initialErrors);
    }
    /** Create an in-memory SettingsManager (no file I/O) */
    static inMemory(settings = {}) {
        const storage = new InMemorySettingsStorage();
        return new SettingsManager(storage, settings, {});
    }
    static loadFromStorage(storage, scope) {
        let content;
        storage.withLock(scope, (current) => {
            content = current;
            return undefined;
        });
        if (!content) {
            return {};
        }
        const settings = JSON.parse(content);
        return SettingsManager.migrateSettings(settings);
    }
    static tryLoadFromStorage(storage, scope) {
        try {
            return { settings: SettingsManager.loadFromStorage(storage, scope), error: null };
        }
        catch (error) {
            return { settings: {}, error: error };
        }
    }
    /** Migrate old settings format to new format */
    static migrateSettings(settings) {
        // Migrate queueMode -> steeringMode
        if ("queueMode" in settings && !("steeringMode" in settings)) {
            settings.steeringMode = settings.queueMode;
            delete settings.queueMode;
        }
        // Migrate legacy websockets boolean -> transport enum
        if (!("transport" in settings) && typeof settings.websockets === "boolean") {
            settings.transport = settings.websockets ? "websocket" : "sse";
            delete settings.websockets;
        }
        // Migrate old skills object format to new array format
        if ("skills" in settings &&
            typeof settings.skills === "object" &&
            settings.skills !== null &&
            !Array.isArray(settings.skills)) {
            const skillsSettings = settings.skills;
            if (skillsSettings.enableSkillCommands !== undefined && settings.enableSkillCommands === undefined) {
                settings.enableSkillCommands = skillsSettings.enableSkillCommands;
            }
            if (Array.isArray(skillsSettings.customDirectories) && skillsSettings.customDirectories.length > 0) {
                settings.skills = skillsSettings.customDirectories;
            }
            else {
                delete settings.skills;
            }
        }
        return settings;
    }
    getGlobalSettings() {
        return structuredClone(this.globalSettings);
    }
    getProjectSettings() {
        return structuredClone(this.projectSettings);
    }
    getBashInterceptorEnabled() {
        return this.settings.bashInterceptor?.enabled ?? true;
    }
    getBashInterceptorRules() {
        return this.settings.bashInterceptor?.rules;
    }
    reload() {
        const globalLoad = SettingsManager.tryLoadFromStorage(this.storage, "global");
        if (!globalLoad.error) {
            this.globalSettings = globalLoad.settings;
            this.globalSettingsLoadError = null;
        }
        else {
            this.globalSettingsLoadError = globalLoad.error;
            this.recordError("global", globalLoad.error);
        }
        this.modifiedFields.clear();
        this.modifiedNestedFields.clear();
        this.modifiedProjectFields.clear();
        this.modifiedProjectNestedFields.clear();
        const projectLoad = SettingsManager.tryLoadFromStorage(this.storage, "project");
        if (!projectLoad.error) {
            this.projectSettings = projectLoad.settings;
            this.projectSettingsLoadError = null;
        }
        else {
            this.projectSettingsLoadError = projectLoad.error;
            this.recordError("project", projectLoad.error);
        }
        this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);
    }
    /** Apply additional overrides on top of current settings */
    applyOverrides(overrides) {
        this.settings = deepMergeSettings(this.settings, overrides);
    }
    /** Mark a global field as modified during this session */
    markModified(field, nestedKey) {
        this.modifiedFields.add(field);
        if (nestedKey) {
            if (!this.modifiedNestedFields.has(field)) {
                this.modifiedNestedFields.set(field, new Set());
            }
            this.modifiedNestedFields.get(field).add(nestedKey);
        }
    }
    /** Mark a project field as modified during this session */
    markProjectModified(field, nestedKey) {
        this.modifiedProjectFields.add(field);
        if (nestedKey) {
            if (!this.modifiedProjectNestedFields.has(field)) {
                this.modifiedProjectNestedFields.set(field, new Set());
            }
            this.modifiedProjectNestedFields.get(field).add(nestedKey);
        }
    }
    recordError(scope, error) {
        const normalizedError = error instanceof Error ? error : new Error(String(error));
        this.errors.push({ scope, error: normalizedError });
    }
    /**
     * Check if project-level settings are active (loaded from a file).
     * Used to scope model persistence to the project when possible,
     * preventing model config bleed between concurrent instances (#650).
     */
    hasProjectSettings() {
        // Project settings are active if we loaded them and they weren't empty/errored
        return !this.projectSettingsLoadError && Object.keys(this.projectSettings).length > 0;
    }
    clearModifiedScope(scope) {
        if (scope === "global") {
            this.modifiedFields.clear();
            this.modifiedNestedFields.clear();
            return;
        }
        this.modifiedProjectFields.clear();
        this.modifiedProjectNestedFields.clear();
    }
    enqueueWrite(scope, task) {
        this.writeQueue = this.writeQueue
            .then(() => {
            task();
            this.clearModifiedScope(scope);
        })
            .catch((error) => {
            this.recordError(scope, error);
        });
    }
    cloneModifiedNestedFields(source) {
        const snapshot = new Map();
        for (const [key, value] of source.entries()) {
            snapshot.set(key, new Set(value));
        }
        return snapshot;
    }
    persistScopedSettings(scope, snapshotSettings, modifiedFields, modifiedNestedFields) {
        this.storage.withLock(scope, (current) => {
            const currentFileSettings = current
                ? SettingsManager.migrateSettings(JSON.parse(current))
                : {};
            const mergedSettings = { ...currentFileSettings };
            for (const field of modifiedFields) {
                const value = snapshotSettings[field];
                if (modifiedNestedFields.has(field) && typeof value === "object" && value !== null) {
                    const nestedModified = modifiedNestedFields.get(field);
                    const baseNested = currentFileSettings[field] ?? {};
                    const inMemoryNested = value;
                    const mergedNested = { ...baseNested };
                    for (const nestedKey of nestedModified) {
                        mergedNested[nestedKey] = inMemoryNested[nestedKey];
                    }
                    mergedSettings[field] = mergedNested;
                }
                else {
                    mergedSettings[field] = value;
                }
            }
            return JSON.stringify(mergedSettings, null, 2);
        });
    }
    save() {
        this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);
        if (this.globalSettingsLoadError) {
            return;
        }
        const snapshotGlobalSettings = structuredClone(this.globalSettings);
        const modifiedFields = new Set(this.modifiedFields);
        const modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedNestedFields);
        this.enqueueWrite("global", () => {
            this.persistScopedSettings("global", snapshotGlobalSettings, modifiedFields, modifiedNestedFields);
        });
    }
    saveProjectSettings(settings) {
        this.projectSettings = structuredClone(settings);
        this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);
        if (this.projectSettingsLoadError) {
            return;
        }
        const snapshotProjectSettings = structuredClone(this.projectSettings);
        const modifiedFields = new Set(this.modifiedProjectFields);
        const modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);
        this.enqueueWrite("project", () => {
            this.persistScopedSettings("project", snapshotProjectSettings, modifiedFields, modifiedNestedFields);
        });
    }
    async flush() {
        await this.writeQueue;
    }
    drainErrors() {
        const drained = [...this.errors];
        this.errors = [];
        return drained;
    }
    // ── Generic setter helpers ──────────────────────────────────────────
    /** Set a top-level global setting field, mark modified, and save. */
    setGlobalSetting(key, value) {
        this.globalSettings[key] = value;
        this.markModified(key);
        this.save();
    }
    /** Set a top-level setting, scoped to project when project settings are active. */
    setScopedSetting(key, value) {
        if (this.hasProjectSettings()) {
            this.projectSettings[key] = value;
            this.markProjectModified(key);
            this.saveProjectSettings(this.projectSettings);
        }
        else {
            this.setGlobalSetting(key, value);
        }
    }
    /** Set a nested field within a global settings object (e.g. compaction.enabled). */
    setNestedGlobalSetting(key, nestedKey, value) {
        if (!this.globalSettings[key]) {
            this.globalSettings[key] = {};
        }
        this.globalSettings[key][nestedKey] = value;
        this.markModified(key, nestedKey);
        this.save();
    }
    /** Set a field on project settings (clone, set, mark modified, save). */
    setProjectSetting(key, value) {
        const projectSettings = structuredClone(this.projectSettings);
        projectSettings[key] = value;
        this.markProjectModified(key);
        this.saveProjectSettings(projectSettings);
    }
    // ── Public getters and setters ──────────────────────────────────────
    getLastChangelogVersion() {
        return this.settings.lastChangelogVersion;
    }
    setLastChangelogVersion(version) {
        this.setGlobalSetting("lastChangelogVersion", version);
    }
    getDefaultProvider() {
        return this.settings.defaultProvider;
    }
    getDefaultModel() {
        return this.settings.defaultModel;
    }
    setDefaultProvider(provider) {
        this.setScopedSetting("defaultProvider", provider);
    }
    setDefaultModel(modelId) {
        this.setScopedSetting("defaultModel", modelId);
    }
    setDefaultModelAndProvider(provider, modelId) {
        if (this.hasProjectSettings()) {
            this.projectSettings.defaultProvider = provider;
            this.projectSettings.defaultModel = modelId;
            this.markProjectModified("defaultProvider");
            this.markProjectModified("defaultModel");
            this.saveProjectSettings(this.projectSettings);
        }
        else {
            this.globalSettings.defaultProvider = provider;
            this.globalSettings.defaultModel = modelId;
            this.markModified("defaultProvider");
            this.markModified("defaultModel");
            this.save();
        }
    }
    getSteeringMode() {
        return this.settings.steeringMode || "one-at-a-time";
    }
    setSteeringMode(mode) {
        this.setGlobalSetting("steeringMode", mode);
    }
    getFollowUpMode() {
        return this.settings.followUpMode || "one-at-a-time";
    }
    setFollowUpMode(mode) {
        this.setGlobalSetting("followUpMode", mode);
    }
    getTheme() {
        return this.settings.theme;
    }
    setTheme(theme) {
        this.setGlobalSetting("theme", theme);
    }
    getDefaultThinkingLevel() {
        return this.settings.defaultThinkingLevel;
    }
    setDefaultThinkingLevel(level) {
        this.setGlobalSetting("defaultThinkingLevel", level);
    }
    getTransport() {
        return this.settings.transport ?? "sse";
    }
    setTransport(transport) {
        this.setGlobalSetting("transport", transport);
    }
    getCompactionEnabled() {
        return this.settings.compaction?.enabled ?? true;
    }
    setCompactionEnabled(enabled) {
        this.setNestedGlobalSetting("compaction", "enabled", enabled);
    }
    getCompactionReserveTokens() {
        return this.settings.compaction?.reserveTokens ?? COMPACTION_RESERVE_TOKENS;
    }
    getCompactionKeepRecentTokens() {
        return this.settings.compaction?.keepRecentTokens ?? COMPACTION_KEEP_RECENT_TOKENS;
    }
    getCompactionSettings() {
        return {
            enabled: this.getCompactionEnabled(),
            reserveTokens: this.getCompactionReserveTokens(),
            keepRecentTokens: this.getCompactionKeepRecentTokens(),
        };
    }
    getBranchSummarySettings() {
        return {
            reserveTokens: this.settings.branchSummary?.reserveTokens ?? COMPACTION_RESERVE_TOKENS,
            skipPrompt: this.settings.branchSummary?.skipPrompt ?? false,
        };
    }
    getBranchSummarySkipPrompt() {
        return this.settings.branchSummary?.skipPrompt ?? false;
    }
    getRetryEnabled() {
        return this.settings.retry?.enabled ?? true;
    }
    setRetryEnabled(enabled) {
        this.setNestedGlobalSetting("retry", "enabled", enabled);
    }
    getRetrySettings() {
        return {
            enabled: this.getRetryEnabled(),
            maxRetries: this.settings.retry?.maxRetries ?? 3,
            baseDelayMs: this.settings.retry?.baseDelayMs ?? RETRY_BASE_DELAY_MS,
            maxDelayMs: this.settings.retry?.maxDelayMs ?? RETRY_MAX_DELAY_MS,
        };
    }
    getHideThinkingBlock() {
        return this.settings.hideThinkingBlock ?? false;
    }
    setHideThinkingBlock(hide) {
        this.setGlobalSetting("hideThinkingBlock", hide);
    }
    getShellPath() {
        return this.settings.shellPath;
    }
    setShellPath(path) {
        this.setGlobalSetting("shellPath", path);
    }
    getQuietStartup() {
        return this.settings.quietStartup ?? false;
    }
    setQuietStartup(quiet) {
        this.setGlobalSetting("quietStartup", quiet);
    }
    getShellCommandPrefix() {
        return this.settings.shellCommandPrefix;
    }
    setShellCommandPrefix(prefix) {
        this.setGlobalSetting("shellCommandPrefix", prefix);
    }
    getCollapseChangelog() {
        return this.settings.collapseChangelog ?? false;
    }
    setCollapseChangelog(collapse) {
        this.setGlobalSetting("collapseChangelog", collapse);
    }
    getPackages() {
        return [...(this.settings.packages ?? [])];
    }
    setPackages(packages) {
        this.setGlobalSetting("packages", packages);
    }
    setProjectPackages(packages) {
        this.setProjectSetting("packages", packages);
    }
    getExtensionPaths() {
        return [...(this.settings.extensions ?? [])];
    }
    setExtensionPaths(paths) {
        this.setGlobalSetting("extensions", paths);
    }
    setProjectExtensionPaths(paths) {
        this.setProjectSetting("extensions", paths);
    }
    getSkillPaths() {
        return [...(this.settings.skills ?? [])];
    }
    setSkillPaths(paths) {
        this.setGlobalSetting("skills", paths);
    }
    setProjectSkillPaths(paths) {
        this.setProjectSetting("skills", paths);
    }
    getPromptTemplatePaths() {
        return [...(this.settings.prompts ?? [])];
    }
    setPromptTemplatePaths(paths) {
        this.setGlobalSetting("prompts", paths);
    }
    setProjectPromptTemplatePaths(paths) {
        this.setProjectSetting("prompts", paths);
    }
    getThemePaths() {
        return [...(this.settings.themes ?? [])];
    }
    setThemePaths(paths) {
        this.setGlobalSetting("themes", paths);
    }
    setProjectThemePaths(paths) {
        this.setProjectSetting("themes", paths);
    }
    getEnableSkillCommands() {
        return this.settings.enableSkillCommands ?? true;
    }
    setEnableSkillCommands(enabled) {
        this.setGlobalSetting("enableSkillCommands", enabled);
    }
    getThinkingBudgets() {
        return this.settings.thinkingBudgets;
    }
    getShowImages() {
        return this.settings.terminal?.showImages ?? true;
    }
    setShowImages(show) {
        this.setNestedGlobalSetting("terminal", "showImages", show);
    }
    getClearOnShrink() {
        // Settings takes precedence, then env var, then default false
        if (this.settings.terminal?.clearOnShrink !== undefined) {
            return this.settings.terminal.clearOnShrink;
        }
        return process.env.PI_CLEAR_ON_SHRINK === "1";
    }
    setClearOnShrink(enabled) {
        this.setNestedGlobalSetting("terminal", "clearOnShrink", enabled);
    }
    getImageAutoResize() {
        return this.settings.images?.autoResize ?? true;
    }
    setImageAutoResize(enabled) {
        this.setNestedGlobalSetting("images", "autoResize", enabled);
    }
    getBlockImages() {
        return this.settings.images?.blockImages ?? false;
    }
    setBlockImages(blocked) {
        this.setNestedGlobalSetting("images", "blockImages", blocked);
    }
    getEnabledModels() {
        return this.settings.enabledModels;
    }
    setEnabledModels(patterns) {
        this.setGlobalSetting("enabledModels", patterns);
    }
    getDoubleEscapeAction() {
        return this.settings.doubleEscapeAction ?? "tree";
    }
    setDoubleEscapeAction(action) {
        this.setGlobalSetting("doubleEscapeAction", action);
    }
    getTreeFilterMode() {
        const mode = this.settings.treeFilterMode;
        const valid = ["default", "no-tools", "user-only", "labeled-only", "all"];
        return mode && valid.includes(mode) ? mode : "default";
    }
    setTreeFilterMode(mode) {
        this.setGlobalSetting("treeFilterMode", mode);
    }
    getShowHardwareCursor() {
        return this.settings.showHardwareCursor ?? process.env.PI_HARDWARE_CURSOR === "1";
    }
    setShowHardwareCursor(enabled) {
        this.setGlobalSetting("showHardwareCursor", enabled);
    }
    getEditorPaddingX() {
        return this.settings.editorPaddingX ?? 0;
    }
    setEditorPaddingX(padding) {
        this.setGlobalSetting("editorPaddingX", Math.max(0, Math.min(3, Math.floor(padding))));
    }
    getAutocompleteMaxVisible() {
        return this.settings.autocompleteMaxVisible ?? 5;
    }
    setAutocompleteMaxVisible(maxVisible) {
        this.setGlobalSetting("autocompleteMaxVisible", Math.max(3, Math.min(20, Math.floor(maxVisible))));
    }
    getRespectGitignoreInPicker() {
        return this.settings.respectGitignoreInPicker ?? true;
    }
    setRespectGitignoreInPicker(value) {
        this.setGlobalSetting("respectGitignoreInPicker", value);
    }
    getSearchExcludeDirs() {
        return this.settings.searchExcludeDirs ?? [];
    }
    setSearchExcludeDirs(dirs) {
        this.setGlobalSetting("searchExcludeDirs", dirs.filter(Boolean));
    }
    getCodeBlockIndent() {
        return this.settings.markdown?.codeBlockIndent ?? "  ";
    }
    getMemorySettings() {
        return {
            enabled: this.settings.memory?.enabled ?? false,
            maxRolloutsPerStartup: this.settings.memory?.maxRolloutsPerStartup ?? 64,
            maxRolloutAgeDays: this.settings.memory?.maxRolloutAgeDays ?? 30,
            minRolloutIdleHours: this.settings.memory?.minRolloutIdleHours ?? 12,
            stage1Concurrency: this.settings.memory?.stage1Concurrency ?? 8,
            summaryInjectionTokenLimit: this.settings.memory?.summaryInjectionTokenLimit ?? 5000,
        };
    }
    getAsyncEnabled() {
        return this.settings.async?.enabled ?? false;
    }
    getAsyncMaxJobs() {
        return this.settings.async?.maxJobs ?? 100;
    }
    getTaskIsolationMode() {
        return this.settings.taskIsolation?.mode ?? "none";
    }
    getTaskIsolationMerge() {
        return this.settings.taskIsolation?.merge ?? "patch";
    }
    getFallbackEnabled() {
        return this.settings.fallback?.enabled ?? false;
    }
    setFallbackEnabled(enabled) {
        this.setNestedGlobalSetting("fallback", "enabled", enabled);
    }
    getFallbackChains() {
        return this.settings.fallback?.chains ?? {};
    }
    getFallbackChain(name) {
        return this.settings.fallback?.chains?.[name];
    }
    setFallbackChain(name, entries) {
        if (!this.globalSettings.fallback) {
            this.globalSettings.fallback = {};
        }
        if (!this.globalSettings.fallback.chains) {
            this.globalSettings.fallback.chains = {};
        }
        // Sort by priority
        this.globalSettings.fallback.chains[name] = [...entries].sort((a, b) => a.priority - b.priority);
        this.markModified("fallback");
        this.save();
    }
    removeFallbackChain(name) {
        if (!this.globalSettings.fallback?.chains?.[name]) {
            return false;
        }
        delete this.globalSettings.fallback.chains[name];
        if (Object.keys(this.globalSettings.fallback.chains).length === 0) {
            delete this.globalSettings.fallback.chains;
        }
        this.markModified("fallback");
        this.save();
        return true;
    }
    getFallbackSettings() {
        return {
            enabled: this.getFallbackEnabled(),
            chains: this.getFallbackChains(),
        };
    }
    getModelDiscoverySettings() {
        return this.settings.modelDiscovery ?? {};
    }
    setModelDiscoveryEnabled(enabled) {
        this.setNestedGlobalSetting("modelDiscovery", "enabled", enabled);
    }
    getEditMode() {
        return this.settings.editMode ?? "standard";
    }
    setEditMode(mode) {
        this.setGlobalSetting("editMode", mode);
    }
    getTimestampFormat() {
        return this.settings.timestampFormat ?? "date-time-iso";
    }
    setTimestampFormat(format) {
        this.setGlobalSetting("timestampFormat", format);
    }
}
//# sourceMappingURL=settings-manager.js.map