// common/js/ozon-analytics.js
//
// OZON 卖家分析数据（what_to_sell/data/v3）的共享调用层。
//
// 三处调用点（列表"数据一览"、"一键铺货"弹窗、数据导出中心）此前各自维护一份
// httpPostoz / ggetSkuFromurl / 70 字段空 item 字面量 / 响应整形逻辑。本文件把这些
// 公共部分抽出来，由 content scripts、iframe、service worker 共用。
//
// 加载方式：
//   1) content_scripts (manifest.json)：作为第一个 JS 注入，所有 ozon 域内脚本可用
//   2) background service worker：importScripts('common/js/ozon-analytics.js')
//   3) html/adtnfosku.html iframe：<script src="../common/js/ozon-analytics.js">
//
// 不能用顶层 let/const（content scripts 共享全局作用域，多次注入会冲突）。
// 全部用 var + 一个命名空间对象 OzAnalytics，并把工具函数挂到 globalThis 以保持
// 现有调用站点（ggetSkuFromurl(...) 之类的裸调）继续工作。

(function (root) {
    var ANALYTICS_URL = 'https://seller.ozon.ru/api/site/seller-analytics/what_to_sell/data/v3';
    var SEARCH_URL = 'https://seller.ozon.ru/api/v1/search';
    var SPIDER_PATH = '/SpiderOzon/adtoAll';

    function ggetSkuFromurl(url) {
        try {
            if (typeof url === 'object' && url && url.url) url = url.url;
            if (!url || typeof url !== 'string') return null;
            var path = url.split('?')[0];
            var parts = path.split('-');
            var last = parts[parts.length - 1] || '';
            var digits = last.match(/\d+/g);
            return digits ? digits[0] : null;
        } catch (e) {
            console.error('ggetSkuFromurl 出错:', e);
            return null;
        }
    }

    function buildRequestBody(sku) {
        return {
            filter: { stock: 'any_stock', sku: sku },
            sort: { key: 'sum_rating' },
            limit: 50,
            offset: 0
        };
    }

    // 5.19 新增：seller.ozon.ru/api/v1/search 的请求体（按 SKU 反查商品基础信息）
    function buildSearchRequestBody(scCompanyId, sku) {
        return {
            company_id: '' + scCompanyId + '',
            need_total: false,
            filter: {
                children_nodes: {
                    children_nodes: [{
                        input_leaf: { sku: { values: ['' + sku + ''] } }
                    }],
                    operator: 'AND'
                }
            },
            pagination: { limit: '50' },
            is_copy_allowed: false
        };
    }

    // 5.19 新增：上报到自家 SpiderOzon 的 payload 结构
    function buildSpiderPayload(combinedData, sku) {
        return {
            sku: sku,
            seller_analytics: combinedData.seller_analytics,
            serrchdata: combinedData.serrchdata,
            prinfo: combinedData.prinfo,
            timestamp: new Date().toISOString()
        };
    }

    function buildHeaders(scCompanyId, full) {
        var base = {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json',
            'Origin': 'https://seller.ozon.ru',
            'x-o3-company-id': scCompanyId,
            'x-o3-language': 'zh-Hans'
        };
        if (!full) return base;
        base['Accept-Encoding'] = 'gzip, deflate, br, zstd';
        base['Accept-Language'] = 'zh-Hans';
        base['Sec-Ch-Ua'] = 'Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"';
        base['Sec-Ch-Ua-Mobile'] = '?1';
        base['Sec-Ch-Ua-Platform'] = '"Android"';
        base['Sec-Fetch-Dest'] = 'empty';
        base['Sec-Fetch-Mode'] = 'cors';
        base['Sec-Fetch-Site'] = 'same-origin';
        base['User-Agent'] = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36';
        return base;
    }

    function emptySpecifications() {
        return { weight: 0, length: 0, width: 0, height: 0, unit: 'g/mm', success: false };
    }

    // 70 字段空 item 占位，sku 字段注入实际值。
    // 注意：原代码中 stock 在不同分支里分别填 "327" 和 "0"，此处保留与 ozon.js 路径一致的 "0"。
    function emptyItem(sku) {
        return [{
            'variantId': '-', 'photo': '-', 'name': '-', 'link': '-', 'brand': '-',
            'category1': '-', 'category3': '-', 'volume': 0, 'sessionCount': '0',
            'convToCart': 0, 'avgPrice': 0, 'sku': '' + (sku || '') + '',
            'convToCartPdp': 0, 'sources': ['-'],
            'blockedBySeller': true, 'blockedAsYourGood': false,
            'soldSum': 0, 'soldCount': '0', 'minSellerPrice': 0, 'salesDynamics': 0,
            'stock': '0', 'fbsStock': 0, 'fboStock': 0, 'cbStock': 0, 'retailStock': 0,
            'gmvSum': 0, 'sumItemsInStock': '0', 'daysInStock': '0', 'avgGmv': 0,
            'accessibility': 0, 'avgGmvOnAccDays': 0, 'avgOrdersOnAccDays': 0,
            'sumMissedGmv': 0, 'avgDeliveryDays': 0, 'qtyViewPdp': '0',
            'pdpToCartConversion': 0, 'skuName': '-', 'isSuper': false,
            'sellerId': '0', 'salesSchema': '-', 'sessionCountSearch': '0',
            'convToCartSearch': 0, 'drr': 0, 'nullableRedemptionRate': 0,
            'nullableCreateDate': '-', 'localIndex': 0, 'daysInPromo': 0,
            'promoRevenueShare': 0, 'daysWithTrafarets': 0, 'discount': 0,
            'views': '0', 'convViewToOrder': 0, 'sellerName': '-',
            'article': '0', 'bin': 'top_0', 'avgDeliveryTime': 0,
            'accessibilityByDays': 0, 'category3Id': '-', 'category1Id': '-',
            'category2Id': '-', 'brandId': '-'
        }];
    }

    // items 为空 → 注入空规格 + 空 item，整形成调用方期待的形状
    function shapeEmptyAnalytics(firstData, sku) {
        firstData.productDetail = emptySpecifications();
        firstData.items = emptyItem(sku);
        return firstData;
    }

    // 拿到 productDetail：合并、补 benchmark 兜底
    function shapeMergedWithDetail(firstData, productDetail) {
        var result = Object.assign({}, firstData, { productDetail: productDetail, _merged: true });
        if (Array.isArray(result.items) && result.items.length === 0) {
            result.items.push(result.benchmark);
        }
        return result;
    }

    // productDetail 取不到：用空规格包裹，items 用 benchmark 兜底
    function shapeFallbackWithoutDetail(firstData) {
        var resultb = Object.assign({}, firstData, {
            productDetail: { specifications: emptySpecifications() },
            items: { 0: firstData.benchmark },
            _merged: true
        });
        if (Array.isArray(resultb.items) && resultb.items.length === 0) {
            resultb.items.push(resultb.benchmark);
        }
        return resultb;
    }

    // detail 抓取抛错：直接退回 firstData，items 空就推 benchmark
    function shapeOnDetailError(firstData) {
        if (Array.isArray(firstData.items) && firstData.items.length === 0) {
            firstData.items.push(firstData.benchmark);
        }
        return firstData;
    }

    var api = {
        ANALYTICS_URL: ANALYTICS_URL,
        SEARCH_URL: SEARCH_URL,
        SPIDER_PATH: SPIDER_PATH,
        ggetSkuFromurl: ggetSkuFromurl,
        buildRequestBody: buildRequestBody,
        buildSearchRequestBody: buildSearchRequestBody,
        buildSpiderPayload: buildSpiderPayload,
        buildHeaders: buildHeaders,
        emptySpecifications: emptySpecifications,
        emptyItem: emptyItem,
        shapeEmptyAnalytics: shapeEmptyAnalytics,
        shapeMergedWithDetail: shapeMergedWithDetail,
        shapeFallbackWithoutDetail: shapeFallbackWithoutDetail,
        shapeOnDetailError: shapeOnDetailError
    };

    root.OzAnalytics = api;

    // 兼容旧调用：保留 ggetSkuFromurl 全局名
    if (typeof root.ggetSkuFromurl !== 'function') {
        root.ggetSkuFromurl = ggetSkuFromurl;
    }
})(typeof globalThis !== 'undefined' ? globalThis : (typeof self !== 'undefined' ? self : this));
