/**
 * =====================================================================
 *  LG webOS native player wrapper
 * =====================================================================
 *  webOS uses a hardware-accelerated player surfaced through the standard
 *  HTML5 <video> element when you append a special `mediaOption` JSON to
 *  the URL via the `|` (pipe) separator. The TV's media pipeline
 *  intercepts the URL, parses the JSON, and routes to the right
 *  decoder (HLS / MPEG-DASH / progressive / live MPEG-TS).
 *
 *  Because we still use a normal <video> element, all the existing
 *  React control surface (play/pause/timeline) keeps working — we only
 *  swap the URL.
 *
 *  All requests still flow through your cPanel proxy:
 *      `https://4kmovies.vip/nadiplayer/api/iptv-proxy?url=<…>`
 *  via `proxiedStreamUrl()` exactly like web/Android, so the User-Agent
 *  override and your CORS rules from `cors.php` apply identically.
 *
 *  Reference: webOS TV Developer Site → "Media Pipeline" → "Media
 *  Option Parameter".
 * =====================================================================
 */

import { isWebOSTV } from "./tvPlatform";

export interface WebOSMediaOptions {
  isLive?: boolean;
  /** "hls" | "mpegts" | "auto" — webOS calls this `mediaTransportType` */
  transport?: "hls" | "mpegts" | "auto";
  /** When true, request adaptive bitrate switching */
  adaptiveStreaming?: boolean;
  /** User-Agent to forward to the IPTV server */
  userAgent?: string;
}

/**
 * Build a webOS-flavoured URL the platform <video> element can play
 * natively. The pipe-separator passes a JSON `mediaOption` blob to the
 * TV's media pipeline.
 *
 * Example:
 *   https://4kmovies.vip/.../proxy?url=...m3u8|{"mediaTransportType":"HLS",...}
 */
export const buildWebOSStreamUrl = (
  url: string,
  opts: WebOSMediaOptions = {}
): string => {
  if (!isWebOSTV()) return url;

  const transport = (() => {
    if (opts.transport && opts.transport !== "auto") {
      return opts.transport.toUpperCase();
    }
    if (/\.m3u8(\?|$)/i.test(url)) return "HLS";
    if (/\.ts(\?|$)/i.test(url) || /\/live\//i.test(url)) return "MPEG-TS";
    if (/\.mpd(\?|$)/i.test(url)) return "DASH";
    return "URI";
  })();

  const mediaOption = {
    mediaTransportType: transport,
    option: {
      // Use the unified media stack — required for live MPEG-TS and HLS.
      htmlMediaOption: {
        useUMSMediaInfo: true,
      },
      // Adaptive bitrate (auto-pick highest stable level).
      adaptiveStreaming: {
        apsBitrate: opts.adaptiveStreaming === false ? 0 : 1,
        // Start low so the first frame appears fast on slow links.
        adaptiveResolution: "auto",
      },
      // Buffering tuned for live IPTV — short pre-roll, generous max.
      bufferingMinTime: 1000,
      bufferingMaxTime: 6000,
      // Live edge tolerance so the player can recover from network blips.
      ...(opts.isLive
        ? {
            liveBuffering: {
              minTime: 4000,
              maxTime: 12000,
            },
          }
        : {}),
      // Forward UA / extra headers via the http-header field.
      ...(opts.userAgent
        ? {
            httpHeader: `User-Agent: ${opts.userAgent}`,
          }
        : {}),
    },
  };

  // webOS expects a literal pipe between the URL and the JSON. The JSON
  // must be a single line (no whitespace) — `JSON.stringify` already
  // produces compact output.
  return `${url}|${JSON.stringify(mediaOption)}`;
};
