/**
 * SHEIN API拦截器 - 页面级别注入脚本
 * 此脚本将被动态注入到页面中，在页面级别拦截网络请求
 * 使用立即执行函数确保在任何网络请求之前就覆盖原生方法
 */

(function() {
    'use strict';
    
    // 防止重复注入
    if (window.sheinInterceptorInjected) {
        console.log('⚠️ SHEIN拦截器已经注入，跳过');
        return;
    }
    window.sheinInterceptorInjected = true;
    
    console.log('🔧 SHEIN API拦截器开始初始化...');
    
    // 内存缓存变量
    let cachedProductDetail = null;
    let isContentScriptReady = false;
    
    // 立即存储原始方法，确保在任何其他脚本修改之前保存
    const originalXHROpen = XMLHttpRequest.prototype.open;
    const originalXHRSend = XMLHttpRequest.prototype.send;
    const originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
    const originalFetch = window.fetch;
    
    // 统计信息
    const stats = {
        total: 0,
        errors: 0,
        cached: 0
    };
    
    // 存储拦截到的数据
    let interceptedData = {
        storeCode: null,
        version: null,
        lang: null,
        authHeaders: {} // 存储从真实请求中拦截的认证头
    };
    
    // 缓存管理器
    const CacheManager = {
        // 保存商品详情数据到内存
        saveProductDetail(url, responseData) {
            cachedProductDetail = {
                url,
                data: responseData,
                timestamp: Date.now()
            };
            stats.cached++;
            console.log('💾 商品详情数据已缓存到内存');
            return true;
        },
        
        // 从内存获取商品详情数据
        getProductDetail() {
            if (cachedProductDetail) {
                console.log('📦 从内存获取到缓存数据');
                return cachedProductDetail;
            }
            return null;
        },
        
        // 检查content script是否就绪
        isContentReady() {
            return isContentScriptReady;
        },
        
        // 设置content script就绪状态
        setContentReady() {
            isContentScriptReady = true;
            console.log('✅ Content script就绪状态已设置');
        }
    };
    
    // 立即覆盖原生方法，确保在任何网络请求之前生效
    console.log('🚀 立即覆盖原生网络方法...');
    
    // 立即拦截XMLHttpRequest.prototype.open
    XMLHttpRequest.prototype.open = function(method, url, ...args) {
        this._interceptor = {
            method,
            url,
            startTime: Date.now(),
            headers: {}
        };
        
        return originalXHROpen.apply(this, [method, url, ...args]);
    };
    
    // 立即拦截XMLHttpRequest.prototype.setRequestHeader
    XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
        if (this._interceptor) {
            this._interceptor.headers[name] = value;
            
            // 如果是SHEIN API请求，保存认证相关的头
            if (this._interceptor.url && this._interceptor.url.includes('shein.com/bff-api/')) {
                const authHeaderNames = [
                    'x-csrf-token', 'x-gw-auth', 'x-oest', 'anti-in', 
                    'armortoken', 'smdeviceid', 'uber-trace-id', 'webversion'
                ];
                
                if (authHeaderNames.includes(name.toLowerCase())) {
                    interceptedData.authHeaders[name] = value;
                }
            }
        }
        
        return originalXHRSetRequestHeader.apply(this, [name, value]);
    };
    
    // 立即拦截XMLHttpRequest.prototype.send
    XMLHttpRequest.prototype.send = function(data) {
        const xhr = this;
        const interceptor = xhr._interceptor;
        
        if (interceptor) {
            interceptor.requestData = data;
            
            // 监听状态变化
            const originalOnReadyStateChange = xhr.onreadystatechange;
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    const endTime = Date.now();
                    const responseInfo = {
                        method: interceptor.method,
                        url: interceptor.url,
                        startTime: interceptor.startTime,
                        endTime,
                        duration: endTime - interceptor.startTime,
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText,
                        responseHeaders: xhr.getAllResponseHeaders(),
                        requestData: interceptor.requestData
                    };
                    
                    // 延迟处理响应，确保其他函数已定义
                    setTimeout(() => handleResponse(responseInfo), 0);
                }
                
                if (originalOnReadyStateChange) {
                    originalOnReadyStateChange.apply(this, arguments);
                }
            };
        }
        
        return originalXHRSend.apply(this, [data]);
    };
    
    // 立即拦截fetch
    window.fetch = async function(url, options = {}) {
        const startTime = Date.now();
        const method = options.method || 'GET';
        
        
        try {
            const response = await originalFetch(url, options);
            const endTime = Date.now();
            
            // 克隆响应以避免消费
            const clonedResponse = response.clone();
            
            try {
                const text = await clonedResponse.text();
                const responseInfo = {
                    method,
                    url: url.toString(),
                    startTime,
                    endTime,
                    duration: endTime - startTime,
                    status: response.status,
                    statusText: response.statusText,
                    responseText: text,
                    requestData: options.body
                };
                
                // 延迟处理响应，确保其他函数已定义
                setTimeout(() => handleResponse(responseInfo), 0);
            } catch (error) {
            }
            
            return response;
        } catch (error) {
            const endTime = Date.now();
            const errorInfo = {
                method,
                url: url.toString(),
                startTime,
                endTime,
                duration: endTime - startTime,
                error: error.message,
                requestData: options.body,
                status: 0
            };
            
            // 延迟处理响应，确保其他函数已定义
            setTimeout(() => handleResponse(errorInfo), 0);
            throw error;
        }
    };
    
    console.log('✅ 原生网络方法覆盖完成');
    
    // 发送数据到content script
    function sendToContentScript(data) {
        window.postMessage({
            type: 'SHEIN_API_INTERCEPTED',
            source: 'shein-interceptor',
            data: data
        }, '*');
    }
    
    // 提取URL参数
    function getUrlParams(url) {
        const params = {};
        try {
            // 如果是相对URL，添加当前域名
            let fullUrl = url;
            if (url.startsWith('/')) {
                fullUrl = window.location.origin + url;
            } else if (!url.startsWith('http')) {
                fullUrl = window.location.origin + '/' + url;
            }
            
            const urlObj = new URL(fullUrl);
            urlObj.searchParams.forEach((value, key) => {
                params[key] = value;
            });
        } catch (error) {
            console.log('❌ 解析URL参数失败:', error, 'URL:', url);
            // 尝试手动解析查询参数
            try {
                const queryString = url.includes('?') ? url.split('?')[1] : '';
                if (queryString) {
                    queryString.split('&').forEach(param => {
                        const [key, value] = param.split('=');
                        if (key && value) {
                            params[decodeURIComponent(key)] = decodeURIComponent(value);
                        }
                    });
                }
            } catch (fallbackError) {
                console.log('❌ 手动解析URL参数也失败:', fallbackError);
            }
        }
        return params;
    }
    
    // 发送店铺人气请求
    async function fetchStorePopularity(storeCode, version, lang) {
        try {
            const popularityUrl = `https://us.shein.com/bff-api/ccc/store/popularity?_ver=${version}&_lang=${lang}&storeCode=${storeCode}`;
            
            console.log('🏪 发送店铺人气请求:', popularityUrl);
            
            const response = await originalFetch(popularityUrl, {
                method: 'GET',
                headers: {
                    'accept': '*/*',
                    'accept-language': 'zh-CN,zh;q=0.9',
                    'sec-fetch-dest': 'empty',
                    'sec-fetch-mode': 'cors',
                    'sec-fetch-site': 'same-origin'
                },
                credentials: 'include'
            });
            
            if (response.ok) {
                const data = await response.text();
                console.log('✅ 店铺人气数据获取成功');
                
                // 发送店铺数据到content script
                sendToContentScript({
                    type: 'store_popularity_data',
                    storeCode,
                    data,
                    timestamp: Date.now()
                });
                
                return data;
            } else {
                console.log('❌ 店铺人气请求失败:', response.status);
            }
        } catch (error) {
            console.log('❌ 发送店铺人气请求时出错:', error);
        }
    }
    // 处理商品详情响应
    function handleGoodsDetailResponse(responseInfo) {
        const { url, responseText } = responseInfo;
        
        try {
            const data = JSON.parse(responseText);
            
            // 提取storeCode
            const storeCode = data?.info?.shipInfo?.shipRequestInfo?.storeCode;
            
            if (storeCode) {
                console.log('🏪 从商品详情中提取到storeCode:', storeCode);
                
                // 从原始URL中提取参数
                console.log('🔍 正在解析URL参数，URL:', url);
                const urlParams = getUrlParams(url);
                console.log('📋 解析到的URL参数:', urlParams);
                
                const version = urlParams._ver || '1.1.8';
                const lang = urlParams._lang || 'en';
                
                console.log('🌐 使用参数 - version:', version, 'lang:', lang);
                
                // 发送店铺人气请求
                fetchStorePopularity(storeCode, version, lang);
                
            } else {
                console.log('⚠️ 未找到storeCode在响应数据中');
                console.log('📄 响应数据结构:', {
                    hasInfo: !!data?.info,
                    hasShipInfo: !!data?.info?.shipInfo,
                    hasShipRequestInfo: !!data?.info?.shipInfo?.shipRequestInfo
                });
            }
        } catch (error) {
            console.log('❌ 解析商品详情响应失败:', error);
            console.log('📄 原始响应文本长度:', responseText?.length || 0);
        }
    }
    
    // 处理响应数据
    function handleResponse(responseInfo) {
        const { url, method, status, responseText, duration } = responseInfo;
        
        // 检查是否是商品详情API请求
        if (url.includes('/bff-api/product/get_goods_detail_realtime_data') && status === 200) {
            console.log('🎯 检测到商品详情API请求');
            
            // 缓存商品详情数据
            CacheManager.saveProductDetail(url, responseText);
            
            // 如果content script已就绪，立即发送数据
            if (CacheManager.isContentReady()) {
                console.log('📤 Content script已就绪，立即发送商品详情数据');
                sendToContentScript({
                    type: 'api_response',
                    url,
                    method,
                    status,
                    duration,
                    responseText,
                    timestamp: Date.now()
                });
            } else {
                console.log('⏳ Content script未就绪，数据已缓存到内存');
            }
            
            // 处理店铺数据获取
            handleGoodsDetailResponse(responseInfo);
            return;
        }
        
        // 对于其他请求，只在content script就绪时发送
        if (CacheManager.isContentReady()) {
            sendToContentScript({
                type: 'api_response',
                url,
                method,
                status,
                duration,
                responseText,
                timestamp: Date.now()
            });
        }
    }
    
    // 监听来自content script的消息
    window.addEventListener('message', function(event) {
        if (event.source !== window) return;
        
        const { type, source } = event.data;
        if (source !== 'shein-content-script') return;
        
        switch (type) {
            case 'SHEIN_CONTENT_SCRIPT_READY':
                console.log('✅ 收到content script就绪信号');
                CacheManager.setContentReady();
                
                // 检查是否有缓存的商品详情数据
                const cachedData = CacheManager.getProductDetail();
                if (cachedData) {
                    console.log('📤 发送缓存的商品详情数据到content script');
                    sendToContentScript({
                        type: 'api_response',
                        url: cachedData.url,
                        method: 'GET',
                        status: 200,
                        duration: 0,
                        responseText: cachedData.data,
                        timestamp: cachedData.timestamp,
                        fromCache: true
                    });
                }
                break;
                
            case 'REQUEST_CACHED_DATA':
                console.log('📦 收到主动获取缓存数据请求');
                const cached = CacheManager.getProductDetail();
                if (cached) {
                    sendToContentScript({
                        type: 'api_response',
                        url: cached.url,
                        method: 'GET',
                        status: 200,
                        duration: 0,
                        responseText: cached.data,
                        timestamp: cached.timestamp,
                        fromCache: true
                    });
                } else {
                    console.log('📭 没有找到缓存的商品详情数据');
                    sendToContentScript({
                        type: 'no_cached_data',
                        timestamp: Date.now()
                    });
                }
                break;
        }
    });
    
    
    window.getSheinCachedData = function() {
        return CacheManager.getProductDetail();
    };
    
    console.log('✅ SHEIN API拦截器初始化完成');
    
    // 发送初始化完成消息
    sendToContentScript({
        type: 'interceptor_ready',
        timestamp: Date.now()
    });
    
})();