/**
 * Diagnostics Export Utility
 * 
 * Comprehensive diagnostics collection and export for the DailyNotification plugin
 * Provides detailed system information for debugging and support
 * 
 * @author Matthew Raymer
 * @version 1.0.0
 */

import { Capacitor } from '@capacitor/core'
import { 
  type PermissionStatus, 
  type NotificationStatus, 
  type ExactAlarmStatus 
} from './bridge'

export interface ComprehensiveDiagnostics {
  // Basic app information
  appVersion: string
  platform: string
  apiLevel: string
  timezone: string
  lastUpdated: string
  
  // Core status matrix fields
  postNotificationsGranted: boolean
  exactAlarmGranted: boolean
  channelEnabled: boolean
  batteryOptimizationsIgnored: boolean
  canScheduleNow: boolean
  lastError?: string
  
  // Detailed capabilities
  capabilities: {
    notificationStatus: NotificationStatus
    permissions: PermissionStatus
    exactAlarmStatus: ExactAlarmStatus
    
    // Browser/WebView information
    userAgent: string
    language: string
    platform: string
    cookieEnabled: boolean
    onLine: boolean
    hardwareConcurrency: number
    maxTouchPoints: number
    
    // Timing information
    timestamp: number
    timezoneOffset: number
    
    // Plugin availability
    pluginAvailable: boolean
    
    // Error context
    errorContext: {
      hasError: boolean
      errorMessage: string | null
      lastCheckTime: string
    }
    
    // Performance metrics
    performanceMetrics: {
      loadTime: number
      memoryUsage?: number
      connectionType?: string
    }
  }
  
  // System information
  systemInfo: {
    screenResolution: string
    colorDepth: number
    pixelRatio: number
    viewportSize: string
    devicePixelRatio: number
  }
  
  // Network information
  networkInfo: {
    connectionType: string
    effectiveType?: string
    downlink?: number
    rtt?: number
  }
  
  // Storage information
  storageInfo: {
    localStorageAvailable: boolean
    sessionStorageAvailable: boolean
    indexedDBAvailable: boolean
    webSQLAvailable: boolean
  }
}

export class DiagnosticsExporter {
  
  /**
   * Collect comprehensive diagnostics
   */
  async collectDiagnostics(
    notificationStatus: NotificationStatus,
    permissions: PermissionStatus,
    exactAlarmStatus: ExactAlarmStatus,
    pluginAvailable: boolean
  ): Promise<ComprehensiveDiagnostics> {
    
    const startTime = performance.now()
    
    // Collect system information
    const systemInfo = this.collectSystemInfo()
    
    // Collect network information
    const networkInfo = this.collectNetworkInfo()
    
    // Collect storage information
    const storageInfo = this.collectStorageInfo()
    
    // Calculate performance metrics
    const loadTime = performance.now() - startTime
    
    // Detect platform using Capacitor
    const platform = Capacitor.getPlatform()
    const platformDisplayName = platform.charAt(0).toUpperCase() + platform.slice(1)
    
    // API Level is Android-specific, show N/A for iOS/web
    const apiLevel = platform === 'android' ? 'Unknown' : 'N/A'
    
    return {
      appVersion: '1.0.0', // TODO: Get from app info
      platform: platformDisplayName,
      apiLevel: apiLevel, // TODO: Get from device info for Android
      timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
      lastUpdated: new Date().toLocaleString(),
      postNotificationsGranted: permissions.notifications === 'granted',
      exactAlarmGranted: exactAlarmStatus.enabled,
      channelEnabled: notificationStatus.isEnabled,
      batteryOptimizationsIgnored: false, // TODO: Check battery optimization status
      canScheduleNow: notificationStatus.isEnabled && permissions.notifications === 'granted',
      lastError: notificationStatus.error,
      capabilities: {
        notificationStatus,
        permissions,
        exactAlarmStatus,
        userAgent: navigator.userAgent,
        language: navigator.language,
        platform: navigator.platform,
        cookieEnabled: navigator.cookieEnabled,
        onLine: navigator.onLine,
        hardwareConcurrency: navigator.hardwareConcurrency || 0,
        maxTouchPoints: navigator.maxTouchPoints || 0,
        timestamp: Date.now(),
        timezoneOffset: new Date().getTimezoneOffset(),
        pluginAvailable,
        errorContext: {
          hasError: !!notificationStatus.error,
          errorMessage: notificationStatus.error || null,
          lastCheckTime: new Date().toISOString()
        },
        performanceMetrics: {
          loadTime,
          memoryUsage: this.getMemoryUsage(),
          connectionType: networkInfo.connectionType
        }
      },
      systemInfo,
      networkInfo,
      storageInfo
    }
  }
  
  /**
   * Collect system information
   */
  private collectSystemInfo(): {
    screenResolution: string
    colorDepth: number
    pixelRatio: number
    viewportSize: string
    devicePixelRatio: number
  } {
    return {
      screenResolution: `${screen.width}x${screen.height}`,
      colorDepth: screen.colorDepth,
      pixelRatio: window.devicePixelRatio || 1,
      viewportSize: `${window.innerWidth}x${window.innerHeight}`,
      devicePixelRatio: window.devicePixelRatio || 1
    }
  }
  
  /**
   * Collect network information
   */
  private collectNetworkInfo(): {
    connectionType: string
    effectiveType?: string
    downlink?: number
    rtt?: number
  } {
    const connection = (navigator as Navigator & { connection?: unknown }).connection || 
                      (navigator as Navigator & { mozConnection?: unknown }).mozConnection || 
                      (navigator as Navigator & { webkitConnection?: unknown }).webkitConnection
    
    return {
      connectionType: (connection as { type?: string })?.type || 'unknown',
      effectiveType: (connection as { effectiveType?: string })?.effectiveType,
      downlink: (connection as { downlink?: number })?.downlink,
      rtt: (connection as { rtt?: number })?.rtt
    }
  }
  
