/**
 * API-key placeholder detection — shared between server-side persistence
 * (`apiKeyManager`) and the web UI's settings flow.
 *
 * Background: when the backend has a key configured, the UI used to
 * display a fake string like `lx_••••••••••••••••(server-managed)` in
 * the editable settings field. Auto-save then echoed that string back
 * to `setSessionKeys`, overwriting the real key with the bullets and
 * 401-ing every agent request.
 *
 * Defense layers all share these detection rules so they can't drift
 * apart over time.
 */

// Display string the UI used to write into settings.apiKeys.loxiaBackend.
// Kept exported for detection only — new code should never write it.
export const LEGACY_BULLET_PLACEHOLDER = 'lx_••••••••••••••••(server-managed)';

// Old sentinel used by appStore's restore path. Detect & strip on inbound.
export const LEGACY_PLATFORM_MANAGED_SENTINEL = 'platform-managed';

/**
 * Heuristic: does this look like a placeholder rather than a real key?
 * Real keys are alphanumeric + a few punctuation chars; placeholders contain
 * bullets, parens, or match a known sentinel string.
 *
 * @param {*} value
 * @returns {boolean}
 */
export function isPlaceholderApiKey(value) {
  if (typeof value !== 'string') return false;
  if (!value) return false;
  if (value === LEGACY_PLATFORM_MANAGED_SENTINEL) return true;
  if (value.includes('•')) return true;
  if (value.includes('(server-managed)')) return true;
  if (value.includes('[server-managed]')) return true;
  return false;
}

/**
 * Strip a placeholder, returning '' if the value isn't a real key. Real
 * keys pass through unchanged. Non-strings collapse to '' to keep
 * downstream code simple.
 *
 * @param {string|*} value
 * @returns {string}
 */
export function sanitizeApiKeyValue(value) {
  if (typeof value !== 'string') return '';
  return isPlaceholderApiKey(value) ? '' : value;
}

/**
 * Sanitize an entire `apiKeys` object — common shape used by settings
 * persistence and api.setApiKeys. Returns a new object with placeholder
 * values replaced by ''. Does not mutate the input.
 *
 * @param {Object|null|undefined} apiKeys
 * @returns {Object}
 */
export function sanitizeApiKeysObject(apiKeys) {
  if (!apiKeys || typeof apiKeys !== 'object') return {};
  const out = {};
  for (const [k, v] of Object.entries(apiKeys)) {
    out[k] = sanitizeApiKeyValue(v);
  }
  return out;
}
