// AI Visibility Reporter - Background Module
// Batches and sends AI visibility events to the dashboard API

export class AIVisibilityReporter {
  constructor(config = {}) {
    this.apiUrl = config.apiUrl || 'https://api.portal.nithic.ai';
    this.enabled = config.enabled !== false;
    this.deviceId = config.deviceId || null;
    this.extensionVersion = config.extensionVersion || '2.0.0';
    this.apiKey = config.apiKey || null; // Tenant API key for auth

    // Batch queue
    this.queue = [];
    this.batchSize = 20;
    this.flushIntervalMs = 15000; // 15 seconds
    this.flushTimer = null;

    // Track active AI tabs for agent counting
    this.activeAITabs = new Map(); // tabId → { domain, service, since }

    this._startFlushTimer();
    console.log('✓ AI Visibility Reporter initialized');
  }

  /**
   * Record an AI visibility event
   */
  record(event) {
    if (!this.enabled) return;

    this.queue.push({
      event_type: event.eventType,
      ai_domain: event.domain,
      ai_service: event.service,
      user_id: this.deviceId,
      username: event.username || null,
      browser: this._getBrowserName(),
      browser_version: this._getBrowserVersion(),
      agent_id: this.deviceId,
      is_violation: event.isViolation || false,
      policy_name: event.policyName || null,
      alert_type: event.alertType || null,
      content_size: event.contentSize || 0,
      identity_domain: event.identityDomain || null,
      identity_type: event.identityType || 'unknown',
      metadata: event.metadata || {},
      created_at: new Date().toISOString()
    });

    // Flush immediately if batch is full
    if (this.queue.length >= this.batchSize) {
      this._flush();
    }
  }

  /**
   * Track a tab visiting an AI domain
   */
  trackTab(tabId, domain, service) {
    this.activeAITabs.set(tabId, { domain, service, since: Date.now() });
  }

  /**
   * Untrack a tab (navigated away or closed)
   */
  untrackTab(tabId) {
    this.activeAITabs.delete(tabId);
  }

  /**
   * Check if a tab is on an AI domain
   */
  getTabAIInfo(tabId) {
    return this.activeAITabs.get(tabId) || null;
  }

  /**
   * Flush queued events to the API
   */
  async _flush() {
    if (this.queue.length === 0) return;

    const batch = this.queue.splice(0, this.batchSize);

    try {
      const headers = { 'Content-Type': 'application/json' };
      if (this.apiKey) headers['X-API-Key'] = this.apiKey;

      const response = await fetch(`${this.apiUrl}/api/ai-visibility/events`, {
        method: 'POST',
        headers,
        body: JSON.stringify({ events: batch })
      });

      if (!response.ok) {
        console.warn(`AI Visibility: Failed to send batch (${response.status})`);
        // Re-queue failed events (at the front)
        this.queue.unshift(...batch);
        // Cap queue size
        if (this.queue.length > 200) {
          this.queue = this.queue.slice(0, 200);
        }
      }
    } catch (err) {
      console.warn('AI Visibility: Network error, will retry:', err.message);
      this.queue.unshift(...batch);
      if (this.queue.length > 200) {
        this.queue = this.queue.slice(0, 200);
      }
    }
  }

  _startFlushTimer() {
    if (this.flushTimer) clearInterval(this.flushTimer);
    this.flushTimer = setInterval(() => this._flush(), this.flushIntervalMs);
  }

  _getBrowserName() {
    const ua = navigator.userAgent;
    if (ua.includes('Edg/')) return 'Edge';
    if (ua.includes('Firefox/')) return 'Firefox';
    if (ua.includes('Chrome/')) return 'Chrome';
    if (ua.includes('Safari/')) return 'Safari';
    return 'Other';
  }

  _getBrowserVersion() {
    const ua = navigator.userAgent;
    const match = ua.match(/(Chrome|Edg|Firefox|Safari)\/(\d+[\d.]*)/);
    return match ? match[2] : null;
  }

  destroy() {
    if (this.flushTimer) clearInterval(this.flushTimer);
    this._flush(); // Final flush
  }
}
