/**
 * PR-C Deprecation Warning Utility
 * Provides `warnOnce(key, message)` — same key won't print twice.
 * Used by deprecation checks across all modules.
 */

const _warned = new Set();

/**
 * Emit a deprecation warning once per process lifetime.
 * @param {string} key - unique key for this warning (e.g. "active-memory.blocking")
 * @param {string} message - human-readable message
 * @param {object} [opts]
 * @param {boolean} [opts.force] - if true, emit even if already warned
 * @returns {boolean} true if warning was emitted, false if skipped (duplicate)
 */
export function warnOnce(key, message, opts = {}) {
  if (!opts.force && _warned.has(key)) {
    return false;
  }
  _warned.add(key);
  console.warn(`[DEPRECATED][OpenClaw v2] ${key}: ${message}`);
  return true;
}

/**
 * Reset all warned keys (for testing).
 */
export function resetWarnings() {
  _warned.clear();
}

/**
 * Get count of unique warnings emitted so far.
 */
export function getWarningCount() {
  return _warned.size;
}

/**
 * Get all warned keys.
 */
export function getWarnedKeys() {
  return [..._warned];
}

/**
 * Emit multiple deprecation warnings with deduplication.
 * @param {Array<{key: string, message: string}>} warnings
 */
export function warnMany(warnings) {
  const emitted = [];
  for (const w of warnings) {
    if (warnOnce(w.key, w.message)) {
      emitted.push(w);
    }
  }
  return emitted;
}

/**
 * Run a deprecation check function and collect warnings.
 * @param {string} checkName - name of the check
 * @param {() => Array<{key:string, message:string}>} fn - check function
 * @returns {{ name: string, warnings: Array<{key:string, message:string}> }}
 */
export function runDeprecationCheck(checkName, fn) {
  try {
    const warnings = fn();
    return { name: checkName, warnings };
  } catch (e) {
    return { name: checkName, warnings: [{ key: checkName, message: `Check failed: ${e.message}` }] };
  }
}
