'use strict';

// --- Backward-Compatibility Lifecycle Registry ---
// Tracks compat shims, their deprecation status, and telemetry keys.
// Called at boot to log warnings; queried by /telemetry skill for removal candidates.

const COMPAT_REGISTRY = {
  chat_json_mode: {
    addedIn: '0.5.0',
    deprecatedIn: null,
    removeAfter: null,
    replacedBy: '?stream=1 SSE mode',
    telemetryKey: 'chat_json_mode',
  },
  devbox_gateway: {
    addedIn: '0.4.0',
    deprecatedIn: null,
    removeAfter: null,
    replacedBy: null,
    telemetryKey: 'devbox_gateway',
  },
};

// Boot-collected compat usage flags (one-time per boot, not per-request)
const _bootUsage = {};

function recordCompatUsage(key) {
  _bootUsage[key] = true;
}

function getBootUsage() {
  return { ..._bootUsage };
}

// Simple semver compare: returns true if a >= b
function _semverGte(a, b) {
  if (!a || !b) return false;
  const pa = a.split('.').map(Number);
  const pb = b.split('.').map(Number);
  for (let i = 0; i < 3; i++) {
    if ((pa[i] || 0) > (pb[i] || 0)) return true;
    if ((pa[i] || 0) < (pb[i] || 0)) return false;
  }
  return true; // equal
}

function checkDeprecations(currentVersion) {
  for (const [key, info] of Object.entries(COMPAT_REGISTRY)) {
    if (info.removeAfter && _semverGte(currentVersion, info.removeAfter)) {
      console.warn(`[compat] ${key}: scheduled for removal (since ${info.removeAfter})`);
    }
  }
}

function getRemovalCandidates(compatUsageByInstall) {
  // compatUsageByInstall: { feature: numberOfInstallsUsing }
  const candidates = [];
  for (const [key, info] of Object.entries(COMPAT_REGISTRY)) {
    if (!info.deprecatedIn) continue;
    const usageCount = (compatUsageByInstall && compatUsageByInstall[info.telemetryKey]) || 0;
    candidates.push({
      key,
      telemetryKey: info.telemetryKey,
      deprecatedIn: info.deprecatedIn,
      removeAfter: info.removeAfter,
      replacedBy: info.replacedBy,
      activeInstalls: usageCount,
      safeToRemove: usageCount === 0,
    });
  }
  return candidates;
}

function getRegistry() {
  return { ...COMPAT_REGISTRY };
}

module.exports = {
  COMPAT_REGISTRY,
  recordCompatUsage,
  getBootUsage,
  checkDeprecations,
  getRemovalCandidates,
  getRegistry,
};
