'use strict';

// ============================================
// CursorPro Extension - 反混淆版本
// ============================================

const vscode = require('vscode');
const { CursorProProvider } = require('./webview/provider');
const fs = require('fs');
const path = require('path');

let usageStatusBarItem;

// 创建输出通道
const outputChannel = vscode.window.createOutputChannel('CursorPro');
exports.outputChannel = outputChannel;

/**
 * 日志输出函数
 */
function log(message) {
    const timestamp = new Date().toLocaleTimeString();
    outputChannel.appendLine(`[${timestamp}] ${message}`);
    console.log(`[CursorPro] ${message}`);
}
exports.log = log;

/**
 * 清理 Service Worker 缓存
 */
function cleanServiceWorkerCache() {
    try {
        const platform = process.platform;
        const cachePaths = [];

        if (platform === 'win32') {
            const appData = process.env.APPDATA || '';
            const localAppData = process.env.LOCALAPPDATA || '';
            cachePaths.push(
                path.join(appData, 'Cursor', 'Cache'),
                path.join(localAppData, 'Cursor', 'Cache'),
                path.join(appData, 'Cursor', 'GPUCache'),
                path.join(localAppData, 'Cursor', 'GPUCache')
            );
        } else if (platform === 'darwin') {
            const home = process.env.HOME || '';
            cachePaths.push(
                path.join(home, 'Library', 'Application Support', 'Cursor', 'Cache'),
                path.join(home, 'Library', 'Application Support', 'Cursor', 'GPUCache')
            );
        } else {
            const home = process.env.HOME || '';
            cachePaths.push(
                path.join(home, '.config', 'Cursor', 'Cache'),
                path.join(home, '.config', 'Cursor', 'Service Worker')
            );
        }

        for (const cachePath of cachePaths) {
            if (!fs.existsSync(cachePath)) continue;

            const cachesDir = path.join(cachePath, 'Caches');
            if (fs.existsSync(cachesDir)) {
                try {
                    const files = fs.readdirSync(cachesDir);
                    for (const file of files) {
                        try { fs.unlinkSync(path.join(cachesDir, file)); } catch (e) {}
                    }
                    console.log('[CursorPro] Caches 已清理:', cachesDir);
                } catch (e) {}
            }

            const cacheStorageDir = path.join(cachePath, 'CacheStorage');
            if (fs.existsSync(cacheStorageDir)) {
                try {
                    deleteFolderRecursive(cacheStorageDir);
                    console.log('[CursorPro] CacheStorage 已清理:', cacheStorageDir);
                } catch (e) {}
            }

            const databaseDir = path.join(cachePath, 'Database');
            if (fs.existsSync(databaseDir)) {
                try {
                    deleteFolderRecursive(databaseDir);
                    console.log('[CursorPro] Database 已清理:', databaseDir);
                } catch (e) {}
            }
        }
    } catch (error) {
        console.log('[CursorPro] 清理缓存出错:', error);
    }
}

function deleteFolderRecursive(folderPath) {
    if (fs.existsSync(folderPath)) {
        fs.readdirSync(folderPath).forEach((file) => {
            const curPath = path.join(folderPath, file);
            if (fs.lstatSync(curPath).isDirectory()) {
                deleteFolderRecursive(curPath);
            } else {
                try { fs.unlinkSync(curPath); } catch (e) {}
            }
        });
        try { fs.rmdirSync(folderPath); } catch (e) {}
    }
}

/**
 * 扩展激活入口
 */
function activate(context) {
    cleanServiceWorkerCache();

    const provider = new CursorProProvider(context.extensionUri, context);
    context.subscriptions.push(
        vscode.window.registerWebviewViewProvider('cursorpro.sidebar', provider)
    );

    usageStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
    usageStatusBarItem.text = '$(dashboard) CursorPro';
    usageStatusBarItem.tooltip = 'CursorPro 使用情况';
    usageStatusBarItem.command = 'cursorpro.showUsage';
    usageStatusBarItem.backgroundColor = new vscode.ThemeColor('statusBarItem.warningBackground');

    const hasKey = context.globalState.get('cursorpro.key');
    if (hasKey) usageStatusBarItem.show();

    context.subscriptions.push(usageStatusBarItem);
    context.subscriptions.setKeysForSync(['cursorpro.key']);

    context.subscriptions.push(
        vscode.commands.registerCommand('cursorpro.showUsage', () => {
            vscode.commands.executeCommand('cursorpro.sidebar.focus');
        })
    );
}
exports.activate = activate;

function deactivate() {
    console.log('[CursorPro] 扩展已停用');
}
exports.deactivate = deactivate;

function showStatusBar() {
    if (usageStatusBarItem) usageStatusBarItem.show();
}
exports.showStatusBar = showStatusBar;

function hideStatusBar() {
    if (usageStatusBarItem) usageStatusBarItem.hide();
}
exports.hideStatusBar = hideStatusBar;

function updateUsageStatusBar(requestCount, usageAmount) {
    if (usageStatusBarItem) {
        const count = requestCount;
        const amount = typeof usageAmount === 'number'
            ? usageAmount
            : parseFloat(usageAmount.toString().replace('$', '')) || 0;
        const displayAmount = typeof usageAmount === 'number'
            ? '$' + usageAmount.toFixed(2)
            : usageAmount;

        usageStatusBarItem.text = `$(dashboard) ${count} | ${displayAmount}`;
        usageStatusBarItem.tooltip = `请求次数: ${count}\n已用额度: ${displayAmount}\n点击查看详情`;

        if (amount >= 10) {
            usageStatusBarItem.backgroundColor = new vscode.ThemeColor('statusBarItem.errorBackground');
            usageStatusBarItem.color = undefined;
        } else if (amount >= 5) {
            usageStatusBarItem.backgroundColor = new vscode.ThemeColor('statusBarItem.warningBackground');
            usageStatusBarItem.color = undefined;
        } else {
            usageStatusBarItem.backgroundColor = undefined;
            usageStatusBarItem.color = 'statusBarItem.warningBackground';
        }
    }
}
exports.updateUsageStatusBar = updateUsageStatusBar;