  /**
   * Collect storage information
   */
  private collectStorageInfo(): {
    localStorageAvailable: boolean
    sessionStorageAvailable: boolean
    indexedDBAvailable: boolean
    webSQLAvailable: boolean
  } {
    return {
      localStorageAvailable: this.isStorageAvailable('localStorage'),
      sessionStorageAvailable: this.isStorageAvailable('sessionStorage'),
      indexedDBAvailable: this.isStorageAvailable('indexedDB'),
      webSQLAvailable: this.isStorageAvailable('openDatabase')
    }
  }
  
  /**
   * Check if storage is available
   */
  private isStorageAvailable(type: string): boolean {
    try {
      const storage = (window as unknown as Record<string, unknown>)[type]
      if (!storage) return false
      
      if (type === 'indexedDB') {
        return !!storage
      }
      
      if (type === 'openDatabase') {
        return !!storage
      }
      
      // Test localStorage/sessionStorage
      const test = '__storage_test__'
      ;(storage as { setItem: (key: string, value: string) => void }).setItem(test, test)
      ;(storage as { removeItem: (key: string) => void }).removeItem(test)
      return true
    } catch {
      return false
    }
  }
  
  /**
   * Get memory usage (if available)
   */
  private getMemoryUsage(): number | undefined {
    const memory = (performance as Performance & { memory?: { usedJSHeapSize: number } }).memory
    return memory ? memory.usedJSHeapSize : undefined
  }
  
  /**
   * Export diagnostics as JSON string
   */
  exportAsJSON(diagnostics: ComprehensiveDiagnostics): string {
    return JSON.stringify(diagnostics, null, 2)
  }
  
  /**
   * Export diagnostics as CSV
   */
  exportAsCSV(diagnostics: ComprehensiveDiagnostics): string {
    const rows = [
      ['Field', 'Value'],
      ['App Version', diagnostics.appVersion],
      ['Platform', diagnostics.platform],
      ['API Level', diagnostics.apiLevel],
      ['Timezone', diagnostics.timezone],
      ['Last Updated', diagnostics.lastUpdated],
      ['Post Notifications Granted', diagnostics.postNotificationsGranted.toString()],
      ['Exact Alarm Granted', diagnostics.exactAlarmGranted.toString()],
      ['Channel Enabled', diagnostics.channelEnabled.toString()],
      ['Battery Optimizations Ignored', diagnostics.batteryOptimizationsIgnored.toString()],
      ['Can Schedule Now', diagnostics.canScheduleNow.toString()],
      ['Last Error', diagnostics.lastError || 'None'],
      ['Plugin Available', diagnostics.capabilities.pluginAvailable.toString()],
      ['User Agent', diagnostics.capabilities.userAgent],
      ['Language', diagnostics.capabilities.language],
      ['Platform', diagnostics.capabilities.platform],
      ['Online', diagnostics.capabilities.onLine.toString()],
      ['Hardware Concurrency', diagnostics.capabilities.hardwareConcurrency.toString()],
      ['Max Touch Points', diagnostics.capabilities.maxTouchPoints.toString()],
      ['Screen Resolution', diagnostics.systemInfo.screenResolution],
      ['Color Depth', diagnostics.systemInfo.colorDepth.toString()],
      ['Pixel Ratio', diagnostics.systemInfo.pixelRatio.toString()],
      ['Viewport Size', diagnostics.systemInfo.viewportSize],
      ['Connection Type', diagnostics.networkInfo.connectionType],
      ['Local Storage Available', diagnostics.storageInfo.localStorageAvailable.toString()],
      ['Session Storage Available', diagnostics.storageInfo.sessionStorageAvailable.toString()],
      ['IndexedDB Available', diagnostics.storageInfo.indexedDBAvailable.toString()],
      ['WebSQL Available', diagnostics.storageInfo.webSQLAvailable.toString()]
    ]
    
    return rows.map(row => row.map(cell => `"${cell}"`).join(',')).join('\n')
  }
  
  /**
   * Copy diagnostics to clipboard
   */
  async copyToClipboard(diagnostics: ComprehensiveDiagnostics, format: 'json' | 'csv' = 'json'): Promise<void> {
    const content = format === 'json' 
      ? this.exportAsJSON(diagnostics)
      : this.exportAsCSV(diagnostics)
    
    await navigator.clipboard.writeText(content)
  }
}

// Singleton instance
export const diagnosticsExporter = new DiagnosticsExporter()

// Utility functions
export async function collectDiagnostics(
  notificationStatus: NotificationStatus,
  permissions: PermissionStatus,
  exactAlarmStatus: ExactAlarmStatus,
  pluginAvailable: boolean
): Promise<ComprehensiveDiagnostics> {
  return diagnosticsExporter.collectDiagnostics(notificationStatus, permissions, exactAlarmStatus, pluginAvailable)
}

export function exportDiagnosticsAsJSON(diagnostics: ComprehensiveDiagnostics): string {
  return diagnosticsExporter.exportAsJSON(diagnostics)
}

export function exportDiagnosticsAsCSV(diagnostics: ComprehensiveDiagnostics): string {
  return diagnosticsExporter.exportAsCSV(diagnostics)
}

export async function copyDiagnosticsToClipboard(diagnostics: ComprehensiveDiagnostics, format: 'json' | 'csv' = 'json'): Promise<void> {
  return diagnosticsExporter.copyToClipboard(diagnostics, format)
}
