"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
/* eslint-disable */
/**
 * Enhanced script to regenerate the icons.ts file from existing icon files
 * Can be run with --check flag to validate the current file
 */
const fs = require('fs-extra');
const path = require('path');
const libraryIconsPath = path.join(__dirname, '../baseIcons');
// Map for prefix normalization
const PREFIX_MAP = {
    con: 'conc', // "con" is a reserved dir name in windows
    bas: 'base',
    bra: 'brand',
};
// Check command line arguments
const args = process.argv.slice(2);
const isCheckMode = args.includes('--check');
const isDryRun = args.includes('--dry-run');
main();
function main() {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            if (isCheckMode) {
                console.log('🔍 Checking icons.ts file...');
                yield checkIconsFile();
            }
            else {
                console.log('🚀 Regenerating icons.ts file...');
                yield regenerateIconsFile();
            }
        }
        catch (error) {
            console.error('❌ Error:', error.message);
            process.exit(1);
        }
    });
}
function checkIconsFile() {
    return __awaiter(this, void 0, void 0, function* () {
        const allIconNames = yield getAllIconNames();
        const expectedContent = generateIconsContent(allIconNames);
        const iconsFilePath = path.join(libraryIconsPath, 'icons.ts');
        if (!(yield fs.pathExists(iconsFilePath))) {
            console.error('❌ icons.ts file does not exist');
            return;
        }
        const currentContent = yield fs.readFile(iconsFilePath, 'utf8');
        if (currentContent.trim() === expectedContent.trim()) {
            console.log('✅ icons.ts file is up to date');
        }
        else {
            console.log('⚠️  icons.ts file needs regeneration');
            console.log(`Current file has ${currentContent.split('\\n').length} lines`);
            console.log(`Expected file should have ${expectedContent.split('\\n').length} lines`);
        }
    });
}
function regenerateIconsFile() {
    return __awaiter(this, void 0, void 0, function* () {
        const allIconNames = yield getAllIconNames();
        if (allIconNames.length === 0) {
            console.error('❌ No icon files found');
            return;
        }
        const newContent = generateIconsContent(allIconNames);
        const iconsFilePath = path.join(libraryIconsPath, 'icons.ts');
        if (isDryRun) {
            console.log('📋 DRY RUN - Content to be written:');
            console.log(newContent.split('\\n').slice(0, 10).join('\\n') + '\\n...');
            console.log(`Total lines: ${newContent.split('\\n').length}`);
            return;
        }
        // Create backup
        if (yield fs.pathExists(iconsFilePath)) {
            const backupPath = iconsFilePath + '.backup';
            yield fs.copy(iconsFilePath, backupPath);
            console.log(`📋 Created backup: ${path.basename(backupPath)}`);
        }
        yield fs.writeFile(iconsFilePath, newContent);
        console.log('✅ Successfully regenerated icons.ts');
        // Show summary
        const iconsByPrefix = groupIconsByPrefix(allIconNames);
        const sortedPrefixes = Object.keys(iconsByPrefix).sort((a, b) => {
            const order = { base: 1, brand: 2, conc: 3, ui: 4 };
            return (order[a] || 999) - (order[b] || 999);
        });
        console.log(`📊 Summary: ${allIconNames.length} exports across ${sortedPrefixes.length} categories`);
        sortedPrefixes.forEach(prefix => {
            console.log(`   ${prefix}: ${iconsByPrefix[prefix].length} icons`);
        });
    });
}
function generateIconsContent(iconNames) {
    const iconsByPrefix = groupIconsByPrefix(iconNames);
    // Sort prefixes for consistent output
    const sortedPrefixes = Object.keys(iconsByPrefix).sort((a, b) => {
        const order = { base: 1, brand: 2, conc: 3, ui: 4 };
        return (order[a] || 999) - (order[b] || 999);
    });
    // Generate exports grouped by prefix
    const exportSections = sortedPrefixes.map(prefix => {
        const icons = iconsByPrefix[prefix].sort();
        const exports = icons.map(iconName => `export { default as ${iconName} } from './${prefix}/${iconName}'`);
        return [`// ${prefix.toUpperCase()} icons (${icons.length})`, ...exports].join('\\n');
    });
    return ([
        '// This file is auto-generated. Do not edit manually.',
        '// Run the icon transformation script to update.',
        '',
        ...exportSections,
    ].join('\\n') + '\\n');
}
function groupIconsByPrefix(iconNames) {
    return iconNames.reduce((groups, iconName) => {
        const filePrefix = iconName.slice(0, 3);
        const folder = normalizeIconPrefix(filePrefix);
        if (!groups[folder]) {
            groups[folder] = [];
        }
        groups[folder].push(iconName);
        return groups;
    }, {});
}
/** Gets all icon names from the library folder structure */
function getAllIconNames() {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const items = yield fs.readdir(libraryIconsPath, { withFileTypes: true });
            // Get only directories (base, brand, conc, ui)
            const folders = items.filter(item => item.isDirectory()).map(item => item.name);
            if (folders.length === 0) {
                console.log('⚠️  No icon folders found');
                return [];
            }
            console.log(`📁 Found folders: ${folders.join(', ')}`);
            // Read all .ts files from all folders
            const allIconNames = [];
            for (const folder of folders) {
                const folderPath = path.join(libraryIconsPath, folder);
                const files = yield fs.readdir(folderPath);
                const tsFiles = files.filter(file => file.endsWith('.ts')).map(filename => filename.replace('.ts', ''));
                console.log(`   ${folder}: ${tsFiles.length} files`);
                allIconNames.push(...tsFiles);
            }
            console.log(`📋 Total icons found: ${allIconNames.length}`);
            return allIconNames;
        }
        catch (error) {
            console.error('❌ Error reading icon names:', error.message);
            return [];
        }
    });
}
/** Optimized prefix normalization with constant time lookup */
function normalizeIconPrefix(prefix) {
    return PREFIX_MAP[prefix] || (prefix.startsWith('ui') ? 'ui' : prefix);
}
//# sourceMappingURL=update-icons-exports.js.map