// Force strict mode and setup for ESM
"use strict";
import {
  backupSettingsFile,
  cleanupSettingsBackup,
  getNestedProperty,
  getPersistScopeForModelSelection,
  restoreSettingsFromBackup
} from "./chunk-BYFID5BL.js";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/config/loadedSettingsAdapter.ts
init_esbuild_shims();
function createLoadedSettingsAdapter(settings, scope) {
  const persistScope = scope ?? getPersistScopeForModelSelection(settings);
  const settingsFile = settings.forScope(persistScope);
  let settingsSnapshot = null;
  let originalSnapshot = null;
  return {
    getValue(key) {
      return getNestedProperty(settings.merged, key);
    },
    setValue(key, value) {
      for (const part of key.split(".")) {
        if (part === "__proto__" || part === "constructor" || part === "prototype") {
          throw new Error(
            `Refusing to write settings key with reserved segment: ${key}`
          );
        }
      }
      settings.setValue(persistScope, key, value);
    },
    getModelProviders() {
      return settings.merged.modelProviders ?? {};
    },
    persist() {
    },
    backup() {
      backupSettingsFile(settingsFile.path);
      settingsSnapshot = structuredClone(settingsFile.settings);
      originalSnapshot = structuredClone(settingsFile.originalSettings);
    },
    restore() {
      const restored = restoreSettingsFromBackup(settingsFile.path);
      if (!restored) {
        console.error(
          `[loadedSettingsAdapter] On-disk rollback of ${settingsFile.path} failed; in-memory state was restored but the file may be inconsistent. Re-run /auth or inspect the file directly to recover.`
        );
      }
      if (settingsSnapshot !== null) {
        settingsFile.settings = settingsSnapshot;
      }
      if (originalSnapshot !== null) {
        settingsFile.originalSettings = originalSnapshot;
      }
      settings.recomputeMerged();
    },
    cleanupBackup() {
      cleanupSettingsBackup(settingsFile.path);
      settingsSnapshot = null;
      originalSnapshot = null;
    }
  };
}
__name(createLoadedSettingsAdapter, "createLoadedSettingsAdapter");

export {
  createLoadedSettingsAdapter
};
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Adapter that lets core's `applyProviderInstallPlan` write through
 * `LoadedSettings` while preserving CLI-specific guarantees:
 * - scope resolution via `getPersistScopeForModelSelection`
 * - on-disk `.orig` backup of the target settings file
 * - in-memory snapshot of `settings` / `originalSettings` for rollback
 * - merged-settings recomputation after restore
 */
