"use strict";
/**
 * Migration: Pre-cleanup Empty Directories
 *
 * This migration runs before the reorganize migrations to:
 * 1. Check Nx version is 22 or higher
 * 2. Reset Nx cache to ensure fresh project graph
 * 3. Clean up any existing empty directories that might block the migration flow
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
const child_process_1 = require("child_process");
/**
 * Check that Nx version is 22 or higher
 */
function checkNxVersion(tree) {
    devkit_1.logger.info('  Checking Nx version compatibility...');
    const pkg = (0, devkit_1.readJson)(tree, 'package.json');
    const nxVersion = pkg.devDependencies?.nx || pkg.dependencies?.nx;
    if (!nxVersion) {
        devkit_1.logger.error('❌ No Nx version found in package.json');
        throw new Error('No Nx version found in package.json. Please install Nx first.');
    }
    const majorVersion = parseInt(nxVersion.match(/\d+/)?.[0] ?? '0');
    if (majorVersion < 22) {
        const errorMessage = `❌ This migration requires Nx 22 or higher. Current version: ${nxVersion}. Please upgrade Nx first.`;
        devkit_1.logger.error(errorMessage);
        throw new Error(errorMessage);
    }
    devkit_1.logger.info(`  Nx version check passed (version: ${nxVersion})`);
}
/**
 * Reset Nx cache to ensure fresh project graph
 * This is important before moving projects, as Nx caches project locations
 */
function resetNxCache() {
    try {
        devkit_1.logger.info('  Resetting Nx cache...');
        (0, child_process_1.execSync)('npx nx reset', {
            stdio: 'pipe',
        });
        devkit_1.logger.info('  Nx cache reset successfully');
    }
    catch (error) {
        // Log but don't fail - cache reset is best effort
        devkit_1.logger.warn('  Could not reset Nx cache (this may be fine): ' + error);
    }
}
/**
 * Clean up empty directories in unisphere folder.
 * Also removes directories that only contain hidden files (like .DS_Store).
 */
function cleanupEmptyDirectories() {
    const foldersToClean = [
        'unisphere/packages',
        'unisphere/applications',
        'unisphere/runtimes',
    ];
    for (const folder of foldersToClean) {
        try {
            // First, remove common junk files that prevent directories from being "empty"
            (0, child_process_1.execSync)(`find ${folder} -name '.DS_Store' -delete 2>/dev/null || true`, {
                stdio: 'pipe',
            });
            // Then delete empty directories (depth-first, so nested empty dirs are handled)
            const result = (0, child_process_1.execSync)(`find ${folder} -type d -empty -delete -print 2>/dev/null || true`, {
                stdio: 'pipe',
                encoding: 'utf-8',
            });
            if (result && result.trim()) {
                const deleted = result.trim().split('\n').filter(Boolean);
                devkit_1.logger.info(`  Deleted ${deleted.length} empty directory(ies) in ${folder}`);
                for (const dir of deleted) {
                    devkit_1.logger.info(`    - ${dir}`);
                }
            }
        }
        catch (error) {
            // Log but don't fail - folder might not exist
            devkit_1.logger.warn(`  Could not clean ${folder}: ${error}`);
        }
    }
}
/**
 * Main migration function
 */
async function update(tree) {
    devkit_1.logger.info('');
    devkit_1.logger.info('========================================');
    devkit_1.logger.info('Pre-cleanup: Preparing for reorganization');
    devkit_1.logger.info('========================================');
    devkit_1.logger.info('');
    // Step 1: Check Nx version is 22 or higher
    checkNxVersion(tree);
    // Step 2: Reset Nx cache to ensure fresh project graph
    resetNxCache();
    // Step 3: Clean up empty directories
    devkit_1.logger.info('  Removing empty directories...');
    cleanupEmptyDirectories();
    devkit_1.logger.info('  Empty directories cleaned');
    devkit_1.logger.info('');
    devkit_1.logger.info('Pre-cleanup completed');
    devkit_1.logger.info('');
}
