#!/usr/bin/env node
/**
 * GitLink CLI 卸载命令
 * 用法: gitlink-cli-uninstall [--purge]
 */

const { execSync } = require('child_process');
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 ask(msg) {
    console.log(`${colors.blue}[ASK]${colors.reset}  ${msg}`);
}

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

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

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

    if (removeSync(skillsDir)) {
        info('Skills已删除');
    } else {
        warn('Skills目录不存在或删除失败');
    }
}

// ---------- 删除配置 ----------
function removeConfig(purgeAll = false) {
    if (!purgeAll) {
        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)) {
            info(`已删除: ${configPath}`);
            removedCount++;
        }
    }

    if (removedCount > 0) {
        info('配置文件已删除');
    }
}

// ---------- 主流程 ----------
function main() {
    const args = process.argv.slice(2);
    const purgeAll = args.includes('--purge') || args.includes('-p');
    const help = args.includes('--help') || args.includes('-h');

    if (help) {
        console.log('');
        console.log('GitLink CLI 卸载命令');
        console.log('');
        console.log('用法: gitlink-cli-uninstall [选项]');
        console.log('');
        console.log('选项:');
        console.log('  --purge, -p  删除所有文件（包括配置）');
        console.log('  --help, -h   显示此帮助');
        console.log('');
        console.log('示例:');
        console.log('  gitlink-cli-uninstall         # 保留配置');
        console.log('  gitlink-cli-uninstall --purge # 完全删除');
        console.log('');
        process.exit(0);
    }

    console.log('');
    console.log('========================================');
    info('GitLink CLI 卸载');
    console.log('========================================');
    console.log('');

    step('卸载npm包...');

    try {
        // 执行npm uninstall
        if (process.platform === 'win32') {
            execSync('npm uninstall -g @gitlink-ai/cli', { stdio: 'inherit' });
        } else {
            execSync('npm uninstall -g @gitlink-ai/cli', { stdio: 'inherit' });
        }
    } catch (err) {
        warn('npm卸载命令执行失败，请手动运行: npm uninstall -g @gitlink-ai/cli');
    }

    // 删除skills
    removeSkills();

    // 删除配置
    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('如需删除，请运行: gitlink-cli-uninstall --purge');
    }

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

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