(function installPddFeePageHook() {
  if (window.__PDD_FEE_PAGE_HOOK__) return;
  window.__PDD_FEE_PAGE_HOOK__ = true;

  const SOURCE = "pdd-fee-network-hook";
  const TARGET_PATHS = [
    "/sydney/api/mallTrade/queryMallTradeList",
    "/mms-gateway/apollo/api/report/queryHourlyRangeReport"
  ];

  function shouldCapture(url) {
    return TARGET_PATHS.some((path) => String(url || "").includes(path));
  }

  function normalizeHeaders(headersLike) {
    const result = {};
    if (!headersLike) return result;

    try {
      if (headersLike instanceof Headers) {
        headersLike.forEach((value, key) => {
          result[key] = value;
        });
        return result;
      }
    } catch (error) {
      console.warn("PDD fee hook headers read failed:", error);
    }

    if (Array.isArray(headersLike)) {
      headersLike.forEach((entry) => {
        if (Array.isArray(entry) && entry.length >= 2) result[entry[0]] = entry[1];
      });
      return result;
    }

    if (typeof headersLike === "object") {
      return { ...headersLike };
    }

    return result;
  }

  async function readBodyText(body, request) {
    if (typeof body === "string") return body;
    if (body instanceof URLSearchParams) return body.toString();
    if (body instanceof FormData) {
      return JSON.stringify(Array.from(body.entries()).map(([key, value]) => [key, typeof value === "string" ? value : String(value)]));
    }
    if (body instanceof Blob) return await body.text();
    if (request) {
      try {
        return await request.clone().text();
      } catch (error) {
        return "";
      }
    }
    return "";
  }

  function postPayload(payload) {
    window.postMessage({
      source: SOURCE,
      type: "network",
      ...payload
    }, "*");
  }

  async function parseJsonResponse(response) {
    try {
      return await response.clone().json();
    } catch (error) {
      try {
        return JSON.parse(await response.clone().text());
      } catch (nestedError) {
        return null;
      }
    }
  }

  const originalFetch = window.fetch.bind(window);
  window.fetch = async function patchedFetch(input, init) {
    const request = input instanceof Request ? input : null;
    const url = request ? request.url : String(input || "");
    const method = String(init?.method || request?.method || "GET").toUpperCase();
    const response = await originalFetch(input, init);

    if (shouldCapture(url)) {
      const requestBody = await readBodyText(init?.body, request);
      const headers = normalizeHeaders(init?.headers || request?.headers);
      const json = await parseJsonResponse(response);
      if (json) {
        postPayload({ url, method, headers, requestBody, response: json });
      }
    }

    return response;
  };

  const originalOpen = XMLHttpRequest.prototype.open;
  const originalSend = XMLHttpRequest.prototype.send;
  const originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;

  XMLHttpRequest.prototype.open = function patchedOpen(method, url) {
    this.__pddFeeHook = {
      method: String(method || "GET").toUpperCase(),
      url: String(url || ""),
      headers: {}
    };
    return originalOpen.apply(this, arguments);
  };

  XMLHttpRequest.prototype.setRequestHeader = function patchedSetRequestHeader(name, value) {
    if (this.__pddFeeHook && name) {
      this.__pddFeeHook.headers[name] = value;
    }
    return originalSetRequestHeader.apply(this, arguments);
  };

  XMLHttpRequest.prototype.send = function patchedSend(body) {
    if (this.__pddFeeHook) {
      this.__pddFeeHook.body = body;
      this.addEventListener("loadend", async () => {
        const meta = this.__pddFeeHook;
        if (!meta || !shouldCapture(meta.url)) return;

        let json = null;
        if (this.responseType === "json") {
          json = this.response;
        } else if (typeof this.responseText === "string" && this.responseText) {
          try {
            json = JSON.parse(this.responseText);
          } catch (error) {
            json = null;
          }
        }

        if (!json) return;

        postPayload({
          url: meta.url,
          method: meta.method,
          headers: meta.headers,
          requestBody: await readBodyText(meta.body),
          response: json
        });
      }, { once: true });
    }

    return originalSend.apply(this, arguments);
  };
})();
