// Background service worker for DCS Credit Application Extension

console.log('DCS Extension background script loaded');

// Listen for extension installation
chrome.runtime.onInstalled.addListener((details) => {
  console.log('DCS Credit Application Extension installed successfully');
  if (details.reason === 'install') {
    console.log('Welcome to DCS Credit Application Processor!');
  }
});

// Listen for messages from popup and content scripts
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('Background received message:', request.action);
  
  try {
    switch (request.action) {
      case 'checkServerConnection':
        checkPythonServer().then(isConnected => {
          sendResponse({ connected: isConnected });
        }).catch(error => {
          console.error('Server connection check failed:', error);
          sendResponse({ connected: false, error: error.message });
        });
        return true; // Keep message channel open for async response
        
      case 'getStoredData':
        chrome.storage.local.get(['extractedData']).then(result => {
          sendResponse({ data: result.extractedData });
        }).catch(error => {
          console.error('Storage retrieval failed:', error);
          sendResponse({ data: null, error: error.message });
        });
        return true; // Keep message channel open for async response

      case 'forwardToContentScript':
        // Fallback method to communicate with content script through background
        handleContentScriptForwarding(request, sender, sendResponse);
        return true; // Keep message channel open for async response
        
      case 'storeDataForFallback':
        // Store extraction data as fallback
        chrome.storage.local.set({
          fallbackData: request.data,
          fallbackTimestamp: Date.now()
        }).then(() => {
          sendResponse({ success: true });
        }).catch(error => {
          console.error('Fallback storage failed:', error);
          sendResponse({ success: false, error: error.message });
        });
        return true;
        
      case 'healthCheck':
        // Background service health check
        sendResponse({ 
          success: true, 
          message: 'Background service running',
          timestamp: Date.now()
        });
        break;
        
      default:
        sendResponse({ 
          success: true, 
          message: 'Background service running' 
        });
    }
  } catch (error) {
    console.error('Background service error:', error);
    sendResponse({ success: false, error: error.message });
  }
});

// Handle content script message forwarding as fallback communication
async function handleContentScriptForwarding(request, sender, sendResponse) {
  try {
    const { targetTabId, originalAction, originalData } = request;
    
    // Forward message to content script in specified tab
    chrome.tabs.sendMessage(targetTabId, {
      action: originalAction,
      data: originalData,
      forwardedFromBackground: true
    }, (response) => {
      if (chrome.runtime.lastError) {
        console.error('Content script forwarding failed:', chrome.runtime.lastError.message);
        sendResponse({
          success: false,
          error: `Content script communication failed: ${chrome.runtime.lastError.message}`
        });
      } else {
        sendResponse({
          success: true,
          data: response
        });
      }
    });
  } catch (error) {
    console.error('Error in content script forwarding:', error);
    sendResponse({
      success: false,
      error: error.message
    });
  }
}

// Monitor tab updates to detect DCS pages
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete' && tab.url) {
    checkForDCSPage(tab);
  }
});

// Check if page might be a DCS credit application
function checkForDCSPage(tab) {
  const url = tab.url.toLowerCase();
  const title = tab.title.toLowerCase();
  
  const dcsIndicators = [
    'credit application',
    'dcs',
    'dealer credit',
    'finance application'
  ];

  const isDCSPage = dcsIndicators.some(indicator => 
    url.includes(indicator) || title.includes(indicator)
  );

  if (isDCSPage) {
    // Update extension badge to indicate DCS page
    chrome.action.setBadgeText({ 
      text: 'DCS',
      tabId: tab.id 
    });
    chrome.action.setBadgeBackgroundColor({ 
      color: '#4CAF50',
      tabId: tab.id 
    });
  } else {
    // Clear badge for non-DCS pages
    chrome.action.setBadgeText({ 
      text: '',
      tabId: tab.id 
    });
  }
}

// Check Python server connection
async function checkPythonServer() {
  try {
    // Get API URL from settings
    const settings = await chrome.storage.local.get(['apiUrl']);
    const apiUrl = settings.apiUrl || 'http://localhost:8000';
    
    const response = await fetch(`${apiUrl}/health`, {
      method: 'GET',
      signal: AbortSignal.timeout(2000)
    });
    return response.ok;
  } catch (error) {
    return false;
  }
}

console.log('DCS Extension background service initialized');