(() => {
  if (window.__MMW_QINGTAI_INTERCEPTOR__) return;
  window.__MMW_QINGTAI_INTERCEPTOR__ = true;

  const MESSAGE_ACTION = "intercepted-data";
  const MARKER_ATTR = "data-mmw-qingtai-interceptor";
  const ALLOWED_HOSTS = new Set([
    "compass.jinritemai.com",
    "buyin.jinritemai.com",
    "cc.oceanengine.com"
  ]);
  const CAPTURE_PATH_PREFIXES = [
    "/compass_api/",
    "/square_pc_api/",
    "/api/anchor/",
    "/creative_radar_api/"
  ];
  const MAX_LEAVES = 800;

  document.documentElement?.setAttribute(MARKER_ATTR, "1");

  function normalizeCaptureUrl(value) {
    try {
      const url = new URL(String(value || ""), location.href);
      if (url.protocol !== "https:" || !ALLOWED_HOSTS.has(url.hostname)) return "";
      if (!CAPTURE_PATH_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))) return "";
      return `${url.origin}${url.pathname}`;
    } catch {
      return "";
    }
  }

  function getResponseBody(xhr) {
    switch (xhr.responseType) {
      case "arraybuffer":
      case "blob":
      case "document":
        return null;
      case "json":
        return xhr.response;
      default:
        return xhr.responseText;
    }
  }

  function parsePayload(body) {
    if (!body) return null;
    if (typeof body === "object") return body;
    if (typeof body !== "string") return null;
    try {
      return JSON.parse(body);
    } catch {
      return null;
    }
  }

  function emit(requestUrl, leaves) {
    if (!requestUrl || !leaves.length) return;
    window.postMessage({ action: MESSAGE_ACTION, data: { request_url: requestUrl, leaves } }, "*");
  }

  function handleXhrResult(xhr) {
    const request = xhr.__mmwRequestInfo;
    if (!request?.url) return;

    const requestUrl = normalizeCaptureUrl(request.url);
    if (!requestUrl) return;

    const payload = parsePayload(getResponseBody(xhr));
    if (!payload) return;

    emit(requestUrl, minimizePayload(payload));
  }

  function handleFetchResult(requestUrl, response) {
    const normalizedUrl = normalizeCaptureUrl(requestUrl);
    if (!normalizedUrl || !response?.ok || typeof response.clone !== "function") return;

    response.clone().json().then((payload) => {
      if (!payload) return;
      emit(normalizedUrl, minimizePayload(payload));
    }).catch(() => {});
  }

  function minimizePayload(payload) {
    const root = payload && typeof payload === "object" && !Array.isArray(payload) && "data" in payload
      ? payload.data
      : payload;
    const leaves = [];
    const seen = new WeakSet();
    walk(root, [], 0);
    return leaves;

    function walk(value, path, depth) {
      if (leaves.length >= MAX_LEAVES || depth > 18 || value == null) return;
      if (typeof value !== "object") {
        const key = String(path[path.length - 1] || "");
        const text = String(value ?? "").trim();
        const idCandidate = /(^|_)(id|itemid|videoid|materialid|groupid|contentid)$/i.test(key.replace(/[^A-Za-z0-9_]/g, ""))
          && /^[0-9]{5,40}$/.test(text);
        const mediaCandidate = /(image|img|cover|pic|uri|url)/i.test(key) && text.length > 3 && text.length <= 2048;
        if (idCandidate || mediaCandidate) leaves.push({ path: path.join("."), value: text });
        return;
      }
      if (seen.has(value)) return;
      seen.add(value);
      if (Array.isArray(value)) {
        value.slice(0, 600).forEach((item, index) => walk(item, [...path, String(index)], depth + 1));
        return;
      }
      Object.entries(value).slice(0, 300).forEach(([key, item]) => walk(item, [...path, key], depth + 1));
    }
  }

  function patchXhr() {
    if (typeof XMLHttpRequest !== "function") return;

    const nativeOpen = XMLHttpRequest.prototype.open;
    const nativeSend = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function(...args) {
      this.__mmwRequestInfo = {
        method: args[0],
        url: String(args[1] || "")
      };
      return nativeOpen.apply(this, args);
    };

    XMLHttpRequest.prototype.send = function(...args) {
      const xhr = this;
      const original = xhr.onreadystatechange;

      xhr.onreadystatechange = function(...callbackArgs) {
        if (xhr.readyState === 4) {
          handleXhrResult(xhr);
        }
        if (typeof original === "function") {
          return original.apply(this, callbackArgs);
        }
      };

      return nativeSend.apply(this, args);
    };
  }

  function patchFetch() {
    if (typeof window.fetch !== "function") return;

    const nativeFetch = window.fetch;
    window.fetch = function(...args) {
      const requestUrl = typeof Request === "function" && args[0] instanceof Request
        ? args[0].url
        : String(args[0] || "");
      const result = nativeFetch.apply(this, args);
      Promise.resolve(result).then((response) => handleFetchResult(requestUrl, response)).catch(() => {});
      return result;
    };
  }

  patchXhr();
  patchFetch();
})();
