import fs from 'node:fs';

// src/features/token-optimizer/infrastructure/config.ts
var DEFAULT_TOKEN_OPTIMIZER_STATE = {
  enabled: false
};
var tokenOptimizerRuntimeState = globalThis.__JU_HONG_E_TOKEN_OPTIMIZER_STATE__ ?? (globalThis.__JU_HONG_E_TOKEN_OPTIMIZER_STATE__ = {
  ...DEFAULT_TOKEN_OPTIMIZER_STATE
});
function normalizeTokenOptimizerState(value) {
  if (!value || typeof value !== "object") {
    return { ...DEFAULT_TOKEN_OPTIMIZER_STATE };
  }
  const enabled = "enabled" in value ? Boolean(value.enabled) : DEFAULT_TOKEN_OPTIMIZER_STATE.enabled;
  return {
    enabled
  };
}
function readTokenOptimizerConfig(paths) {
  if (!fs.existsSync(paths.tokenOptimizerConfigPath)) {
    return { ...DEFAULT_TOKEN_OPTIMIZER_STATE };
  }
  try {
    const parsed = JSON.parse(fs.readFileSync(paths.tokenOptimizerConfigPath, "utf8"));
    return normalizeTokenOptimizerState(parsed);
  } catch {
    return { ...DEFAULT_TOKEN_OPTIMIZER_STATE };
  }
}
function hydrateTokenOptimizerState(paths) {
  const nextState = readTokenOptimizerConfig(paths);
  tokenOptimizerRuntimeState.enabled = nextState.enabled;
  return tokenOptimizerRuntimeState.enabled;
}
function isTokenOptimizerEnabled(paths) {
  if (paths) {
    return hydrateTokenOptimizerState(paths);
  }
  return tokenOptimizerRuntimeState.enabled;
}
function saveTokenOptimizerConfig(paths, enabled) {
  const nextState = {
    enabled: Boolean(enabled)
  };
  fs.writeFileSync(paths.tokenOptimizerConfigPath, `${JSON.stringify(nextState, null, 2)}
`, "utf8");
  tokenOptimizerRuntimeState.enabled = nextState.enabled;
  return nextState;
}

export { hydrateTokenOptimizerState, isTokenOptimizerEnabled, readTokenOptimizerConfig, saveTokenOptimizerConfig };
