/**
 * Shaka Player DRM Configuration
 */
import shaka from "shaka-player";
import { Logger } from "../utils/logger.js";

export async function setupShakaDRM(shakaPlayer, drmConfig = {}, logger = null) {
  const log = logger || new Logger("Shaka-DRM");
  
  if (!shakaPlayer || !drmConfig) {
    log.warn("Shaka DRM setup requires player and drmConfig");
    return;
  }

  const config = {
    drm: {
      servers: {},
      // retryParameters: {
      //   maxAttempts: 3,
      //   baseDelay: 1000,
      //   backoffFactor: 2,
      //   fuzzFactor: 0.1,
      //   timeout: 30000,
      // },
    },
    // streaming: {
    //   bufferBehind: 30,
    //   bufferingGoal: 10,
    //   rebufferingGoal: 2,
    //   bufferingGoalDefault: 10,
    //   rebufferingGoalDefault: 2,
    //   bufferBehindDefault: 30,
    // },
    // abr: {
    //   enabled: true,
    //   defaultBandwidthEstimate: 1000000,
    //   useNetworkInformation: true,
    // },
  };

  // Widevine
  if (
    drmConfig.widevine &&
    drmConfig.widevine.url &&
    drmConfig.widevine.licenseHeaders
  ) {
    config.drm.servers["com.widevine.alpha"] = drmConfig.widevine.url;

    // if (drmConfig.widevine.audioContentType) {
    //   config.drm["com.widevine.alpha"] = {
    //     audioContentType: drmConfig.widevine.audioContentType,
    //     videoContentType: drmConfig.widevine_0.videoContentType,
    //   };
    // }
  }

  let req, cert;

  // FairPlay
  const requestFairplay = Boolean(
    drmConfig.fairplay &&
      drmConfig.fairplay.certificateUrl &&
      drmConfig.fairplay.url &&
      drmConfig.fairplay.licenseHeaders
  );

  if (requestFairplay) {
    try {
      req = await fetch(
        drmConfig.fairplay.certificateUrl ??
          "https://lic.staging.drmtoday.com/license-server-fairplay/cert/orca"
      );
      cert = await req.arrayBuffer();

      config.drm.servers["com.apple.fps"] = drmConfig.fairplay.url;
      config.drm.advanced = {
        "com.apple.fps": {
          serverCertificate: new Uint8Array(cert),
        },
      };
    } catch (error) {
      log.error("Error fetching FairPlay certificate:", error);
    }
  }

  // playready
  if (
    drmConfig.playready &&
    drmConfig.playready.url &&
    drmConfig.playready.licenseHeaders
  ) {
    config.drm.servers["com.microsoft.playready"] = config.drm.servers[
      "com.microsoft.playready"
    ] = drmConfig.playready.url;
  }

  // Apply configuration
  try {
    shakaPlayer.configure(config);

    shakaPlayer
      .getNetworkingEngine()
      .registerRequestFilter(function (type, request) {
        if (type == shaka.net.NetworkingEngine.RequestType.LICENSE) {
          // request.headers["x-dt-auth-token"] = "your upfront token goes here";
          request.headers["x-dt-custom-data"] =
            drmConfig?.widevine?.licenseHeaders["x-dt-custom-data"] ??
            drmConfig?.fairplay?.licenseHeaders["x-dt-custom-data"] ??
            drmConfig?.playready?.licenseHeaders["x-dt-custom-data"];
        }
      });

    if (requestFairplay) {
      shakaPlayer
        .getNetworkingEngine()
        .registerResponseFilter((type, response) => {
          if (type === shaka.net.NetworkingEngine.RequestType.LICENSE) {
            if (shakaPlayer.keySystem() === "com.apple.fps") {
              let responseText = shaka.util.StringUtils.fromUTF8(response.data);
              response.data =
                shaka.util.Uint8ArrayUtils.fromBase64(responseText).buffer;
            }
          }
        });
    }

    // Event listener for errors
    shakaPlayer.addEventListener("error", (event) => {
      const error = event.detail;
      log.error("Shaka DRM Error:", error);
    });

    log.info("Shaka DRM configured successfully");
  } catch (error) {
    log.error("Error configuring Shaka DRM:", error);
  }
}

/**
 * Adaptive streaming
 */
export function setupAdaptiveStreaming(shakaPlayer, streamingConfig = {}) {
  const config = {
    streaming: {
      bufferBehind: 30,
      bufferingGoal: 10,
      rebufferingGoal: 2,
      ...streamingConfig,
    },
    abr: {
      enabled: true,
      defaultBandwidthEstimate: 1000000,
      useNetworkInformation: true,
      ...streamingConfig.abr,
    },
    manifest: {
      dash: {
        clockSyncUri: "",
        ignoreDrmInfo: false,
        ...streamingConfig.dash,
      },
      hls: {
        ...streamingConfig.hls,
      },
    },
  };

  shakaPlayer.configure(config);
}

/**
 * Bitrate management
 */
export function setupBitrateManagement(shakaPlayer, bitrateConfig = {}) {
  const config = {
    abr: {
      enabled: bitrateConfig.enabled !== false,
      defaultBandwidthEstimate: bitrateConfig.defaultBandwidth || 1000000,
      useNetworkInformation: bitrateConfig.useNetworkInfo !== false,
      restrictions: {
        minWidth: bitrateConfig.minWidth,
        maxWidth: bitrateConfig.maxWidth,
        minPixels: bitrateConfig.minPixels,
        maxPixels: bitrateConfig.maxPixels,
        minFrameRate: bitrateConfig.minFrameRate,
        maxFrameRate: bitrateConfig.maxFrameRate,
        minBandwidth: bitrateConfig.minBandwidth,
        maxBandwidth: bitrateConfig.maxBandwidth,
      },
    },
  };

  shakaPlayer.configure(config);
}

/**
 * Caption/subtitle
 */
export function setupTextTracks(shakaPlayer, textConfig = {}) {
  if (textConfig.preferredLanguages) {
    shakaPlayer.configure({
      preferredAudioLanguage: textConfig.preferredLanguages.audio || "en",
      preferredTextLanguage: textConfig.preferredLanguages.text || "en",
    });
  }

  if (textConfig.tryStartWithClosedCaptions) {
    shakaPlayer.configure({
      textTrackRestrictions: {
        onlyForcedSubtitles: false,
      },
    });
  }
}

export default {
  setupShakaDRM,
  setupAdaptiveStreaming,
  setupBitrateManagement,
  setupTextTracks,
};
