/**
 * DSS Telemetry - Browser Error Capture
 * Automatically captures all console errors, uncaught exceptions, and promise rejections
 * Sends telemetry to backend for monitoring and auto-fixing
 */
(function() {
  'use strict';

  const TELEMETRY_ENDPOINT = '/api/telemetry/log';
  const originalError = console.error;
  const originalWarn = console.warn;

  // Buffer for batching (optional optimization)
  let errorBuffer = [];
  let flushTimeout = null;

  /**
   * Send log data to backend telemetry endpoint
   */
  function sendLog(data) {
    const payload = JSON.stringify({
      ...data,
      timestamp: new Date().toISOString(),
      url: window.location.href,
      userAgent: navigator.userAgent
    });

    // Use sendBeacon for reliability (works even on page unload)
    if (navigator.sendBeacon) {
      const blob = new Blob([payload], { type: 'application/json' });
      navigator.sendBeacon(TELEMETRY_ENDPOINT, blob);
    } else {
      // Fallback to fetch with keepalive
      fetch(TELEMETRY_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: payload,
        keepalive: true
      }).catch(err => {
        // Silently fail - don't want telemetry errors to break the app
        console.debug('[Telemetry] Failed to send log:', err);
      });
    }
  }

  /**
   * 1. Capture Global Uncaught Errors
   */
  window.addEventListener('error', function(event) {
    sendLog({
      type: 'uncaught',
      level: 'error',
      message: event.message,
      filename: event.filename,
      lineno: event.lineno,
      colno: event.colno,
      stack: event.error?.stack || 'No stack trace available'
    });
  });

  /**
   * 2. Capture Unhandled Promise Rejections
   */
  window.addEventListener('unhandledrejection', function(event) {
    sendLog({
      type: 'promise',
      level: 'error',
      message: String(event.reason),
      stack: event.reason?.stack || 'No stack trace available'
    });
  });

  /**
   * 3. Intercept console.error
   */
  console.error = function(...args) {
    sendLog({
      type: 'console',
      level: 'error',
      message: args.map(arg => {
        if (typeof arg === 'object') {
          try {
            return JSON.stringify(arg);
          } catch {
            return String(arg);
          }
        }
        return String(arg);
      }).join(' ')
    });

    // Call original console.error so logs still appear in DevTools
    originalError.apply(console, args);
  };

  /**
   * 4. Optionally capture console.warn (for comprehensive monitoring)
   */
  console.warn = function(...args) {
    sendLog({
      type: 'console',
      level: 'warn',
      message: args.map(arg => String(arg)).join(' ')
    });

    originalWarn.apply(console, args);
  };

  // Log telemetry initialization
  console.debug('[Telemetry] Browser error capture initialized');

})();
