(() => {
  if (globalThis.MMWSourceTraceSelector) return;

  const VIDEO_URL_RE = /(?:\.mp4(?:$|[?#])|\.mov(?:$|[?#])|\.m4v(?:$|[?#])|\.webm(?:$|[?#])|\.m3u8(?:$|[?#])|\.mpd(?:$|[?#])|video|play|stream|vod|bytev|douyin|ixigua)/i;
  const IMAGE_URL_RE = /\.(?:jpe?g|png|gif|webp|avif|bmp)(?:$|[?#])/i;
  const MEDIA_KEYS = new Set([
    "source", "sources", "source_candidates", "sourceCandidates",
    "videos", "video_list", "videoList", "video_fullinfo", "video_full_info",
    "resources", "resource_list", "resourceList", "media", "medias",
    "Original", "original",
  ]);
  const ORIGINAL_KEYS = new Set([
    "original", "isoriginal", "originalvideo", "isoriginalvideo", "originvideo", "sourceoriginal",
  ]);
  const ORIGINAL_META_KEYS = new Set([
    "definition", "format", "gearname", "label", "name", "quality", "qualitylabel", "resolution", "type",
  ]);
  const ORIGINAL_MARKERS = ["original", "原视频", "原画", "原始视频"];

  function number(value) {
    const parsed = Number(value);
    return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
  }

  function sizeBytes(value) {
    if (value === null || value === undefined || value === "") return 0;
    if (typeof value === "number") return Math.max(0, Math.trunc(value));
    const text = String(value).trim().replaceAll(",", "");
    if (!text) return 0;
    if (/^\d+(?:\.\d+)?$/.test(text)) return Math.max(0, Math.trunc(Number(text)));
    const match = text.match(/([0-9]+(?:\.[0-9]+)?)\s*(b|bytes?|k|kb|kib|m|mb|mib|g|gb|gib|t|tb|tib|字节)/i);
    if (!match) return 0;
    const unit = match[2].toLowerCase();
    const multiplier = {
      b: 1, byte: 1, bytes: 1, "字节": 1,
      k: 1024, kb: 1024, kib: 1024,
      m: 1024 ** 2, mb: 1024 ** 2, mib: 1024 ** 2,
      g: 1024 ** 3, gb: 1024 ** 3, gib: 1024 ** 3,
      t: 1024 ** 4, tb: 1024 ** 4, tib: 1024 ** 4,
    }[unit] || 1;
    return Math.max(0, Math.trunc(Number(match[1]) * multiplier));
  }

  function bitrate(value) {
    if (typeof value === "number") return Math.max(0, Math.trunc(value));
    const match = String(value || "").toLowerCase().replaceAll(",", "").match(/([0-9]+(?:\.[0-9]+)?)\s*([kmg]?)(?:bit|bps|b\/s)?/);
    if (!match) return 0;
    const multiplier = { "": 1, k: 1000, m: 1000 ** 2, g: 1000 ** 3 }[match[2]] || 1;
    return Math.max(0, Math.trunc(Number(match[1]) * multiplier));
  }

  function normalizedKey(value) {
    return String(value || "").trim().toLowerCase().replace(/[^a-z0-9]+/g, "");
  }

  function hasOriginalMarker(value) {
    const text = String(value || "").trim().toLowerCase();
    return ORIGINAL_MARKERS.some((marker) => text.includes(marker));
  }

  function isOriginalMedia(value, context = "") {
    if (ORIGINAL_KEYS.has(normalizedKey(context)) || hasOriginalMarker(context)) return true;
    if (!value || typeof value !== "object" || Array.isArray(value)) return false;
    for (const [key, candidate] of Object.entries(value)) {
      const normalized = normalizedKey(key);
      if (ORIGINAL_KEYS.has(normalized)) {
        if (candidate === true || (candidate && typeof candidate === "object")) return true;
        const text = String(candidate || "").trim().toLowerCase();
        if (["1", "true", "yes", "y", "original"].includes(text) || /^https?:\/\//i.test(text) || hasOriginalMarker(text)) {
          return true;
        }
      }
      if (ORIGINAL_META_KEYS.has(normalized) && hasOriginalMarker(candidate)) return true;
    }
    return false;
  }

  function mediaUrl(value) {
    if (!value || typeof value !== "object") return "";
    const keys = [
      "Original", "original", "original_url", "originalUrl", "origin_url", "originUrl",
      "download_url", "downloadUrl", "url", "play_url", "playUrl", "video_url",
      "videoUrl", "source_url", "sourceUrl", "main_url", "mainUrl", "src",
      "下载地址", "源视频地址", "链接",
    ];
    for (const key of keys) {
      const candidate = value[key];
      if (typeof candidate === "string" && /^https?:\/\//i.test(candidate.trim())) return candidate.trim();
    }
    for (const key of ["url_list", "urlList", "urls", "play_addr", "playAddr", "download_addr", "downloadAddr"]) {
      const candidate = value[key];
      if (typeof candidate === "string" && /^https?:\/\//i.test(candidate.trim())) return candidate.trim();
      if (Array.isArray(candidate)) {
        for (const item of candidate) {
          if (typeof item === "string" && /^https?:\/\//i.test(item.trim())) return item.trim();
          const nested = mediaUrl(item);
          if (nested) return nested;
        }
      }
      const nested = mediaUrl(candidate);
      if (nested) return nested;
    }
    return "";
  }

  function normalizeMedia(value, context = "") {
    const original = isOriginalMedia(value, context);
    if (typeof value === "string") value = { download_url: value };
    if (!value || typeof value !== "object" || Array.isArray(value)) return null;
    const url = mediaUrl(value);
    if (!url || IMAGE_URL_RE.test(url) || (!original && !VIDEO_URL_RE.test(url))) return null;
    const bytes = [
      "size_bytes", "sizeBytes", "bytes", "file_size", "fileSize", "fileSizeBytes",
      "content_length", "contentLength", "resource_size", "resourceSize", "video_size",
      "resource_value", "resourceValue", "videoSize", "video_file_size", "videoFileSize",
      "origin_size", "originSize", "data_size", "dataSize", "file_bytes", "fileBytes",
      "filesize", "文件字节", "文件大小", "视频大小", "资源大小", "资源值", "size", "大小",
    ].map((key) => sizeBytes(value[key])).find(Boolean) || 0;
    return {
      ...value,
      download_url: url,
      size_bytes: bytes,
      size_text: String(value.size_text || value.sizeText || value.size_label || value.大小 || value.文件大小 || value.size || "").trim(),
      resolution: String(value.resolution || value.definition || value.quality || value.quality_label || value.qualityLabel || value.清晰度 || value.分辨率 || "").trim(),
      bitrate: bitrate(value.bitrate || value.bit_rate || value.bitRate || value.bps),
      width: number(value.width || value.video_width || value.videoWidth),
      height: number(value.height || value.video_height || value.videoHeight),
      is_original: original,
    };
  }

  function resolutionScore(media) {
    const pixels = number(media?.width) * number(media?.height);
    const text = String(media?.resolution || "").toLowerCase();
    const dimensions = text.match(/([0-9]{2,5})\s*[x×*]\s*([0-9]{2,5})/);
    const dimensionPixels = dimensions ? Number(dimensions[1]) * Number(dimensions[2]) : 0;
    const k = text.match(/([0-9]+(?:\.[0-9]+)?)\s*k/);
    const width = k ? Number(k[1]) * 1000 : 0;
    const kPixels = width ? width * Math.trunc(width * 9 / 16) : 0;
    const height = Math.max(0, ...((text.match(/\d+/g) || []).map(Number)));
    const labelPixels = height ? height * Math.trunc(height * 16 / 9) : 0;
    return Math.max(pixels, dimensionPixels, kPixels, labelPixels);
  }

  function rank(media) {
    return [media?.is_original ? 1 : 0, resolutionScore(media), number(media?.bitrate), number(media?.size_bytes)];
  }

  function isBetter(left, right) {
    const a = rank(left);
    const b = rank(right);
    for (let index = 0; index < a.length; index += 1) {
      if (a[index] !== b[index]) return a[index] > b[index];
    }
    return false;
  }

  function mergeMedia(preferred, fallback) {
    const result = { ...preferred };
    for (const key of ["resolution", "size_text"]) {
      if (!result[key] && fallback?.[key]) result[key] = fallback[key];
    }
    for (const key of ["size_bytes", "bitrate", "width", "height"]) {
      result[key] = Math.max(number(result[key]), number(fallback?.[key]));
    }
    result.is_original = Boolean(result.is_original || fallback?.is_original);
    return result;
  }

  function collectMediaCandidates(payload) {
    const values = [];
    const visited = new Set();
    function visit(value, context = "", depth = 0) {
      if (!value || depth > 8 || (typeof value !== "object" && typeof value !== "string")) return;
      if (typeof value === "object") {
        if (visited.has(value)) return;
        visited.add(value);
      }
      const media = normalizeMedia(value, context);
      if (media && (MEDIA_KEYS.has(context) || context === "" || value.size_bytes || value.size || value.file_size || value.fileSize)) {
        values.push(media);
      }
      if (Array.isArray(value)) {
        for (const item of value) visit(item, context, depth + 1);
        return;
      }
      if (!value || typeof value !== "object") return;
      for (const [key, child] of Object.entries(value)) {
        if (MEDIA_KEYS.has(key) || ["data", "result", "payload"].includes(key)) visit(child, key, depth + 1);
      }
    }
    visit(payload);
    const byUrl = new Map();
    for (const media of values) {
      const current = byUrl.get(media.download_url);
      if (!current) {
        byUrl.set(media.download_url, media);
        continue;
      }
      const preferred = isBetter(media, current) ? media : current;
      const fallback = preferred === media ? current : media;
      byUrl.set(media.download_url, mergeMedia(preferred, fallback));
    }
    return [...byUrl.values()].sort((left, right) => isBetter(left, right) ? -1 : (isBetter(right, left) ? 1 : 0));
  }

  function selectLargestCandidate(candidates) {
    return candidates.reduce((largest, item) => {
      if (!largest) return item;
      const itemSize = number(item?.size_bytes);
      const largestSize = number(largest?.size_bytes);
      if (itemSize !== largestSize) return itemSize > largestSize ? item : largest;
      return isBetter(item, largest) ? item : largest;
    }, null);
  }

  function selectLargestMedia(payload) {
    return selectLargestCandidate(collectMediaCandidates(payload));
  }

  function selectPreferredMedia(payload) {
    const candidates = collectMediaCandidates(payload);
    return candidates.find((item) => item?.is_original) || selectLargestCandidate(candidates);
  }

  globalThis.MMWSourceTraceSelector = Object.freeze({
    collectMediaCandidates,
    isOriginalMedia,
    normalizeMedia,
    selectLargestMedia,
    selectPreferredMedia,
  });
})();
