// Log when the background script is loaded
console.log('Background script loaded');

// Function to check if chrome.runtime is initialized
function isChromeRuntimeReady() {
  // Check for our global initialization flags first
  if (typeof window.__qtWebChannelTransportReady === 'boolean' &&
      window.__qtWebChannelTransportReady === true) {
    return true;
  }
  
  // Check if the isChromeRuntimeInitialized function exists and use it
  if (typeof window.isChromeRuntimeInitialized === 'function') {
    return window.isChromeRuntimeInitialized();
  }
  
  // Fallback to basic checks
  return typeof chrome !== 'undefined' &&
         chrome.runtime &&
         typeof chrome.runtime.id === 'string';
}

// Function to wait for chrome.runtime to be initialized
function waitForChromeRuntime(callback, maxAttempts = 100) {
  let attempts = 0;
  
  function checkRuntime() {
    if (isChromeRuntimeReady()) {
      console.log('chrome.runtime API is ready');
      callback();
    } else if (attempts < maxAttempts) {
      attempts++;
      
      // Log less frequently to reduce console spam
      if (attempts === 1 || attempts % 10 === 0) {
        console.log(`Waiting for chrome.runtime API to initialize (attempt ${attempts}/${maxAttempts})...`);
      }
      
      // Try to trigger initialization if we're past several attempts
      if (attempts > 20 && attempts % 20 === 0) {
        console.log('Attempting to trigger chrome.runtime initialization');
        document.dispatchEvent(new CustomEvent('requestWebChannelTransport', {
          detail: { timestamp: Date.now() }
        }));
      }
      
      setTimeout(checkRuntime, 100);
    } else {
      console.error('ERROR: chrome.runtime API failed to initialize after multiple attempts');
      
      // Report initialization status if available
      if (typeof window.reportInitializationStatus === 'function') {
        window.reportInitializationStatus();
      } else {
        console.error('Initialization status:');
        console.error(`- chrome defined: ${typeof chrome !== 'undefined'}`);
        console.error(`- chrome.runtime defined: ${typeof chrome !== 'undefined' && typeof chrome.runtime !== 'undefined'}`);
        console.error(`- __qtWebChannelTransportReady: ${window.__qtWebChannelTransportReady}`);
      }
    }
  }
  
  checkRuntime();
}

// Add a listener for the chrome.runtime.initialized event
document.addEventListener('chrome.runtime.initialized', (event) => {
  console.log(`chrome.runtime API initialized for extension: ${event.detail.extensionId}`);
  initializeBackgroundFunctionality();
});

// Initialize all background functionality
function initializeBackgroundFunctionality() {
  // Verify chrome.runtime.onMessage exists before adding listener
  if (!chrome.runtime || !chrome.runtime.onMessage) {
    console.error('chrome.runtime.onMessage is not available');
    
    // Try to create it if it doesn't exist
    if (chrome.runtime && !chrome.runtime.onMessage) {
      console.log('Attempting to create chrome.runtime.onMessage');
      chrome.runtime.onMessage = {
        addListener: function(callback) {
          console.log('Added listener to newly created onMessage');
          if (!this.listeners) this.listeners = [];
          this.listeners.push(callback);
        },
        removeListener: function(callback) {
          if (!this.listeners) return;
          const index = this.listeners.indexOf(callback);
          if (index !== -1) {
            this.listeners.splice(index, 1);
          }
        },
        hasListener: function(callback) {
          return this.listeners && this.listeners.includes(callback);
        },
        listeners: []
      };
    }
  }
  
  // Now try to add the message listener
  try {
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      console.log('Background received message:', message);
      console.log('Sender:', sender);
      
      // Send a response back
      setTimeout(() => {
        sendResponse({
          received: true,
          from: 'background',
          timestamp: Date.now(),
          echo: message
        });
      }, 500); // Simulate some async processing
      
      return true; // Keep the message channel open for async response
    });
    console.log('Message listener set up successfully in background');
  } catch (e) {
    console.error('Failed to add message listener in background:', e);
  }

  // Verify chrome.runtime.onConnect exists before adding listener
  if (!chrome.runtime || !chrome.runtime.onConnect) {
    console.error('chrome.runtime.onConnect is not available');
    
    // Try to create it if it doesn't exist
    if (chrome.runtime && !chrome.runtime.onConnect) {
      console.log('Attempting to create chrome.runtime.onConnect');
      chrome.runtime.onConnect = {
        addListener: function(callback) {
          console.log('Added listener to newly created onConnect');
          if (!this.listeners) this.listeners = [];
          this.listeners.push(callback);
        },
        removeListener: function(callback) {
          if (!this.listeners) return;
          const index = this.listeners.indexOf(callback);
          if (index !== -1) {
            this.listeners.splice(index, 1);
          }
        },
        hasListener: function(callback) {
          return this.listeners && this.listeners.includes(callback);
        },
        listeners: []
      };
    }
  }
  
  // Now try to add the connect listener
  try {
    chrome.runtime.onConnect.addListener((port) => {
      console.log(`Port connected: ${port.name}`);
      
      // Listen for messages on this port
      port.onMessage.addListener((message) => {
        console.log(`Port message received on ${port.name}:`, message);
        
        // Send a response back through the port
        port.postMessage({
          received: true,
          from: 'background',
          timestamp: Date.now(),
          echo: message
        });
      });
      
      // Handle port disconnection
      port.onDisconnect.addListener(() => {
        console.log(`Port disconnected: ${port.name}`);
        if (chrome.runtime.lastError) {
          console.error('Port error:', chrome.runtime.lastError);
        }
      });
      
      // Send an initial message to the port
      port.postMessage({
        action: 'connected',
        from: 'background',
        timestamp: Date.now()
      });
    });
    console.log('Connect listener set up successfully in background');
  } catch (e) {
    console.error('Failed to add connect listener in background:', e);
  }

  // Start the ping interval
  startPingInterval();

  // Log extension information
  logExtensionInfo();
}

// Send a message to the popup every 10 seconds if it's open
function startPingInterval() {
  setInterval(() => {
    chrome.runtime.sendMessage({
      action: 'ping',
      from: 'background',
      timestamp: Date.now()
    }, (response) => {
      if (chrome.runtime.lastError) {
        // This is normal if the popup is not open
        console.log('Ping failed (popup probably closed):', chrome.runtime.lastError.message);
      } else {
        console.log('Ping response:', response);
      }
    });
  }, 10000);
}

// Log information about the extension
function logExtensionInfo() {
  console.log('Extension ID:', chrome.runtime.id);
  try {
    const manifest = chrome.runtime.getManifest();
    console.log('Manifest:', manifest);
  } catch (error) {
    console.error('Error getting manifest:', error);
  }
}

// Check if runtime is ready and initialize, or wait for it
if (isChromeRuntimeReady()) {
  console.log('chrome.runtime API is already available, initializing background');
  initializeBackgroundFunctionality();
} else {
  console.log('Waiting for chrome.runtime API to initialize...');
  // The initialization will happen when the chrome.runtime.initialized event fires
}