"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Api = void 0;
const vscode = __importStar(require("vscode"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const utils_1 = require("../util/utils");
class Api {
    // 静态变量存储唯一实例
    static instance;
    static isDownloading = false;
    static abortController = null;
    constructor() { }
    static getInstance() {
        if (!Api.instance) {
            Api.instance = new Api();
        }
        return Api.instance;
    }
    compareVersions(version1, version2) {
        return (0, utils_1.compareVersions)(version1, version2);
    }
    // 取消下载
    static cancelDownload() {
        if (Api.abortController) {
            Api.abortController.abort();
            Api.abortController = null;
        }
    }
    async checkForUpdateV2(currentVersion, context, signal) {
        if (Api.isDownloading) {
            console.info('Another download task is in progress, skipping...');
            return;
        }
        try {
            // 设置下载锁
            Api.isDownloading = true;
            // 创建 AbortController 用于取消下载
            Api.abortController = new AbortController();
            const abortSignal = signal || Api.abortController.signal;
            // 根据平台获取配置文件URL,没有linux平台，linux直接返回，不支持，要区分mac的arm64和x64
            const platform = os.platform();
            let configUrl;
            if (platform === 'win32') {
                configUrl = 'https://nfiles3three.autohome.com.cn/gpt-app-other/ide/vscode_win_x64/config.json';
            }
            else if (platform === 'darwin') {
                // 检查是否是 ARM 架构
                const isArm = os.arch() === 'arm64';
                configUrl = isArm
                    ? 'https://nfiles3three.autohome.com.cn/gpt-app-other/ide/vscode_mac_arm64/config.json'
                    : 'https://nfiles3three.autohome.com.cn/gpt-app-other/ide/vscode_mac_x86/config.json';
            }
            else {
                // Linux 或其他平台直接返回
                console.info(`Platform ${platform} is not supported`);
                return;
            }
            // 添加时间戳防止缓存
            configUrl = `${configUrl}?t=${Date.now()}`;
            // 获取配置文件
            const response = await fetch(configUrl, { signal: abortSignal });
            if (!response.ok) {
                throw new Error('Failed to fetch update config');
            }
            const config = await response.json();
            const latestVersion = config.latest_version;
            const downloadUrl = config.download_url;
            // 比较版本号
            const versionCompare = this.compareVersions(latestVersion, currentVersion);
            if (versionCompare <= 0) {
                console.info('Current version is up to date');
                return;
            }
            // 需要更新，下载新版本
            console.info(`Downloading new version: ${latestVersion}`);
            const vsixResponse = await fetch(downloadUrl + `?t=${Date.now()}`, { signal: abortSignal });
            if (!vsixResponse.ok) {
                throw new Error('Failed to download new version');
            }
            // 获取插件目录
            const extensionPath = context.extensionPath;
            if (!extensionPath) {
                throw new Error('Extension path not found');
            }
            // 检查插件目录是否存在
            if (!fs.existsSync(extensionPath)) {
                throw new Error('Extension directory does not exist');
            }
            // 获取插件外层目录
            const extensionDir = path.dirname(extensionPath);
            if (!fs.existsSync(extensionDir)) {
                throw new Error('Extension parent directory does not exist');
            }
            // 保存vsix文件到临时文件
            const vsixPath = await (0, utils_1.createTmpFile)();
            // 检查是否已取消
            if (abortSignal.aborted) {
                throw new Error('下载已取消');
            }
            const buffer = Buffer.from(await vsixResponse.arrayBuffer());
            // 再次检查是否已取消
            if (abortSignal.aborted) {
                throw new Error('下载已取消');
            }
            await fs.promises.writeFile(vsixPath, buffer);
            // 检查vsix文件是否成功创建
            if (!fs.existsSync(vsixPath)) {
                throw new Error('Failed to create vsix file');
            }
            // 安装新版本
            const uri = vscode.Uri.file(vsixPath);
            await vscode.commands.executeCommand('workbench.extensions.installExtension', uri);
            // 删除插件目录的上层目录中所有以ideaigenerate开头的文件
            try {
                const parentDir = path.dirname(extensionPath);
                const files = await fs.promises.readdir(parentDir);
                for (const file of files) {
                    if (file.startsWith('ideaigenerate')) {
                        const filePath = path.join(parentDir, file);
                        try {
                            fs.rmSync(filePath, { recursive: true, force: true });
                            console.info(`[Update] Deleted file or directory: ${filePath}`);
                        }
                        catch (err) {
                            console.error(`[Update] Failed to delete ${filePath}:`, err);
                        }
                    }
                }
            }
            catch (err) {
                console.error('[Update] Error while deleting ideaigenerate files:', err);
            }
            // 删除vsix文件,因为是临时文件，现在不用删除了
            // fs.rmSync(vsixPath, { recursive: true, force: true });
        }
        catch (error) {
            // 如果是取消操作，抛出特定的错误
            if (error.name === 'AbortError' || error.message === '下载已取消') {
                console.info('下载已取消');
                throw new Error('下载已取消');
            }
            console.error('Update check failed:', error);
            throw error;
        }
        finally {
            // 无论成功还是失败，都释放下载锁和 AbortController
            Api.isDownloading = false;
            Api.abortController = null;
        }
    }
}
exports.Api = Api;
const api = Api.getInstance();
exports.default = api;
//# sourceMappingURL=Api.js.map