import { BrowserAutomator } from '../core/browser_automator.js';
export async function runOzonBlockbusterSearch1688(data, broadcastToExtension, respond, imageBase64Cache) {
  const items = data.items || [];
  if (!items.length) { respond({ results: {}, errors: [] }); return; }

  broadcastToExtension({ type: "system", text: `🔍 1688 图搜启动 (${items.length} 个商品，单 Tab 轮询)...` });

  const results = {};
  const errors = [];

  // DOM 提取函数（注入到 1688 页面执行）
  function extractProducts() {
    const products = [];
    const els = document.querySelectorAll('[class*="searchOfferItem--"], [class*="OfferCard"], .cardui-normal, .major-offer');
    els.forEach((el, idx) => {
      if (idx >= 50) return;
      const titleEl = el.querySelector('[class*="titleText"], [class*="title"], [class*="Title"]');
      const priceEl = el.querySelector('[class*="priceItem"], [class*="price"], [class*="Price"]');
      const imgEl = el.querySelector('[class*="mainImg"], img');
      const linkEl = el.querySelector('a[href*="offer"]');
      if (titleEl) {
        let imgSrc = imgEl?.getAttribute('src') || imgEl?.getAttribute('data-lazy-src') || '';
        if (imgSrc && imgSrc.startsWith('//')) imgSrc = 'https:' + imgSrc;
        const rawHref = linkEl?.href || el.querySelector('a')?.href || '';
        const match = rawHref.match(/offerId=(\d+)/) || rawHref.match(/offer\/(\d+)/);
        const offerId = match ? match[1] : '';
        
        // 🚨 修正：绝不丢失防风控追踪参数，原子化处理
        let validUrl = rawHref;
        if (offerId && !validUrl.includes('detail.1688.com')) {
           let queryParts = [];
           if (rawHref.includes('?')) {
               queryParts = rawHref.split('?')[1].split('&').filter(p => !p.startsWith('offerId='));
           }
           const query = queryParts.length > 0 ? '?' + queryParts.join('&') : '';
           validUrl = 'https://detail.1688.com/offer/' + offerId + '.html' + query;
        }

        products.push({
          title: titleEl.textContent?.trim(),
          price: priceEl?.textContent?.trim(),
          url: validUrl,
          image: imgSrc,
          offerId: offerId
        });
      }
    });
    return { products, productCount: products.length };
  }

  // 在 1688 页面 MAIN world 中上传缓存的完美 JPEG base64
  async function uploadBase64InPage(tabId, jpegDataUrl) {
    const result = await BrowserAutomator.execute(tabId, async (b64) => {
        try {
          const resp = await fetch("https://search.1688.com/service/uploadErpImgSearch", {
            method: "POST",
            credentials: "include",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ imgBase64: b64, searchType: "imageSearch", appName: "pcErpImage", urlType: "main" }) });
          const res = await resp.json();
          const imageId = String(res.data?.imageId || "0");
          return {
            ok: res.code === 0 && imageId !== "0",
            imageId,
            raw: JSON.stringify(res).substring(0, 300)
          };
        } catch(e) {
          return { ok: false, error: e.message };
        }
      }, [jpegDataUrl], "MAIN");
    return result;
  }

  // 等待 tab 加载完成
  /* waitForTabComplete removed, using BrowserAutomator.waitForLoad instead */

  let tab = null;
  try {
      // 创建单个 tab，先导航到 1688 首页（让页面有 1688 cookie 上下文）
      tab = await BrowserAutomator.createTab("https://search.1688.com", false);
      await BrowserAutomator.waitForLoad(tab.id);
      broadcastToExtension({ type: "system", text: "🏠 1688 首页加载完成，开始上传+搜索..." });
  
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        const sku_id = item.sku_id;
        let image_id = item.image_id;
  
        try {
          // 优先用已有的 imageId
          if (item.image_id) {
            image_id = item.image_id;
            broadcastToExtension({ type: "system", text: `♻️ [${i+1}/${items.length}] ${sku_id}: 复用 imageId=${image_id}` });
          }
          
          // 从请求参数或缓存中取出完美好图 base64
          let cachedBase64 = item.image_base64 || imageBase64Cache.get(sku_id);
          
          // SW 重启防丢失：如果内存里没找到，尝试从 Cache API 中恢复图片
          if (!cachedBase64) {
            try {
              const cacheName = `ozon-images-${data.task_id || 'default'}`;
              const cache = await caches.open(cacheName);
              const res = await cache.match(`https://local-ozon-cache/${sku_id}.jpg`);
              if (res) {
                const blob = await res.blob();
                const buffer = await blob.arrayBuffer();
                const bytes = new Uint8Array(buffer);
                let binary = '';
                const chunkSize = 8192;
                for (let j = 0; j < bytes.length; j += chunkSize) {
                  binary += String.fromCharCode.apply(null, bytes.subarray(j, j + chunkSize));
                }
                cachedBase64 = 'data:' + blob.type + ';base64,' + btoa(binary);
                broadcastToExtension({ type: "system", text: `♻️ [${i+1}/${items.length}] ${sku_id}: 从 Cache API 持久缓存中恢复了图片` });
              }
            } catch (err) { console.error('Cache API match failed:', err); }
          }
  
          // 如果没有 imageId 但有完美缓存图，在 1688 页面里上传
          if (!image_id && cachedBase64) {
            broadcastToExtension({ type: "system", text: `📤 [${i+1}/${items.length}] ${sku_id}: 直接上传完美缓存图 (${cachedBase64.length} chars)...` });
            const upResult = await uploadBase64InPage(tab.id, cachedBase64);
            broadcastToExtension({ type: "system", text: `📡 [${i+1}/${items.length}] ${sku_id}: id=${upResult.imageId} raw: ${upResult.raw || upResult.error}` });
            if (upResult.ok) {
              image_id = upResult.imageId;
              broadcastToExtension({ type: "system", text: `✅ [${i+1}/${items.length}] 成功获得 imageId=${image_id}` });
            } else {
              throw new Error("Upload failed: " + (upResult.error || upResult.raw));
            }
          }
          if (!image_id) throw new Error("No imageId and no cached base64");
  
          // ── 导航到搜索结果页，并在页面 JS 执行前注入全图锁定 ──
          const searchUrl = `https://search.1688.com/youyuan/index.htm?tab=imageSearch&showP4P=false&showBid=false&imageId=${image_id}&imageRegion=0%2C0%2C1%2C1`;
          broadcastToExtension({ type: "system", text: `🌐 [${i+1}/${items.length}] 打开: ${searchUrl.substring(0, 120)}` });
  
          // Step A: 监听 loading 事件，第一时间注入拦截脚本
          const injectPromise = new Promise((resolve) => {
            const listener = (tabIdChange, changeInfo) => {
              if (tabIdChange !== tab.id || changeInfo.status !== 'loading') return;
              chrome.tabs.onUpdated.removeListener(listener);
              BrowserAutomator.executeImmediately(tab.id, () => {
                  if (window.__rbFullImageLocked) return;
                  window.__rbFullImageLocked = true;
                  const lockRegion = (url) => {
                    if (!url) return url;
                    try {
                      const u = new URL(url, location.href);
                      if (u.searchParams.has('imageRegion')) {
                        u.searchParams.set('imageRegion', '0,0,1,1');
                      }
                      return u.toString();
                    } catch(e) {
                      return url;
                    }
                  };
                  // 1. 锁定 URL
                  const _replace = history.replaceState.bind(history);
                  const _push = history.pushState.bind(history);
                  history.replaceState = (s, t, u) => _replace(s, t, lockRegion(u));
                  history.pushState = (s, t, u) => _push(s, t, lockRegion(u));
                  // 2. 锁定搜索 API
                  const origFetch = window.fetch.bind(window);
                  window.fetch = (url, opts) => {
                    if (typeof url === 'string') url = lockRegion(url);
                    else if (url && url.url) url = new Request(lockRegion(url.url), url);
                    return origFetch(url, opts);
                  };
                  const origOpen = XMLHttpRequest.prototype.open;
                  XMLHttpRequest.prototype.open = function(method, url, ...rest) {
                    if (typeof url === 'string') url = lockRegion(url);
                    return origOpen.call(this, method, url, ...rest);
                  };
                } ).then(resolve).catch((e) => {
                console.error("Inject failed:", e);
                resolve();
              });
            };
            chrome.tabs.onUpdated.addListener(listener);
            setTimeout(() => {
              chrome.tabs.onUpdated.removeListener(listener);
              resolve();
            }, 5000);
          });
  
          // Step B: 触发导航
          await BrowserAutomator.navigate(tab.id, searchUrl);
  
          // Step C: 等注入完成，再等页面加载完
          await injectPromise;
          await BrowserAutomator.waitForLoad(tab.id);
          await new Promise(r => setTimeout(r, 3000));
  
          // 检查是否遇到登录拦截或为空
          const pageInfo = await BrowserAutomator.execute(tab.id, () => ({
              isLogin: location.href.includes('login.1688.com') || !!document.querySelector('.login-box'),
              emptyHint: document.body?.innerText?.includes('空空如也') || false
            }) );
          if (pageInfo.isLogin) {
            broadcastToExtension({ type: "system", text: `🚨 [${i+1}/${items.length}] 警告：1688 未登录，已跳转登录页！请手动登录后重试。` });
            throw new Error("Requires 1688 Login");
          }
          if (pageInfo.emptyHint) {
            broadcastToExtension({ type: "system", text: `🚨 [${i+1}/${items.length}] 警告：1688 结果为空。这通常是因为未登录账号导致的图搜降级，请确认已在当前浏览器登录 1688。` });
          }
  
          // DOM 提取
          let domResult = await BrowserAutomator.execute(tab.id, extractProducts);
          let extracted = domResult;
  
          // 重试
          if (!extracted?.productCount) {
            broadcastToExtension({ type: "system", text: `⏳ [${i+1}/${items.length}] 0 商品，等 6 秒重试...` });
            await new Promise(r => setTimeout(r, 6000));
            domResult = await BrowserAutomator.execute(tab.id, extractProducts);
            extracted = domResult;
          }
  
          results[sku_id] = extracted;
          broadcastToExtension({ type: "system", text: `🔍 [${i+1}/${items.length}] ${sku_id}: ${extracted?.productCount || 0} 个候选商品` });
  
        } catch (e) {
          errors.push(`${sku_id}: ${e.message}`);
          results[sku_id] = { products: [], productCount: 0, error: e.message };
          broadcastToExtension({ type: "system", text: `❌ [${i+1}/${items.length}] ${sku_id}: ${e.message}` });
        }
      }
  } finally {
      if (tab) {
          await BrowserAutomator.closeTab(tab.id)
      }
  }
  respond({ results, errors });
}
