/**
 * @file PolicyManager.ts
 * Responsible for detecting device context & performance profile
 * and generating a responsive policy snapshot.
 */

export interface PolicySnapshot {
  device: 'mobile' | 'desktop';
  performance: 'low' | 'medium' | 'high';
  motion: 'reduced' | 'full';
  network: 'offline' | 'slow' | 'fast';
  timestamp: string;
}

export class PolicyManager {
  /** Detects device type based on window width & user agent */
  static detectDevice(): 'mobile' | 'desktop' {
    if (typeof window === 'undefined') return 'desktop';
    const width = window.innerWidth || 1024;
    return width < 768 ? 'mobile' : 'desktop';
  }

  /** Estimates performance using frame timing & hardware info */
  static detectPerformance(): 'low' | 'medium' | 'high' {
    if (typeof performance === 'undefined') return 'medium';
    const cores = (navigator as any)?.hardwareConcurrency || 4;
    if (cores <= 2) return 'low';
    if (cores >= 8) return 'high';
    return 'medium';
  }

  /** Detects user motion preference */
  static detectMotion(): 'reduced' | 'full' {
    if (typeof window === 'undefined') return 'full';
    return window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'reduced' : 'full';
  }

  /** Estimates network condition */
  static detectNetwork(): 'offline' | 'slow' | 'fast' {
    const nav = navigator as any;
    if (!nav?.connection) return 'fast';
    const { effectiveType } = nav.connection;
    if (!navigator.onLine) return 'offline';
    if (effectiveType.includes('2g')) return 'slow';
    return 'fast';
  }

  /** Generates complete snapshot of current context */
  static detect(): PolicySnapshot {
    return {
      device: this.detectDevice(),
      performance: this.detectPerformance(),
      motion: this.detectMotion(),
      network: this.detectNetwork(),
      timestamp: new Date().toISOString(),
    };
  }
}
