(() => {
  const GUARD = "__MMW_ORIGINAL_ECOMMERCE_BACKGROUND_ADAPTER__";
  if (globalThis[GUARD]) return;
  globalThis[GUARD] = true;

  const PLATFORM_ACTION = "MMW_ORIGINAL_PLATFORM_REQUEST";
  const SERVICE_ACTION = "MMW_ORIGINAL_SERVICE";
  const CACHE_WARNING_MESSAGE = "MMW_ORIGINAL_CACHE_WARNING";
  const EVALUATION_STORAGE_KEY = "mmwOriginalEvaluationTemplates";
  const PDD_AI_STORAGE_KEY = "mmwOriginalPddAiUsers";
  const FRAME_STORAGE_KEY = "mmwOriginalImageFrames";
  const OFFICIAL_HOST_SUFFIXES = [
    "taobao.com", "tmall.com", "alicdn.com", "alibaba.com", "alibabausercontent.com",
    "1688.com", "pinduoduo.com", "yangkeduo.com", "jd.com", "jd.hk", "360buyimg.com",
    "jinritemai.com", "douyin.com", "iesdouyin.com", "byteimg.com", "snssdk.com",
    "kuaishou.com", "kwaixiaodian.com", "xiaohongshu.com", "xhscdn.com", "goofish.com",
    "weixin.qq.com", "qq.com", "weidian.com", "dewu.com", "vip.com", "temu.com",
    "aliexpress.com", "shopee.com", "shein.com", "ozon.com", "ebay.com", "amazon.com",
    "yiwugo.com", "vvic.com", "17zwd.com", "made-in-china.com", "baidu.com"
  ];
  const NOOP_SERVICES = new Set([
    "Home.Plujapi.updateUseNumber",
    "Home.EnterpriseVipConfig.useToolLog",
    "Home.ToolWarning.addToolUseLog",
    "Home.HelpCenter.indexUplog",
    "Home.GoldLogApi.deductUserGold",
    "Home.Home.changeWechatService",
    "Dpzd.User_OperatingLog.addactlog",
    "Dpzd.User_FeedBack.advice",
    "Home.Oss.uploadPictures"
  ]);

  function isObject(value) {
    return Boolean(value) && typeof value === "object" && !Array.isArray(value);
  }

  function axiosResponse(payload, url = "", status = 200, statusText = "OK", headers = {}) {
    let text = "";
    try {
      text = typeof payload === "string" ? payload : JSON.stringify(payload ?? {});
    } catch (_) {}
    return {
      data: payload,
      json: isObject(payload) || Array.isArray(payload) ? payload : {},
      text,
      status,
      statusText,
      headers,
      url: String(url || ""),
      redirected: false
    };
  }

  function serviceData(config) {
    const body = isObject(config?.data) ? config.data : {};
    try {
      const query = Object.fromEntries(new URL(String(config?.url || ""), "https://mmwgzt.xyz").searchParams);
      return { ...query, ...body };
    } catch (_) {
      return { ...body };
    }
  }

  function sanitizeAiPayload(value, seen = new WeakSet()) {
    if (Array.isArray(value)) return value.map((item) => sanitizeAiPayload(item, seen));
    if (!isObject(value)) return value;
    if (seen.has(value)) return undefined;
    seen.add(value);
    const blocked = new Set([
      "authorization", "cookie", "cookies", "headers", "origin", "referer", "token",
      "anti-content", "anti_content", "user-agent", "user_agent", "x-token", "access-token"
    ]);
    const result = {};
    for (const [key, item] of Object.entries(value)) {
      if (blocked.has(String(key).toLowerCase())) continue;
      const clean = sanitizeAiPayload(item, seen);
      if (clean !== undefined) result[key] = clean;
    }
    return result;
  }

  function officialHost(hostname) {
    const host = String(hostname || "").toLowerCase().replace(/^\.+/, "");
    if (!host) return false;
    return OFFICIAL_HOST_SUFFIXES.some((suffix) => host === suffix || host.endsWith(`.${suffix}`));
  }

  function requestUrl(value) {
    const url = new URL(String(value || ""));
    if (url.protocol !== "https:" && url.protocol !== "http:") {
      throw new Error("仅支持 HTTP/HTTPS 平台请求");
    }
    if (!officialHost(url.hostname)) {
      throw new Error(`已拦截非官方平台地址：${url.hostname || "未知地址"}`);
    }
    return url;
  }

  function addQuery(url, params) {
    if (!isObject(params)) return;
    for (const [key, value] of Object.entries(params)) {
      if (value === undefined || value === null) continue;
      if (Array.isArray(value)) {
        for (const item of value) url.searchParams.append(key, String(item));
      } else if (isObject(value)) {
        url.searchParams.set(key, JSON.stringify(value));
      } else {
        url.searchParams.set(key, String(value));
      }
    }
  }

  function safeHeaders(input) {
    const result = new Headers();
    if (!isObject(input)) return result;
    const forbidden = new Set([
      "accept-encoding", "connection", "content-length", "cookie", "host", "origin",
      "referer", "sec-fetch-dest", "sec-fetch-mode", "sec-fetch-site", "user-agent"
    ]);
    for (const [rawName, rawValue] of Object.entries(input)) {
      if (rawValue === undefined || rawValue === null) continue;
      let name = String(rawName || "").trim();
      if (!name) continue;
      if (name.toLowerCase().startsWith("mcj_")) name = name.slice(4);
      if (!name || forbidden.has(name.toLowerCase())) continue;
      try {
        result.set(name, String(rawValue));
      } catch (_) {}
    }
    return result;
  }

  const PLATFORM_DNR_HEADERS = new Set(["cookie", "origin", "referer"]);
  let platformDnrSequence = 0;

  function platformDnrHeaders(input) {
    const result = new Map();
    if (!isObject(input)) return [];
    for (const [rawName, rawValue] of Object.entries(input)) {
      if (rawValue === undefined || rawValue === null) continue;
      let name = String(rawName || "").trim();
      if (!name) continue;
      const prefixed = name.toLowerCase().startsWith("mcj_");
      if (prefixed) name = name.slice(4);
      const lowerName = name.toLowerCase();
      if (!name || (!prefixed && !PLATFORM_DNR_HEADERS.has(lowerName))) continue;
      result.set(lowerName, { header: name, operation: "set", value: String(rawValue) });
    }
    return [...result.values()];
  }

  async function installPlatformHeaderRule(url, input) {
    const requestHeaders = platformDnrHeaders(input);
    if (!requestHeaders.length) return null;
    if (!chrome.declarativeNetRequest?.updateDynamicRules) {
      throw new Error("当前浏览器不支持平台会话请求头注入");
    }
    platformDnrSequence = (platformDnrSequence + 1) % 1000000;
    const id = 780000000 + platformDnrSequence;
    await chrome.declarativeNetRequest.updateDynamicRules({
      removeRuleIds: [id],
      addRules: [{
        id,
        priority: 10000,
        action: { type: "modifyHeaders", requestHeaders },
        condition: {
          requestDomains: [url.hostname],
          urlFilter: `${url.origin}${url.pathname}`,
          resourceTypes: ["xmlhttprequest", "other"]
        }
      }]
    });
    return id;
  }

  async function removePlatformHeaderRule(id) {
    if (!id || !chrome.declarativeNetRequest?.updateDynamicRules) return;
    try {
      await chrome.declarativeNetRequest.updateDynamicRules({ removeRuleIds: [id] });
    } catch (_) {}
  }

  function requestBody(config, headers, method) {
    if (method === "GET" || method === "HEAD") return undefined;
    const value = config.body !== undefined ? config.body : config.data;
    if (value === undefined || value === null) return undefined;
    if (typeof value === "string" || value instanceof Blob || value instanceof ArrayBuffer) return value;
    const contentType = String(headers.get("content-type") || "").toLowerCase();
    if (contentType.includes("application/x-www-form-urlencoded")) {
      const form = new URLSearchParams();
      for (const [key, item] of Object.entries(isObject(value) ? value : {})) {
        form.set(key, isObject(item) || Array.isArray(item) ? JSON.stringify(item) : String(item));
      }
      return form.toString();
    }
    if (!headers.has("content-type")) headers.set("content-type", "application/json");
    return JSON.stringify(value);
  }

  async function platformRequest(configInput) {
    const config = isObject(configInput) ? { ...configInput } : {};
    const url = requestUrl(config.url);
    const method = String(config.method || "GET").toUpperCase();
    addQuery(url, config.params);
    const headers = safeHeaders(config.headers);
    const controller = new AbortController();
    const timeout = Math.min(120000, Math.max(3000, Number(config.timeout || 30000)));
    const timer = setTimeout(() => controller.abort(), timeout);
    let platformRuleId = null;
    try {
      platformRuleId = await installPlatformHeaderRule(url, config.headers);
      const response = await fetch(url.href, {
        method,
        headers,
        body: requestBody(config, headers, method),
        credentials: "include",
        cache: "no-store",
        redirect: "follow",
        signal: controller.signal
      });
      const text = await response.text();
      let data = text;
      try {
        data = text ? JSON.parse(text) : {};
      } catch (_) {}
      const responseHeaders = {};
      response.headers.forEach((value, key) => { responseHeaders[key] = value; });
      if (!response.ok) throw new Error(`平台请求失败：HTTP ${response.status}`);
      return {
        data,
        json: isObject(data) || Array.isArray(data) ? data : {},
        text,
        status: response.status,
        statusText: response.statusText,
        headers: responseHeaders,
        url: response.url,
        redirected: response.redirected
      };
    } catch (error) {
      if (error?.name === "AbortError") throw new Error("平台请求超时");
      throw error;
    } finally {
      clearTimeout(timer);
      await removePlatformHeaderRule(platformRuleId);
    }
  }

  async function storedList(key) {
    const record = await chrome.storage.local.get([key]);
    return Array.isArray(record?.[key]) ? record[key] : [];
  }

  async function writeStoredList(key, list) {
    await chrome.storage.local.set({ [key]: list });
    return list;
  }

  function serviceName(config) {
    try {
      return String(new URL(String(config?.url || ""), "https://mmwgzt.xyz").searchParams.get("s") || "").trim();
    } catch (_) {
      return "";
    }
  }

  function servicePath(config) {
    try {
      return new URL(String(config?.url || ""), "https://mmwgzt.xyz").pathname;
    } catch (_) {
      return "";
    }
  }

  function unlimitedAccount() {
    return {
      account_type: 2,
      bypass_account: 1,
      residual_gold: 999999,
      no_vip_num: 999999,
      product_use_num: 999999,
      pddai_num: 999999,
      pddai_tool_num: 0,
      pddai_tool_total: 5,
      pddai_platform_num: 0,
      useData: [{ tool_type: 0, num: 999999 }]
    };
  }

  function parseJsonObject(value) {
    if (isObject(value)) return value;
    try {
      const parsed = JSON.parse(String(value || "{}"));
      return isObject(parsed) ? parsed : {};
    } catch (_) {
      return {};
    }
  }

  function monitorPlatform(data) {
    const platform = String(data?.platform || data?.platform_id || "unknown").trim() || "unknown";
    return platform.startsWith("monitor-") ? platform : `monitor-${platform}`;
  }

  function monitorGoodsId(product, data = {}) {
    const productData = isObject(product?.productData)
      ? product.productData
      : (isObject(product?.product_data) ? product.product_data : {});
    return String(
      productData.id
      || productData.goods_id
      || productData.goodsId
      || product.goods_id
      || product.goodsId
      || product.id
      || data.goods_id
      || data.good_id
      || ""
    ).trim();
  }

  function cachedProduct(response) {
    return response?.product || response?.record?.product || response?.data?.product || null;
  }

  function cachedRecordId(response) {
    return Number(response?.id || response?.record?.id || response?.data?.id || 0);
  }

  function monitorCachePayload(product, data = {}) {
    const productData = isObject(product.productData)
      ? product.productData
      : (isObject(product.product_data) ? product.product_data : {});
    const goodsId = monitorGoodsId(product, data);
    if (!goodsId) throw new Error("商品监控数据缺少商品ID");
    return {
      source_platform: monitorPlatform(data),
      source_item_id: goodsId,
      source_url: String(productData.link || productData.url || product.goods_url || product.url || ""),
      title: String(productData.title || product.title || product.goods_name || ""),
      product,
      collected_at: new Date().toISOString()
    };
  }

  function monitorRecord(response, product, sourceItemId = "") {
    if (!isObject(product)) return null;
    const productData = isObject(product.productData)
      ? product.productData
      : (isObject(product.product_data) ? product.product_data : {});
    const salesStatistics = isObject(product.salesStatistics)
      ? product.salesStatistics
      : (isObject(product.sales_statistics) ? product.sales_statistics : {});
    return {
      id: cachedRecordId(response),
      good_id: monitorGoodsId(product, { goods_id: sourceItemId }),
      product_data: productData,
      sales_statistics: salesStatistics,
      goods_data: product,
      create_time: response?.created_at || response?.record?.created_at || response?.data?.created_at || "",
      update_time: response?.updated_at || response?.record?.updated_at || response?.data?.updated_at || ""
    };
  }

  async function cloud(path, method = "GET", data = {}) {
    if (typeof requestNativeEcommerceCloud !== "function") {
      throw new Error("MMWGZT电商云服务尚未加载");
    }
    return requestNativeEcommerceCloud({
      path,
      method,
      ...(method === "GET" ? { query: data } : { body: data })
    });
  }

  function unixSeconds(value) {
    const numeric = Number(value);
    if (Number.isFinite(numeric) && numeric > 0) {
      return Math.floor(numeric > 1e12 ? numeric / 1000 : numeric);
    }
    const text = String(value || "").trim();
    if (!text) return 0;
    const parsed = Date.parse(text.includes("T") ? text : text.replace(" ", "T"));
    return Number.isFinite(parsed) ? Math.floor(parsed / 1000) : 0;
  }

  function safeErrorMessage(error) {
    return String(error?.message || error || "云端同步失败")
      .replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [hidden]")
      .replace(/[\r\n\t]+/g, " ")
      .trim()
      .slice(0, 220);
  }

  async function notifyCacheWarning(context, detail = {}) {
    const tabId = Number(context?.sender?.tab?.id);
    if (!Number.isInteger(tabId) || !chrome.tabs?.sendMessage) return;
    try {
      await chrome.tabs.sendMessage(tabId, {
        type: CACHE_WARNING_MESSAGE,
        operation: String(detail.operation || "product-cache"),
        queued: detail.queued === true,
        pending: Math.max(0, Number(detail.pending || 0)),
        message: String(detail.message || "商品已采集并保存在本地，云端缓存将在稍后重试")
      });
    } catch (_) {}
  }

  async function deferCloudSideEffect(entry, context, error) {
    let queued = false;
    let pending = 0;
    let queueError = "";
    try {
      const outbox = globalThis.MMWOriginalEcommerceSyncOutbox;
      if (!outbox?.enqueue) throw new Error("云端同步队列尚未加载");
      const result = await outbox.enqueue({ ...entry, lastError: safeErrorMessage(error) });
      queued = result?.queued === true;
      pending = Number(result?.pending || 0);
    } catch (caught) {
      queueError = safeErrorMessage(caught);
    }
    const reason = safeErrorMessage(error);
    await notifyCacheWarning(context, {
      operation: entry.operation,
      queued,
      pending,
      message: queued
        ? `商品已采集并保存在本地；云端缓存暂未同步：${reason}。已加入自动重试队列。`
        : `商品已采集并保存在本地；云端缓存暂未同步：${reason}。${queueError || "请稍后手动重试。"}`
    });
    return true;
  }

  async function cloudProduct(config) {
    if (typeof requestNativeEcommerceCloud !== "function") return null;
    const data = isObject(config.data) ? config.data : {};
    try {
      const cached = await requestNativeEcommerceCloud({
        path: "/api/ecommerce/product-cache",
        method: "GET",
        query: {
          source_platform: String(data.platform_id || data.platform || "unknown"),
          source_item_id: String(data.goods_id || data.item_id || "")
        }
      });
      if (!cached?.product) return null;
      return { collection_method: 1, goods_data: JSON.stringify(cached.product) };
    } catch (_) {
      return null;
    }
  }

  async function evaluationService(name, data) {
    const list = await storedList(EVALUATION_STORAGE_KEY);
    if (name.endsWith("getEvaluationContent")) return list;
    if (name.endsWith("addEvaluationContent")) {
      const content = String(data.content || data.evaluation_content || data.text || "").trim();
      if (!content) throw new Error("评价内容不能为空");
      const item = { id: Date.now(), content };
      await writeStoredList(EVALUATION_STORAGE_KEY, [...list, item]);
      return item;
    }
    const id = String(data.id || data.content_id || "");
    await writeStoredList(EVALUATION_STORAGE_KEY, list.filter((item) => String(item.id) !== id));
    return {};
  }

  async function pddAiService(name, data) {
    if (name.endsWith("useOne")) return true;
    const list = await storedList(PDD_AI_STORAGE_KEY);
    if (name.endsWith("nowUsers")) return { count: list.length, list };
    if (name.endsWith("addUser")) {
      const item = { ...data, id: data.id || Date.now() };
      const next = [...list.filter((row) => String(row.id) !== String(item.id)), item];
      await writeStoredList(PDD_AI_STORAGE_KEY, next);
      return item;
    }
    const id = String(data.id || data.user_id || data.uid || "");
    await writeStoredList(PDD_AI_STORAGE_KEY, list.filter((item) => String(item.id) !== id));
    return {};
  }

  async function productCacheService(name, data, context = {}) {
    const platform = String(data.platform_id || data.platform || "unknown");
    const itemId = String(data.goods_id || data.item_id || "");
    if (name.endsWith("getGoodsData")) {
      try {
        const cached = await cloud("/api/ecommerce/product-cache", "GET", {
          source_platform: platform,
          source_item_id: itemId
        });
        const product = cached?.product || cached?.record?.product || cached?.data?.product;
        if (!product) return null;
        return {
          id: cached.id,
          goods_data: JSON.stringify(product),
          collection_method: Number(product.collection_method || data.collection_method || 1),
          create_time: unixSeconds(cached.created_at || cached.updated_at || cached.create_time)
        };
      } catch (_) {
        return null;
      }
    }
    if (name.endsWith("delGoodsDataFormGoodsId")) {
      const lookup = { source_platform: platform, source_item_id: itemId };
      try {
        const cached = await cloud("/api/ecommerce/product-cache", "GET", lookup);
        const id = Number(cached?.id || cached?.record?.id || 0);
        if (!id) return true;
        await cloud("/api/ecommerce/product-cache/delete", "POST", { id });
        return true;
      } catch (error) {
        return deferCloudSideEffect({
          operation: "product-cache-delete-by-source",
          idempotencyKey: `product-cache:${platform}:${itemId || "unknown"}`,
          payload: lookup
        }, context, error);
      }
    }
    const product = parseJsonObject(data.json_data || data.goods_data || data.product);
    const resolvedItemId = itemId || String(product.goods_id || product.id || "");
    const payload = {
      source_platform: platform,
      source_item_id: resolvedItemId,
      source_url: String(product.goods_url || product.url || ""),
      title: String(product.title || product.goods_name || ""),
      product,
      collected_at: new Date().toISOString()
    };
    try {
      await cloud("/api/ecommerce/product-cache/upsert", "POST", payload);
      return true;
    } catch (error) {
      return deferCloudSideEffect({
        operation: "product-cache-upsert",
        idempotencyKey: `product-cache:${platform}:${resolvedItemId || payload.source_url || Date.now()}`,
        path: "/api/ecommerce/product-cache/upsert",
        method: "POST",
        payload
      }, context, error);
    }
  }

  async function monitorGoodsService(action, data) {
    const sourcePlatform = monitorPlatform(data);
    if (action === "attentionGoods" || action === "updateGoods") {
      const product = parseJsonObject(data.data || data.goods_data || data.product);
      await cloud("/api/ecommerce/product-cache/upsert", "POST", monitorCachePayload(product, data));
      return { code: 200, data: true, msg: "" };
    }

    const goodsId = String(data.goods_id || data.good_id || "").trim();
    if (action === "cancelAttentionGoods") {
      if (!goodsId) return { code: 200, data: true, msg: "" };
      const cached = await cloud("/api/ecommerce/product-cache", "GET", {
        source_platform: sourcePlatform,
        source_item_id: goodsId
      });
      const id = cachedRecordId(cached);
      if (id) await cloud("/api/ecommerce/product-cache/delete", "POST", { id });
      return { code: 200, data: true, msg: "" };
    }

    if (action === "getGoodsOne") {
      if (!goodsId) return { code: 200, data: null, msg: "" };
      const cached = await cloud("/api/ecommerce/product-cache", "GET", {
        source_platform: sourcePlatform,
        source_item_id: goodsId
      });
      const record = monitorRecord(cached, cachedProduct(cached), goodsId);
      return { code: 200, data: record, msg: "" };
    }

    const page = Math.max(1, Number(data.page || 1));
    const pageSize = Math.min(100, Math.max(1, Number(data.page_size || 10)));
    const response = await cloud("/api/ecommerce/product-cache/list", "GET", {
      source_platform: sourcePlatform,
      limit: Math.min(200, page * pageSize)
    });
    const rows = response?.records || response?.items || response?.list || [];
    const pageRows = rows.slice((page - 1) * pageSize, page * pageSize);
    const records = await Promise.all(pageRows.map(async (row) => {
      const full = await cloud("/api/ecommerce/product-cache", "GET", { id: row.id });
      return monitorRecord(full, cachedProduct(full), row.source_item_id);
    }));
    return { code: 200, data: records.filter(Boolean), msg: "" };
  }

  async function categoryNameService(data) {
    const currentId = String(data.current_id || data.category_id || "");
    if (!currentId) return { prev_name: "", current_name: "" };
    try {
      const response = await cloud("/api/ecommerce/category-mappings", "GET", {
        source_platform: String(data.platform || data.platform_id || "unknown"),
        source_category_id: currentId,
        limit: 1
      });
      const row = (response?.records || response?.items || response?.list || [])[0];
      const path = String(row?.source_category_path || "").trim();
      if (path) {
        const parts = path.split(/\s*>\s*|\s*-\s*/).filter(Boolean);
        return {
          prev_name: parts.slice(0, -1).join("-") || "",
          current_name: parts.at(-1) || path
        };
      }
    } catch (_) {}
    return { prev_name: "", current_name: currentId };
  }

  async function moveHistoryService(data, context = {}) {
    const product = parseJsonObject(data.json_data || data.product);
    const sourcePlatform = String(data.platform_id || product.platformEnum || "unknown");
    const targetPlatform = String(data.to_platform_id || "unknown");
    const itemId = String(data.goods_id || product.goods_id || product.id || "");
    const rawStatus = String(data.status || "");
    const status = ({
      "1": "success",
      "2": "failed",
      "3": "cancelled",
      "4": "waiting_confirm",
      "5": "success",
      "6": "success"
    })[rawStatus] || rawStatus || "pending";
    const requestId = `${sourcePlatform}:${targetPlatform}:${itemId || Date.now()}`;
    const payload = {
      request_id: requestId,
      source_platform: sourcePlatform,
      target_platform: targetPlatform,
      source_item_id: itemId,
      source_url: String(product.goods_url || product.url || ""),
      title: String(product.title || product.goods_name || ""),
      status,
      total_count: 1,
      success_count: status === "success" ? 1 : 0,
      failed_count: status === "failed" ? 1 : 0,
      payload: { ...data, token: undefined, json_data: undefined, product }
    };
    try {
      await cloud("/api/ecommerce/move-history/upsert", "POST", payload);
      return true;
    } catch (error) {
      return deferCloudSideEffect({
        operation: "move-history-upsert",
        idempotencyKey: `move-history:${requestId}`,
        path: "/api/ecommerce/move-history/upsert",
        method: "POST",
        payload
      }, context, error);
    }
  }

  async function attributeService(name, data) {
    try {
      const query = name.endsWith("getAttributeTwo")
        ? { target_platform: String(data.platform_id || ""), limit: 300 }
        : {
            source_platform: String(data.platform_id || ""),
            target_platform: String(data.to_platform_id || ""),
            limit: 300
          };
      const response = await cloud("/api/ecommerce/attribute-mappings", "GET", query);
      let records = response?.records || response?.items || response?.list || [];
      if (name.endsWith("getAttributeTwo")) {
        const wanted = new Set(String(data.attribute || "").split(",").map((item) => item.trim()).filter(Boolean));
        return records.filter((row) => !wanted.size || wanted.has(String(row.target_attribute_name || ""))).map((row) => ({
          [String(row.target_attribute_name || row.source_attribute_name || "")]: [
            row.source_attribute_name,
            ...(Array.isArray(row.synonyms) ? row.synonyms : [])
          ].filter(Boolean).join(",")
        }));
      }
      const category = String(data.class || "").trim();
      if (category) records = records.filter((row) => {
        const path = String(row.source_category_path || "").trim();
        return !path || path === category || path.endsWith(category) || category.endsWith(path);
      });
      return records.map((row) => ({
        attribute: String(row.source_attribute_name || ""),
        similar_words: [
          row.target_attribute_name,
          ...(Array.isArray(row.synonyms) ? row.synonyms : [])
        ].filter(Boolean).join(",")
      })).filter((row) => row.attribute && row.similar_words);
    } catch (_) {
      return [];
    }
  }

  async function productSelectionService(name, data) {
    if (name.endsWith("getProductlist")) {
      const page = Math.max(1, Number(data.page || 1));
      const pageSize = Math.min(100, Math.max(1, Number(data.page_size || 10)));
      const response = await cloud("/api/ecommerce/product-cache/list", "GET", {
        source_platform: String(data.platform_id || "unknown"),
        keyword: String(data.search_key || ""),
        limit: Math.min(200, page * pageSize)
      });
      const all = response?.records || response?.items || response?.list || [];
      const pageRows = all.slice((page - 1) * pageSize, page * pageSize);
      const list = await Promise.all(pageRows.map(async (row) => {
        try {
          const full = await cloud("/api/ecommerce/product-cache", "GET", { id: row.id });
          const product = full?.product || {};
          return {
            ...row,
            ...product,
            aid: row.id,
            goods_data_json: JSON.stringify(product),
            create_time: row.created_at || ""
          };
        } catch (_) {
          return { ...row, aid: row.id };
        }
      }));
      return { list, total: all.length };
    }
    if (name.endsWith("delProduct")) {
      await cloud("/api/ecommerce/product-cache/delete", "POST", { id: Number(data.aid || data.id || 0) });
      return true;
    }
    const product = parseJsonObject(data.json_data || data.product);
    await cloud("/api/ecommerce/product-cache/upsert", "POST", {
      source_platform: String(data.platform_id || product.platform_id || "unknown"),
      source_item_id: String(data.goods_id || product.goods_id || product.id || ""),
      source_url: String(product.goods_url || product.url || ""),
      title: String(product.title || product.goods_name || ""),
      product
    });
    return true;
  }

  async function imageBytes(urlValue) {
    const url = requestUrl(urlValue);
    const response = await fetch(url.href, { credentials: "include", cache: "no-store" });
    if (!response.ok) throw new Error(`图片读取失败：HTTP ${response.status}`);
    return response;
  }

  async function localWhiteImage(urlValue) {
    if (typeof createImageBitmap !== "function" || typeof OffscreenCanvas !== "function") {
      throw new Error("当前浏览器不支持本地白底图检测");
    }
    const response = await imageBytes(urlValue);
    const bitmap = await createImageBitmap(await response.blob());
    try {
      const width = Math.max(1, Math.min(80, bitmap.width));
      const height = Math.max(1, Math.min(80, bitmap.height));
      const canvas = new OffscreenCanvas(width, height);
      const context = canvas.getContext("2d", { willReadFrequently: true });
      context.drawImage(bitmap, 0, 0, width, height);
      const pixels = context.getImageData(0, 0, width, height).data;
      let white = 0;
      let visible = 0;
      for (let index = 0; index < pixels.length; index += 4) {
        if (pixels[index + 3] < 16) continue;
        visible += 1;
        if (pixels[index] >= 238 && pixels[index + 1] >= 238 && pixels[index + 2] >= 238) white += 1;
      }
      return visible > 0 && white / visible >= 0.72;
    } finally {
      bitmap.close?.();
    }
  }

  async function localDuplicateImages(urls) {
    const rows = await Promise.all((Array.isArray(urls) ? urls : []).map(async (url, index) => {
      try {
        const response = await imageBytes(url);
        const digest = await crypto.subtle.digest("SHA-256", await response.arrayBuffer());
        const hash = Array.from(new Uint8Array(digest), (item) => item.toString(16).padStart(2, "0")).join("");
        return { index, url, hash };
      } catch (_) {
        return null;
      }
    }));
    const first = new Map();
    const duplicates = [];
    for (const row of rows.filter(Boolean)) {
      if (!first.has(row.hash)) first.set(row.hash, row);
      else duplicates.push({ source: first.get(row.hash).url, duplicate: row.url, index: row.index });
    }
    return duplicates;
  }

  function aiContent(result) {
    return String(
      result?.choices?.[0]?.message?.content
      || result?.data?.choices?.[0]?.message?.content
      || result?.message?.content
      || result?.content
      || result?.text
      || result?.answer
      || ""
    );
  }

  function legacyAiImagePayload(data) {
    const options = isObject(data.options) ? data.options : parseJsonObject(data.options);
    const functionType = String(data.functionType || data.function_type || data.operation || "").trim().toLowerCase();
    const operationMap = {
      super_resolution: "clarity",
      remove_watermark: "remove_watermark",
      description_edit: "redraw",
      description_edit_with_mask: "replace_local",
      expand: "expand",
      stylization_all: "similar"
    };
    const targetLanguage = String(
      options.targetLanguage || options.target_language || data.targetLanguage || data.target_language || ""
    ).trim().toLowerCase();
    const operation = functionType === "image_translation"
      ? (targetLanguage === "zh" || targetLanguage.startsWith("zh-") ? "translate_zh" : "translate_en")
      : (operationMap[functionType] || functionType);
    return {
      operation,
      image: data.baseImageUrl || data.base_image_url || data.image || data.imageData || data.dataUrl || "",
      mask: options.maskImageUrl || options.mask_image_url || data.maskImageUrl || data.mask_image_url || data.mask || "",
      prompt: String(data.prompt || options.prompt || ""),
      size: data.size || options.size || "auto",
      output_format: data.output_format || options.output_format || options.format || "png",
      options
    };
  }

  function legacyCategory(result) {
    const asPath = (value) => {
      if (Array.isArray(value)) return value.map((item) => String(item || "").trim()).filter(Boolean).join(" > ");
      if (typeof value === "string" || typeof value === "number") return String(value).trim();
      return "";
    };
    const direct = [
      result?.category,
      result?.category_path,
      result?.path,
      result?.data?.category,
      result?.data?.category_path,
      result?.data?.path
    ].map(asPath).find(Boolean);
    if (direct) return direct;

    const content = aiContent(result).trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "");
    if (!content) return "";
    const jsonCandidates = [content, content.match(/\{[\s\S]*\}/)?.[0]].filter(Boolean);
    for (const candidate of jsonCandidates) {
      try {
        const parsed = JSON.parse(candidate);
        const path = [
          parsed?.category,
          parsed?.category_path,
          parsed?.path,
          parsed?.data?.category,
          parsed?.data?.category_path,
          parsed?.data?.path
        ].map(asPath).find(Boolean);
        if (path) return path;
      } catch (_) {}
    }
    const line = content
      .split(/\r?\n/)
      .map((item) => item.replace(/^(?:推荐)?类目\s*[:：]\s*/i, "").trim())
      .find((item) => item.includes(">") || item.includes("＞"));
    return line || "";
  }

  function wordArray(result) {
    const direct = result?.word_arr || result?.data?.word_arr;
    if (Array.isArray(direct)) return direct.map((item) => String(item)).filter(Boolean);
    const content = aiContent(result).trim();
    if (!content) return [];
    try {
      const parsed = JSON.parse(content.match(/\[[\s\S]*\]/)?.[0] || content);
      if (Array.isArray(parsed)) return parsed.map((item) => String(item)).filter(Boolean);
    } catch (_) {}
    return content.split(/[\s,，、;；|]+/).map((item) => item.trim()).filter(Boolean);
  }

  async function legacyService(path, config) {
    const data = serviceData(config);
    if (path.endsWith("/photo-white")) {
      return { is_white_base_img: await localWhiteImage(data.url) };
    }
    if (path.endsWith("/main-images-check")) {
      return { img_repeat_check: { data: await localDuplicateImages(data.urls) } };
    }
    if (path.endsWith("/search-word") && data.url) {
      return platformRequest(data);
    }
    if (typeof requestEcommerceToolAi !== "function") {
      throw new Error("MMWGZT电商 AI 服务尚未加载");
    }
    let scene = "ai-chat";
    if (path.endsWith("/ai-image")) scene = "ai-image";
    else if (path.endsWith("/douyin-category")) scene = "douyin-category";
    else if (path.endsWith("/search-word")) scene = "search-word";
    const prompt = String(
      data.prompt || data.question || data.title || data.word || data.content || data.message || ""
    );
    const payload = path.endsWith("/ai-image")
      ? legacyAiImagePayload(data)
      : sanitizeAiPayload(data);
    const result = await requestEcommerceToolAi({ scene, prompt, payload });
    if (path.endsWith("/ai-image")) {
      const image = result?.image_url
        || result?.data_url
        || result?.url
        || result?.data?.image_url
        || result?.data?.data_url
        || result?.data?.url
        || result?.data
        || result;
      return { data: image };
    }
    if (path.endsWith("/douyin-category")) {
      return { code: 200, data: { category: legacyCategory(result) } };
    }
    if (path.endsWith("/chat")) {
      return { data: { choices: [{ message: { content: aiContent(result) } }] } };
    }
    if (path.endsWith("/title-tool")) {
      return { code: 200, word_arr: wordArray(result), data: result?.data ?? result };
    }
    return result?.data ?? result;
  }

  async function servicePayload(configInput, context = {}) {
    const config = isObject(configInput) ? configInput : {};
    const path = servicePath(config);
    if (path.includes("/api/ecommerce/original-service/legacy/")) {
      return legacyService(path, config);
    }
    const monitorMatch = path.match(/\/api\/ecommerce\/original-service\/goods\/Goods\/(attentionGoods|cancelAttentionGoods|getAttentionGoods|updateGoods|getGoodsOne)\/?$/);
    if (monitorMatch) {
      return monitorGoodsService(monitorMatch[1], serviceData(config));
    }
    const name = serviceName(config);
    const data = serviceData(config);
    if (NOOP_SERVICES.has(name)) return { ret: 200, data: {}, msg: "" };
    if (name === "Home.UserNumForPlatform.getPlatformVipData") {
      return { ret: 200, data: { num: 999999, total_num: 999999 }, msg: "" };
    }
    if (name === "Home.PersonalCenter.getPersonalDetails") {
      return { ret: 200, data: unlimitedAccount(), msg: "" };
    }
    if (name === "Home.EnterpriseVipConfig.showResidueNum") {
      return { ret: 200, data: [{ num: 999999 }], msg: "" };
    }
    if (name === "Home.Plujapi.getpayConfig") {
      return { ret: 200, data: { giftTips: "", privacyContent: "", url: "https://mmwgzt.xyz" }, msg: "" };
    }
    if (name === "Home.AiToolApi.getToolConfig") return { ret: 200, data: [], msg: "" };
    if (name === "Home.Category.getCategory") {
      return { ret: 200, data: await categoryNameService(data), msg: "" };
    }
    if (name === "Home.GoodsDetailsApi.getGoodsDetails") {
      return { ret: 200, data: await cloudProduct(config) || {}, msg: "" };
    }
    if (name.startsWith("Plugin.PddData.")) {
      return { ret: 200, data: await productCacheService(name, data, context), msg: "" };
    }
    if (name === "Plugin.ShopGoodsData.moveGoodslog") {
      return { ret: 200, data: await moveHistoryService(data, context), msg: "" };
    }
    if (name === "Plugin.ShopGoodsData.addShopGoodsData") {
      return { ret: 200, data: await productCacheService("Plugin.PddData.addGoodsData", data, context), msg: "" };
    }
    if (name.startsWith("Plugin.GoodsAttribute.")) {
      return { ret: 200, data: await attributeService(name, data), msg: "" };
    }
    if (name.startsWith("Plugin.ProductSelection.")) {
      return { ret: 200, data: await productSelectionService(name, data), msg: "" };
    }
    if (name.startsWith("Home.Tool.") && name.includes("EvaluationContent")) {
      return { ret: 200, data: await evaluationService(name, data), msg: "" };
    }
    if (name.startsWith("Home.PddAi.")) {
      return { ret: 200, data: await pddAiService(name, data), msg: "" };
    }
    if (name === "Home.Frame.getFrameList") {
      return { ret: 200, data: { list: await storedList(FRAME_STORAGE_KEY) }, msg: "" };
    }
    if (name === "Home.home.getPlatformUrl") {
      return { ret: 200, data: [{ name: "MMWGZT", url: "https://mmwgzt.xyz" }], msg: "" };
    }
    if (!name) throw new Error("无法识别原版服务请求");
    throw new Error(`不支持的原版云服务：${name}`);
  }

  async function serviceRequest(configInput, context = {}) {
    const config = isObject(configInput) ? configInput : {};
    return axiosResponse(await servicePayload(config, context), config.url);
  }

  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    const action = String(message?.action || "");
    if (action !== PLATFORM_ACTION && action !== SERVICE_ACTION) return false;
    globalThis.MMWEcommerceFlowRecorder?.recordRuntimeBridge?.(
      "original-bridge-request",
      { action, config: message.config },
      sender
    )?.catch?.(() => {});
    const task = Promise.resolve()
      .then(() => {
        const guard = globalThis.MMWRequireEcommerceToolFeatureAccess;
        if (typeof guard !== "function") throw new Error("电商工具权限检查未就绪");
        return guard();
      })
      .then(() => action === PLATFORM_ACTION
        ? platformRequest(message.config)
        : serviceRequest(message.config, { sender }));
    task
      .then((data) => {
        globalThis.MMWEcommerceFlowRecorder?.recordRuntimeBridge?.(
          "original-bridge-response",
          { action, config: message.config, data },
          sender
        )?.catch?.(() => {});
        sendResponse({ success: true, data });
      })
      .catch((error) => {
        globalThis.MMWEcommerceFlowRecorder?.recordRuntimeBridge?.(
          "original-bridge-error",
          { action, config: message.config, error: error?.message || String(error) },
          sender
        )?.catch?.(() => {});
        sendResponse({ success: false, error: error?.message || String(error) });
      });
    return true;
  });
})();
