/**
 * Suppress known noisy runtime deprecations from transitive dependencies while
 * keeping all other warnings visible.
 */
export function shouldSuppressNodeWarning(code: string | undefined, message: string): boolean {
  if (code === 'DEP0040') {
    return true;
  }
  return /`punycode` module is deprecated/i.test(message);
}

export function installNodeWarningFilter(): void {
  const stateKey = Symbol.for('flynn.nodeWarningFilterInstalled');
  const globalState = globalThis as Record<PropertyKey, unknown>;
  if (globalState[stateKey]) {
    return;
  }
  globalState[stateKey] = true;

  const originalEmitWarning = process.emitWarning.bind(process);

  process.emitWarning = ((warning: unknown, ...args: unknown[]) => {
    const message = warning instanceof Error
      ? warning.message
      : typeof warning === 'string'
        ? warning
        : String(warning);

    let code: string | undefined;
    if (warning instanceof Error && typeof (warning as { code?: unknown }).code === 'string') {
      code = (warning as { code?: string }).code;
    }
    if (typeof args[0] === 'string') {
      code = args[0];
    } else if (args[0] && typeof args[0] === 'object' && typeof (args[0] as { code?: unknown }).code === 'string') {
      code = (args[0] as { code?: string }).code;
    }

    if (shouldSuppressNodeWarning(code, message)) {
      return;
    }

    (originalEmitWarning as (...params: unknown[]) => void)(warning, ...args);
  }) as typeof process.emitWarning;
}

installNodeWarningFilter();
