// Auto Update Checker for Auto Auditor Extension
// Checks for new versions and notifies the user

class UpdateChecker {
  constructor() {
    this.updateCheckInterval = 24 * 60 * 60 * 1000; // Check once per day
    this.versionUrl = 'https://raw.githubusercontent.com/berean-ai/auto-auditor/main/VERSION.txt';
    this.downloadUrl = 'https://github.com/berean-ai/auto-auditor/releases/latest/download/auto-auditor.zip';
    this.init();
  }

  init() {
    console.log('[Berean] Update checker initialized');
    
    // Check on startup
    this.checkForUpdates();
    
    // Check periodically
    setInterval(() => this.checkForUpdates(), this.updateCheckInterval);
    
    // Also check when extension is opened
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.action === 'checkUpdates') {
        this.checkForUpdates();
        sendResponse({ status: 'checking' });
      }
    });
  }

  async checkForUpdates() {
    try {
      const currentVersion = chrome.runtime.getManifest().version;
      console.log('[Berean] Current version:', currentVersion);
      
      // Fetch latest version info
      const response = await fetch(this.versionUrl);
      if (!response.ok) {
        console.log('[Berean] Could not check for updates');
        return;
      }
      
      const latestVersion = (await response.text()).trim();
      console.log('[Berean] Latest version available:', latestVersion);
      
      // Compare versions
      if (this.isNewerVersion(latestVersion, currentVersion)) {
        console.log('[Berean] New version available!');
        this.notifyUpdate(latestVersion);
      }
    } catch (error) {
      console.log('[Berean] Update check failed:', error.message);
    }
  }

  isNewerVersion(latest, current) {
    const latestParts = latest.split('.').map(Number);
    const currentParts = current.split('.').map(Number);
    
    for (let i = 0; i < Math.max(latestParts.length, currentParts.length); i++) {
      const latestPart = latestParts[i] || 0;
      const currentPart = currentParts[i] || 0;
      
      if (latestPart > currentPart) return true;
      if (latestPart < currentPart) return false;
    }
    
    return false;
  }

  notifyUpdate(newVersion) {
    // Check if user has already been notified about this version
    chrome.storage.local.get('lastNotifiedVersion', (data) => {
      if (data.lastNotifiedVersion === newVersion) {
        return; // Already notified
      }
      
      // Store that we notified about this version
      chrome.storage.local.set({ lastNotifiedVersion: newVersion });
      
      // Create notification
      chrome.notifications.create('berean-update', {
        type: 'basic',
        iconUrl: chrome.runtime.getURL('icons/icon-128.png'),
        title: 'Watchman Update Available',
        message: `Version ${newVersion} is now available. Click to download.`,
        buttons: [
          { title: 'Download' },
          { title: 'Dismiss' }
        ]
      });
    });
  }

  static handleNotificationClick(notificationId, buttonIndex) {
    if (notificationId === 'berean-update') {
      if (buttonIndex === 0) {
        // Download button clicked
        chrome.tabs.create({ url: this.downloadUrl });
      }
      chrome.notifications.clear(notificationId);
    }
  }
}

// Initialize update checker
const updateChecker = new UpdateChecker();

// Handle notification clicks
chrome.notifications.onButtonClicked.addListener((notificationId, buttonIndex) => {
  UpdateChecker.handleNotificationClick(notificationId, buttonIndex);
});
