/**
 * ReviewCounter - 评价计数器系统
 * 
 * 功能说明：
 * 1. 结合ADHDGoFlyCounter的节点处理技术逻辑
 * 2. 实现类似ReviewTimer的版本更新重置逻辑
 * 3. 页面计数器：统计不重复页面访问，1小时内同一页面只计数一次
 * 4. 节点计数器：统计实际处理的文本节点数量，每个节点处理完计数一次
 * 5. 评价提醒：基于天数+节点数双重条件触发
 * 6. 隐私保护：URL使用SHA-256哈希值存储
 * 7. 版本更新时根据配置决定是否重置计数器
 */

class ReviewCounter {
    constructor() {
        // 存储键定义
        this.STORAGE_KEYS = {
            NODE_COUNT: 'review_counter_node_count',
            PAGE_COUNT: 'review_counter_page_count', 
            PAGE_VISITS: 'review_counter_page_visits',
            METADATA: 'review_counter_metadata',
            INSTALL_TIME: 'review_counter_install_time',
            INSTALL_VERSION: 'review_counter_install_version'
        };
        
        // 版本重置配置
        this.VERSION_RESET = {
            majorVersionReset: true,  // 主版本更新时重置
            minorVersionReset: false, // 次版本更新时不重置
            patchVersionReset: false  // 补丁版本更新时不重置
        };
        
        // 时间常量
        this.ONE_HOUR_MS = 60 * 60 * 1000; // 1小时毫秒数
        
        // 获取当前版本
        this.currentVersion = chrome.runtime.getManifest().version;
    }

    /**
     * 初始化计数器系统
     */
    async init() {
        try {
            console.log('ReviewCounter计数：开始初始化评价计数器系统...');
            
            const stored = await this._getStorageData([
                this.STORAGE_KEYS.INSTALL_TIME,
                this.STORAGE_KEYS.INSTALL_VERSION
            ]);
            
            const installTime = stored[this.STORAGE_KEYS.INSTALL_TIME];
            const installVersion = stored[this.STORAGE_KEYS.INSTALL_VERSION];
            
            // 检查是否需要重置
            if (!installTime || this.shouldResetCounter(installVersion)) {
                await this.resetCounter();
                console.log('ReviewCounter计数：计数器已重置（首次安装或版本更新）');
            } else {
                console.log('ReviewCounter计数：使用现有计数器数据');
            }
            
            // 更新版本信息
            await this._setStorageData({
                [this.STORAGE_KEYS.INSTALL_TIME]: installTime || Date.now(),
                [this.STORAGE_KEYS.INSTALL_VERSION]: this.currentVersion
            });
            
            console.log('ReviewCounter计数：评价计数器系统初始化成功');
            return true;
        } catch (error) {
            console.error('ReviewCounter计数：初始化失败:', error);
            return false;
        }
    }

    /**
     * 检查是否应该重置计数器
     * @param {string} storedVersion - 存储的版本号
     * @returns {boolean} 是否需要重置
     */
    shouldResetCounter(storedVersion) {
        if (!storedVersion) return true;
        
        const current = this.parseVersion(this.currentVersion);
        const stored = this.parseVersion(storedVersion);
        
        // 检查主版本更新
        if (this.VERSION_RESET.majorVersionReset && 
            current.major > stored.major) {
            console.log('ReviewCounter计数：检测到主版本更新，将重置计数器');
            return true;
        }
        
        // 检查次版本更新
        if (this.VERSION_RESET.minorVersionReset && 
            current.major === stored.major && 
            current.minor > stored.minor) {
            console.log('ReviewCounter计数：检测到次版本更新，将重置计数器');
            return true;
        }
        
        // 检查补丁版本更新
        if (this.VERSION_RESET.patchVersionReset && 
            current.major === stored.major && 
            current.minor === stored.minor && 
            current.patch > stored.patch) {
            console.log('ReviewCounter计数：检测到补丁版本更新，将重置计数器');
            return true;
        }
        
        return false;
    }

    /**
     * 解析版本号
     * @param {string} version - 版本号字符串
     * @returns {object} 解析后的版本对象
     */
    parseVersion(version) {
        const parts = version.split('.').map(Number);
        return {
            major: parts[0] || 0,
            minor: parts[1] || 0,
            patch: parts[2] || 0
        };
    }

