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

  broadcastToExtension({ type: "system", text: `🔍 正在通过单标签页模式抓取 ${items.length} 个 Ozon 商品...` });

  const results = {};
  const errors = [];
  let completed = 0;
  let tab = null;

  try {
    // 创建一个持久的后台标签页
    tab = await BrowserAutomator.createTab("about:blank", false);

    for (const item of items) {
      const { sku_id, product_url } = item;
      try {
        // 导航到目标 URL
        await BrowserAutomator.navigate(tab.id, product_url);

        // 等待加载
        await BrowserAutomator.waitForLoad(tab.id, 30000, 1500);

        // 提取
        // ── 抓取最多 3 张 Ozon 商品图 ──
        const scriptResults = await BrowserAutomator.execute(tab.id, () => {
            const MAX_IMAGES = 3;
            const gallery = document.querySelector('[data-widget="webGallery"]');
            const urls = [];
            
            if (gallery) {
              const imgs = gallery.querySelectorAll('img');
              for (let i = 0; i < imgs.length && urls.length < MAX_IMAGES; i++) {
                const src = imgs[i]?.src;
                if (src && !src.includes('og_ozon_ru.png') && !urls.includes(src)) {
                  urls.push(src.replace(/\/wc\d+/, '/wc2000'));
                }
              }
            }
            
            // 如果 gallery 没取到（下架/重定向），从搜索结果取
            if (urls.length === 0) {
              const searchImgs = document.querySelectorAll('.widget-search-result-container img, [data-widget="searchResultsV2"] img');
              for (let i = 0; i < searchImgs.length && urls.length < MAX_IMAGES; i++) {
                const src = searchImgs[i]?.src;
                if (src && !src.includes('og_ozon_ru.png') && !urls.includes(src)) {
                  urls.push(src.replace(/\/wc\d+/, '/wc2000'));
                }
              }
            }
            
            // 兜底 og:image
            if (urls.length === 0) {
              const ogSrc = document.querySelector('meta[property="og:image"]')?.content;
              if (ogSrc && !ogSrc.includes('og_ozon_ru.png')) {
                urls.push(ogSrc.replace(/\/wc\d+/, '/wc2000'));
              }
            }
            
            return urls.length > 0 ? { img_urls: urls } : null;
          }
        );

        const res = scriptResults;
        if (res && res.img_urls && res.img_urls.length > 0) {
          // ═══ 在 Ozon 页面上下文里把每张图转 JPEG base64 ═══
          const imgDataList = [];
          for (let imgIdx = 0; imgIdx < res.img_urls.length; imgIdx++) {
            const imgUrl = res.img_urls[imgIdx];
            let jpegBase64 = null;
            try {
              // 1. 先用 background.js 拥有 <all_urls> 的特权抓图（无视 CORS 拦截）
              const resp = await fetch(imgUrl, { headers: { 'Referer': 'https://www.ozon.ru/' } });
              if (!resp.ok) throw new Error("HTTP error " + resp.status);
              const blob = await resp.blob();
              
              // 2. 直接在 Service Worker 里使用 OffscreenCanvas 将 WebP/任意格式 转换为纯正的 JPEG
              const img = await createImageBitmap(blob);
              const canvas = new OffscreenCanvas(img.width, img.height);
              const ctx = canvas.getContext('2d');
              ctx.fillStyle = '#FFFFFF'; // 填充白底，防止 PNG/WebP 透明通道变黑
              ctx.fillRect(0, 0, img.width, img.height);
              ctx.drawImage(img, 0, 0);
              const outBlob = await canvas.convertToBlob({ type: 'image/jpeg', quality: 0.85 });
              
              const buffer = await outBlob.arrayBuffer();
              const bytes = new Uint8Array(buffer);
              let binary = '';
              // 每 1024 字节拼一次避免循环太慢
              const chunkSize = 8192;
              for (let i = 0; i < bytes.length; i += chunkSize) {
                binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunkSize));
              }
              jpegBase64 = 'data:image/jpeg;base64,' + btoa(binary);
            } catch(e) {
              console.error("图片转换失败: ", e);
            }
            imgDataList.push({ img_url: imgUrl, img_base64: jpegBase64 });
          }

          // 兼容老格式：img_url/img_base64 指向第一张，新增 img_list 字段存全部
          results[sku_id] = {
            img_url: imgDataList[0].img_url,
            img_base64: imgDataList[0].img_base64,
            img_list: imgDataList,  // 新字段：所有图的列表
          };
          // 缓存第一张用于 1688 搜索
          if (imgDataList[0].img_base64 && imgDataList[0].img_base64.length > 1000) {
            imageBase64Cache.set(sku_id, imgDataList[0].img_base64);
            try {
              const cacheName = `ozon-images-${data.task_id || 'default'}`;
              const cache = await caches.open(cacheName);
              const fetchRes = await fetch(imgDataList[0].img_base64);
              await cache.put(`https://local-ozon-cache/${sku_id}.jpg`, fetchRes);
            } catch(err) { console.error('Cache API put failed:', err); }
          }
          // 缓存第二张用于 1688 备用搜索
          if (imgDataList.length > 1 && imgDataList[1].img_base64 && imgDataList[1].img_base64.length > 1000) {
            imageBase64Cache.set(sku_id + '_alt', imgDataList[1].img_base64);
            try {
              const cacheName = `ozon-images-${data.task_id || 'default'}`;
              const cache = await caches.open(cacheName);
              const fetchRes = await fetch(imgDataList[1].img_base64);
              await cache.put(`https://local-ozon-cache/${sku_id}_alt.jpg`, fetchRes);
            } catch(err) {}
          }
          broadcastToExtension({ type: "system", text: `💾 ${sku_id}: 成功抓取 ${imgDataList.length} 张图` });
        } else {
          results[sku_id] = null;
        }
      } catch (e) {
        errors.push(`${sku_id}: ${e.message}`);
        results[sku_id] = null;
      }
      completed++;
      broadcastToExtension({ type: "system", text: `📸 抓图进度: [${completed}/${items.length}] ${sku_id} ${results[sku_id] ? '✅' : '❌'}` });
    }
  } finally {
    if (tab) BrowserAutomator.closeTab(tab.id);
  }

  broadcastToExtension({ type: "system", text: `✅ 抓图完成！` });
  respond({ results, errors });
}
