import { ExtendedDRMConfig, DRMInitResult, DRMErrorCode } from './types/DRMTypes';
import { DRMErrorHandler } from './utils/DRMErrorHandler';
import { BrowserDetector } from './utils/BrowserDetector';
import { BaseDRM } from './systems/BaseDRM';
import { WidevineDRM } from './systems/WidevineDRM';
import { FairPlayDRM } from './systems/FairPlayDRM';
import { PlayReadyDRM } from './systems/PlayReadyDRM';

export class DRMManager {
  private video: HTMLVideoElement;
  private config: ExtendedDRMConfig;
  private debug: boolean;
  private activeDRM: BaseDRM | null = null;

  constructor(video: HTMLVideoElement, config: ExtendedDRMConfig, debug: boolean = false) {
    this.video = video;
    this.config = config;
    this.debug = debug;
  }

  async initialize(): Promise<DRMInitResult> {
    const type = this.config.type || 'auto';

    if (type !== 'auto') {
      return this.initSpecific(type);
    }

    // Auto-detect: try each system based on browser capabilities
    const caps = await BrowserDetector.detectCapabilities();
    this.log('DRM capabilities:', caps);

    if (BrowserDetector.isSafari() && caps.fairplay && this.config.certificateUrl) {
      return this.initSpecific('fairplay');
    }
    if (caps.widevine) {
      return this.initSpecific('widevine');
    }
    if (caps.playready) {
      return this.initSpecific('playready');
    }

    return {
      success: false,
      error: DRMErrorHandler.createError(DRMErrorCode.UNSUPPORTED, 'No supported DRM system found in this browser'),
    };
  }

  private async initSpecific(type: 'widevine' | 'fairplay' | 'playready'): Promise<DRMInitResult> {
    switch (type) {
      case 'widevine':
        this.activeDRM = new WidevineDRM(this.video, this.config, this.debug);
        break;
      case 'fairplay':
        this.activeDRM = new FairPlayDRM(this.video, this.config, this.debug);
        break;
      case 'playready':
        this.activeDRM = new PlayReadyDRM(this.video, this.config, this.debug);
        break;
    }
    return this.activeDRM.initialize();
  }

  getHLSConfig(): Record<string, any> {
    return this.activeDRM?.getHLSConfig() || {};
  }

  getDashProtectionData(): Record<string, any> {
    return this.activeDRM?.getDashProtectionData() || {};
  }

  async destroy(): Promise<void> {
    if (this.activeDRM) {
      await this.activeDRM.destroy();
      this.activeDRM = null;
    }
  }

  private log(...args: any[]): void {
    if (this.debug) console.log('[DRMManager]', ...args);
  }
}