    /**
     * 增加节点计数
     * @param {number} count - 增加的节点数量，默认为1
     */
    async incrementNodeCount(count = 1) {
        try {
            const currentCount = await this.getNodeCount();
            const newCount = currentCount + count;
            
            await this._setStorageData({
                [this.STORAGE_KEYS.NODE_COUNT]: newCount
            });
            
            if (window.__LOG_DEV_MODE) console.log(`ReviewCounter计数：节点计数更新: ${currentCount} → ${newCount} (+${count})`);
            return newCount;
        } catch (error) {
            console.error('ReviewCounter计数：节点计数更新失败:', error);
            return 0;
        }
    }

    /**
     * 增加页面计数（带去重逻辑）
     * @param {string} url - 当前页面URL
     */
    async incrementPageCount(url = window.location.href) {
        try {
            // 生成URL哈希
            const urlHash = await this._generateUrlHash(url);
            const currentTime = Date.now();
            
            // 获取页面访问记录
            const pageVisits = await this._getStorageData(this.STORAGE_KEYS.PAGE_VISITS, {});
            
            // 检查是否需要计数
            const lastVisit = pageVisits[urlHash];
            const shouldCount = !lastVisit || (currentTime - lastVisit.timestamp > this.ONE_HOUR_MS);
            
            if (shouldCount) {
                // 更新页面访问记录
                pageVisits[urlHash] = {
                    timestamp: currentTime,
                    url: url // 仅用于调试，实际存储时可考虑移除
                };
                
                // 清理过期记录
                this._cleanExpiredVisits(pageVisits, currentTime);
                
                // 保存页面访问记录
                await this._setStorageData({
                    [this.STORAGE_KEYS.PAGE_VISITS]: pageVisits
                });
                
                // 增加页面计数
                const currentPageCount = await this.getPageCount();
                const newPageCount = currentPageCount + 1;
                await this._setStorageData({
                    [this.STORAGE_KEYS.PAGE_COUNT]: newPageCount
                });
                
                console.log(`ReviewCounter计数：页面计数更新: ${currentPageCount} → ${newPageCount} (新页面: ${url})`);
                return newPageCount;
            } else {
                const timeSinceLastVisit = Math.round((currentTime - lastVisit.timestamp) / (1000 * 60));
                const currentPageCount = await this.getPageCount();
                if (window.__LOG_DEV_MODE) console.log(`ReviewCounter计数：页面重复访问，跳过计数 (距离上次访问: ${timeSinceLastVisit}分钟) - 当前累计页面数: ${currentPageCount}`);
                return currentPageCount;
            }
        } catch (error) {
            console.error('ReviewCounter计数：页面计数更新失败:', error);
            return 0;
        }
    }

    /**
     * 获取节点计数
     */
    async getNodeCount() {
        return await this._getStorageData(this.STORAGE_KEYS.NODE_COUNT, 0);
    }

    /**
     * 获取页面计数
     */
    async getPageCount() {
        return await this._getStorageData(this.STORAGE_KEYS.PAGE_COUNT, 0);
    }



    /**
     * 标记评价提醒已显示
     */
    async markRatingReminderShown(reminderKey) {
        try {
            const metadata = await this._getStorageData(this.STORAGE_KEYS.METADATA, {});
            const shownReminders = metadata.shownReminders || [];
            
            if (!shownReminders.includes(reminderKey)) {
                shownReminders.push(reminderKey);
                metadata.shownReminders = shownReminders;
                await this._setStorageData({
                    [this.STORAGE_KEYS.METADATA]: metadata
                });
                
                console.log(`ReviewCounter计数：评价提醒已标记为显示: ${reminderKey}`);
            }
        } catch (error) {
            console.error('ReviewCounter计数：标记评价提醒失败:', error);
        }
    }

    /**
     * 获取统计元数据
     */
    async getMetadata() {
        try {
            const metadata = await this._getStorageData(this.STORAGE_KEYS.METADATA, {});
            const installTime = await this._getStorageData(this.STORAGE_KEYS.INSTALL_TIME, Date.now());
            const nodeCount = await this.getNodeCount();
            const pageCount = await this.getPageCount();
            
            const daysSinceInstall = Math.floor((Date.now() - installTime) / (1000 * 60 * 60 * 24));
            
            return {
                installTime,
                daysSinceInstall,
                nodeCount,
                pageCount,
                shownReminders: metadata.shownReminders || [],
                averageNodesPerDay: daysSinceInstall > 0 ? Math.round(nodeCount / daysSinceInstall) : 0,
                averagePagesPerDay: daysSinceInstall > 0 ? Math.round(pageCount / daysSinceInstall) : 0,
                version: await this._getStorageData(this.STORAGE_KEYS.INSTALL_VERSION, 'unknown')
            };
        } catch (error) {
            console.error('ReviewCounter计数：获取元数据失败:', error);
            return {};
        }
    }

