import type { DeviceCapabilities, DeviceTier } from './types';
import { DEFAULT_CONFIG } from './model-config';

/**
 * Detects device capabilities to suggest an optimal performance configuration.
 */
export function detectDeviceCapabilities(): DeviceCapabilities {
  const hasWebGL = (() => {
    try {
      const canvas = document.createElement('canvas');
      return !!(window.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')));
    } catch {
      return false;
    }
  })();

  const cpuCores = navigator.hardwareConcurrency || 2; // Default to 2 if undefined
  // @ts-expect-error - deviceMemory is not in all browsers
  const memory = navigator.deviceMemory || 1; // Default to 1GB if undefined

  let tier: DeviceTier;
  if (cpuCores >= 8 && memory >= 4) {
    tier = 'high';
  } else if (cpuCores >= 4 && memory >= 2) {
    tier = 'mid';
  } else {
    tier = 'low';
  }

  return { tier, hasWebGL, cpuCores, memory };
}

/**
 * Gets a recommended configuration based on the detected device tier.
 * @param capabilities The detected device capabilities.
 * @returns A full DetectionConfig with recommended settings.
 */
export function getRecommendedConfig(capabilities: DeviceCapabilities): typeof DEFAULT_CONFIG {
  const baseConfig = { ...DEFAULT_CONFIG };
  
  switch (capabilities.tier) {
    case 'high':
      return {
        ...baseConfig,
        modelVariant: 'standard',
        frameSkip: 6,
        confidenceThreshold: 0.8,
      };
    case 'mid':
      return {
        ...baseConfig,
        modelVariant: 'standard',
        frameSkip: 6,
        confidenceThreshold: 0.8,
      };
    case 'low':
    default:
      return {
        ...baseConfig,
        modelVariant: 'quantized',
        frameSkip: 6,
        confidenceThreshold: 0.8,
      };
  }
}
