#!/usr/bin/env node
/**
 * GitLink CLI npm 卸载脚本
 * npm preuninstall 钩子自动运行
 */

const fs = require('fs');
const path = require('path');
const os = require('os');

// 颜色输出（支持跨平台）
const colors = {
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    red: '\x1b[31m',
    cyan: '\x1b[36m',
    blue: '\x1b[34m',
    reset: '\x1b[0m'
};

function info(msg) {
    console.log(`${colors.green}[INFO]${colors.reset}  ${msg}`);
}

function warn(msg) {
    console.log(`${colors.yellow}[WARN]${colors.reset}  ${msg}`);
}

function error(msg) {
    console.log(`${colors.red}[ERROR]${colors.reset} ${msg}`);
}

function step(msg) {
    console.log(`${colors.cyan}[STEP]${colors.reset} ${msg}`);
}

// ---------- 删除文件/目录 ----------
function removeSync(target) {
    try {
        if (fs.existsSync(target)) {
            const stat = fs.statSync(target);
            if (stat.isDirectory()) {
                fs.rmdirSync(target, { recursive: true });
                info(`已删除目录: ${target}`);
            } else {
                fs.unlinkSync(target);
                info(`已删除文件: ${target}`);
            }
            return true;
        }
        return false;
    } catch (err) {
        warn(`删除失败: ${target} - ${err.message}`);
        return false;
    }
}

// ---------- 删除Skills ----------
function removeSkills() {
    step('删除 Skills...');

    const skillsDir = path.join(os.homedir(), '.gitlink', 'skills');

    if (!fs.existsSync(skillsDir)) {
        warn('Skills目录不存在');
        return;
    }

    // 统计skills数量
    let skillCount = 0;
    try {
        const items = fs.readdirSync(skillsDir);
        skillCount = items.filter(item => {
            const itemPath = path.join(skillsDir, item);
            return fs.statSync(itemPath).isDirectory();
        }).length;
    } catch (err) {
        // 忽略错误
    }

    info(`找到 ${skillCount} 个Skills`);

    if (removeSync(skillsDir)) {
        info('Skills已删除');
    }
}

// ---------- 删除配置（可选）----------
function removeConfig(purgeAll = false) {
    if (!purgeAll) {
        // npm卸载通常不删除配置
        info('保留配置文件（用户数据）');
        return;
    }

    step('删除配置文件...');

    const configPaths = [
        path.join(os.homedir(), '.gitlink-cli'),
        path.join(os.homedir(), '.config', 'gitlink-cli'),
        path.join(os.homedir(), '.gitlink')
    ];

    let removedCount = 0;
    for (const configPath of configPaths) {
        if (removeSync(configPath)) {
            removedCount++;
        }
    }

    if (removedCount > 0) {
        info('配置文件已删除');
    } else {
        warn('未找到配置文件');
    }
}

// ---------- 主流程 ----------
function main() {
    console.log('');
    console.log('========================================');
    info('GitLink CLI npm 卸载');
    console.log('========================================');
    console.log('');

    // 检查环境变量
    const purgeAll = process.env.GITLINK_UNINSTALL_PURGE === 'true' || process.argv.includes('--purge');

    step('开始清理npm安装的文件...');

    // 删除skills
    removeSkills();

    // 删除配置（如果指定--purge）
    removeConfig(purgeAll);

    console.log('');
    console.log('========================================');
    info('卸载完成！');
    console.log('========================================');
    console.log('');

    if (!purgeAll) {
        info('以下文件可能需要手动清理:');
        console.log(`  - ${path.join(os.homedir(), '.gitlink-cli')}`);
        console.log(`  - ${path.join(os.homedir(), '.gitlink')}`);
        console.log('');
        info('如需删除，请运行: npm uninstall -g @gitlink-ai/cli --purge');
    }

    console.log('');
    info('感谢使用 GitLink CLI！');
    console.log('');
}

// 运行
try {
    main();
} catch (err) {
    error(`卸载失败: ${err.message}`);
    process.exit(1);
}