    /**
     * 重置计数器
     */
    async resetCounter() {
        try {
            await this._removeStorageData([
                this.STORAGE_KEYS.NODE_COUNT,
                this.STORAGE_KEYS.PAGE_COUNT,
                this.STORAGE_KEYS.PAGE_VISITS,
                this.STORAGE_KEYS.METADATA
            ]);
            
            console.log('ReviewCounter计数：计数器已重置');
        } catch (error) {
            console.error('ReviewCounter计数：重置计数器失败:', error);
        }
    }

    /**
     * 输出当前状态日志
     */
    async logCurrentStatus() {
        try {
            const metadata = await this.getMetadata();
            console.log('ReviewCounter计数：=== 当前状态 ===');
            console.log(`ReviewCounter计数：安装时间: ${new Date(metadata.installTime).toLocaleString()}`);
            console.log(`ReviewCounter计数：安装天数: ${metadata.daysSinceInstall}天`);
            console.log(`ReviewCounter计数：节点计数: ${metadata.nodeCount}`);
            console.log(`ReviewCounter计数：页面计数: ${metadata.pageCount}`);
            console.log(`ReviewCounter计数：平均每日节点: ${metadata.averageNodesPerDay}`);
            console.log(`ReviewCounter计数：平均每日页面: ${metadata.averagePagesPerDay}`);
            console.log(`ReviewCounter计数：版本: ${metadata.version}`);
            console.log('ReviewCounter计数：==================');
        } catch (error) {
            console.error('ReviewCounter计数：输出状态失败:', error);
        }
    }

    // ==================== 私有方法 ====================

    /**
     * 生成URL的SHA-256哈希值
     */
    async _generateUrlHash(url) {
        try {
            const encoder = new TextEncoder();
            const data = encoder.encode(url);
            const hashBuffer = await crypto.subtle.digest('SHA-256', data);
            const hashArray = Array.from(new Uint8Array(hashBuffer));
            return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
        } catch (error) {
            console.error('ReviewCounter计数：URL哈希生成失败:', error);
            // 降级方案：使用简单哈希
            return this._simpleHash(url);
        }
    }

    /**
     * 简单哈希函数（降级方案）
     */
    _simpleHash(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // 转换为32位整数
        }
        return Math.abs(hash).toString(16);
    }

    /**
     * 清理过期的页面访问记录
     */
    _cleanExpiredVisits(pageVisits, currentTime) {
        const expiredKeys = [];
        
        for (const [urlHash, visitData] of Object.entries(pageVisits)) {
            if (currentTime - visitData.timestamp > this.ONE_HOUR_MS) {
                expiredKeys.push(urlHash);
            }
        }
        
        expiredKeys.forEach(key => delete pageVisits[key]);
        
        if (expiredKeys.length > 0) {
            console.log(`ReviewCounter计数：清理过期页面访问记录: ${expiredKeys.length}条`);
        }
    }

    /**
     * 获取存储数据
     */
    async _getStorageData(keys, defaultValue = null) {
        return new Promise((resolve) => {
            const keyArray = Array.isArray(keys) ? keys : [keys];
            chrome.storage.local.get(keyArray, (result) => {
                if (Array.isArray(keys)) {
                    resolve(result);
                } else {
                    resolve(result[keys] !== undefined ? result[keys] : defaultValue);
                }
            });
        });
    }

    /**
     * 设置存储数据
     */
    async _setStorageData(data) {
        return new Promise((resolve, reject) => {
            chrome.storage.local.set(data, () => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve();
                }
            });
        });
    }

    /**
     * 删除存储数据
     */
    async _removeStorageData(keys) {
        return new Promise((resolve, reject) => {
            chrome.storage.local.remove(keys, () => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve();
                }
            });
        });
    }
}

// 导出类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ReviewCounter;
} else if (typeof window !== 'undefined') {
    window.ReviewCounter = ReviewCounter;
}