"use strict";
/* eslint-disable */
const fs = require('fs');
const path = require('path');
const ICONS_FILE = path.join(__dirname, '../baseIcons/icons.ts');
const BASE_ICONS_DIR = path.join(__dirname, '../baseIcons');
const CONSTS_FILE = path.join(__dirname, '../consts.ts');
const TYPES_FILE = path.join(__dirname, '../baseIcons/types.ts');
// Configuration: which folders to include/exclude
const FOLDER_CONFIG = {
    include: ['conc', 'brand', 'ui'], // only these folders exist
    exclude: [], // folders to skip/comment out
    commentOut: [] // folders to comment out instead of delete
};
function scanFolderForIcons(folderPath, folderName) {
    if (!fs.existsSync(folderPath)) {
        console.log(`⚠️  Folder not found: ${folderPath}`);
        return [];
    }
    const files = fs.readdirSync(folderPath)
        .filter(file => file.endsWith('.ts') && file !== 'index.ts' && file !== 'types.ts')
        .map(file => {
        const iconName = file.replace('.ts', '');
        return {
            name: iconName,
            path: `./${folderName}/${iconName}`,
            folder: folderName
        };
    });
    return files;
}
function generateExportLine(icon, shouldComment = false) {
    const prefix = shouldComment ? '// ' : '';
    return `${prefix}export { default as ${icon.name} } from '${icon.path}'`;
}
function updateIconsFile() {
    try {
        console.log('🚀 Updating icons.ts exports...');
        // Scan all configured folders, excluding the ones in exclude list
        const allIcons = [];
        FOLDER_CONFIG.include
            .filter(folderName => !FOLDER_CONFIG.exclude.includes(folderName))
            .forEach(folderName => {
            const folderPath = path.join(BASE_ICONS_DIR, folderName);
            const icons = scanFolderForIcons(folderPath, folderName);
            allIcons.push(...icons);
            console.log(`✅ Found ${icons.length} icons in ${folderName}/`);
        });
        // Show excluded folders
        if (FOLDER_CONFIG.exclude.length > 0) {
            console.log(`❌ Excluded folders: ${FOLDER_CONFIG.exclude.join(', ')}`);
        }
        // Group icons by folder
        const iconsByFolder = {};
        allIcons.forEach(icon => {
            if (!iconsByFolder[icon.folder]) {
                iconsByFolder[icon.folder] = [];
            }
            iconsByFolder[icon.folder].push(icon);
        });
        // Sort icons within each folder
        Object.keys(iconsByFolder).forEach(folder => {
            iconsByFolder[folder].sort((a, b) => a.name.localeCompare(b.name));
        });
        // Generate export lines
        const exportLines = [];
        // Process each folder in order (only existing folders)
        const folderOrder = ['conc', 'brand', 'ui'];
        folderOrder
            .filter(folderName => !FOLDER_CONFIG.exclude.includes(folderName))
            .forEach(folderName => {
            const icons = iconsByFolder[folderName] || [];
            const shouldComment = FOLDER_CONFIG.commentOut.includes(folderName);
            if (icons.length > 0) {
                // Add folder comment with icon count
                exportLines.push('');
                exportLines.push(`// ${folderName.toUpperCase()} icons (${icons.length} icons)`);
                // Add exports
                icons.forEach(icon => {
                    exportLines.push(generateExportLine(icon, shouldComment));
                });
            }
        });
        // Create the file content
        const fileContent = `// This file is auto-generated. Do not edit manually.
// Run 'node scripts/update-icons-exports.js' to update.

${exportLines.join('\n')}
`;
        // Write the file
        fs.writeFileSync(ICONS_FILE, fileContent, 'utf8');
        console.log('✅ Successfully updated icons.ts');
        console.log(`📊 Total icons processed: ${allIcons.length}`);
        // Summary by folder
        Object.keys(iconsByFolder).forEach(folder => {
            const count = iconsByFolder[folder].length;
            const status = FOLDER_CONFIG.commentOut.includes(folder) ? '(commented)' : '(active)';
            console.log(`   ${folder}: ${count} icons ${status}`);
        });
        return allIcons; // Return for use in types generation
    }
    catch (error) {
        console.error('❌ Error updating icons.ts:', error.message);
        return [];
    }
}
function findAndFixConstsImports() {
    try {
        console.log('🔍 Scanning for moved/renamed icons in consts.ts...');
        if (!fs.existsSync(CONSTS_FILE)) {
            console.log('⚠️  consts.ts not found');
            return;
        }
        const content = fs.readFileSync(CONSTS_FILE, 'utf8');
        let updatedContent = content;
        let fixedCount = 0;
        // Extract all import statements
        const importRegex = /import\s+(\w+)\s+from\s+'\.\/baseIcons\/(\w+)\/(\w+)'/g;
        const imports = [];
        let match;
        while ((match = importRegex.exec(content)) !== null) {
            imports.push({
                fullMatch: match[0],
                variable: match[1],
                folder: match[2],
                filename: match[3],
                line: match[0]
            });
        }
        console.log(`📋 Found ${imports.length} imports to check`);
        // Check each import and try to find the correct path
        imports.forEach(importInfo => {
            const currentPath = path.join(BASE_ICONS_DIR, importInfo.folder, `${importInfo.filename}.ts`);
            if (!fs.existsSync(currentPath)) {
                console.log(`❌ Missing: ${importInfo.folder}/${importInfo.filename}.ts`);
                // Search for the file in all folders
                const newLocation = findIconInAllFolders(importInfo.filename, importInfo.variable);
                if (newLocation) {
                    console.log(`✅ Found at: ${newLocation.folder}/${newLocation.filename}.ts`);
                    // Replace the import statement
                    const oldImport = importInfo.fullMatch;
                    const newImport = `import ${importInfo.variable} from './baseIcons/${newLocation.folder}/${newLocation.filename}'`;
                    updatedContent = updatedContent.replace(oldImport, newImport);
                    fixedCount++;
                }
                else {
                    console.log(`❌ Could not find ${importInfo.filename} anywhere`);
                }
            }
            else {
                console.log(`✅ OK: ${importInfo.folder}/${importInfo.filename}.ts`);
            }
        });
        // Write the updated content if changes were made
        if (fixedCount > 0) {
            fs.writeFileSync(CONSTS_FILE, updatedContent, 'utf8');
            console.log(`🎉 Fixed ${fixedCount} import paths in consts.ts`);
        }
        else {
            console.log('✅ All imports are already correct');
        }
    }
    catch (error) {
        console.error('❌ Error fixing consts imports:', error.message);
    }
}
// UPDATED FUNCTION: Fix types.ts file in baseIcons folder
function updateTypesFile() {
    try {
        console.log('🔧 Updating baseIcons/types.ts...');
        // Ensure baseIcons directory exists
        if (!fs.existsSync(BASE_ICONS_DIR)) {
            console.error(`❌ BaseIcons directory not found: ${BASE_ICONS_DIR}`);
            return;
        }
        if (!fs.existsSync(TYPES_FILE)) {
            console.log('⚠️  types.ts not found in baseIcons/, creating new file...');
        }
        // Scan all configured folders for icon names
        const allIconNames = [];
        const iconDetails = []; // Store more details for debugging
        FOLDER_CONFIG.include
            .filter(folderName => !FOLDER_CONFIG.exclude.includes(folderName))
            .forEach(folderName => {
            const folderPath = path.join(BASE_ICONS_DIR, folderName);
            if (!fs.existsSync(folderPath)) {
                console.log(`⚠️  Folder not found: ${folderPath}`);
                return;
            }
            const files = fs.readdirSync(folderPath)
                .filter(file => file.endsWith('.ts') && file !== 'index.ts' && file !== 'types.ts')
                .map(file => {
                const iconName = file.replace('.ts', '');
                iconDetails.push({ name: iconName, folder: folderName, file });
                return iconName;
            });
            allIconNames.push(...files);
            console.log(`📁 Scanned ${folderName}/ - found ${files.length} icon files`);
        });
        if (allIconNames.length === 0) {
            console.log('⚠️  No icon files found in any folder');
            return;
        }
        // Sort icon names alphabetically
        allIconNames.sort();
        console.log(`📊 Total icons found: ${allIconNames.length}`);
        // Generate the BaseIcon type
        const iconTypeLines = [];
        iconTypeLines.push('export type BaseIcon =');
        // Group icons by folder for better organization
        const iconsByFolder = {};
        allIconNames.forEach(iconName => {
            // Check which folder the icon actually belongs to
            let folder = 'other';
            for (const folderName of FOLDER_CONFIG.include) {
                const iconPath = path.join(BASE_ICONS_DIR, folderName, `${iconName}.ts`);
                if (fs.existsSync(iconPath)) {
                    folder = folderName;
                    break;
                }
            }
            if (!iconsByFolder[folder]) {
                iconsByFolder[folder] = [];
            }
            iconsByFolder[folder].push(iconName);
        });
        // Sort within each folder
        Object.keys(iconsByFolder).forEach(folder => {
            iconsByFolder[folder].sort();
        });
        // Generate type union with organized comments
        const folderOrder = ['brand', 'ui', 'conc'];
        let isFirstEntry = true;
        let totalIconsProcessed = 0;
        folderOrder.forEach(folder => {
            const icons = iconsByFolder[folder];
            if (!icons || icons.length === 0)
                return;
            // Add folder comment with icon count
            iconTypeLines.push(`  // ${folder.toUpperCase()} icons (${icons.length} icons)`);
            icons.forEach((iconName) => {
                const prefix = isFirstEntry ? '  | ' : '  | ';
                iconTypeLines.push(`${prefix}'${iconName}'`);
                isFirstEntry = false;
                totalIconsProcessed++;
            });
            // Add empty line between folders (except for last with icons)
            const remainingFolders = folderOrder.slice(folderOrder.indexOf(folder) + 1);
            const hasMoreFolders = remainingFolders.some(f => { var _a; return ((_a = iconsByFolder[f]) === null || _a === void 0 ? void 0 : _a.length) > 0; });
            if (hasMoreFolders) {
                iconTypeLines.push('');
            }
        });
        // Handle any icons in 'other' folder
        if (iconsByFolder.other && iconsByFolder.other.length > 0) {
            iconTypeLines.push('');
            iconTypeLines.push(`  // OTHER icons (${iconsByFolder.other.length} icons)`);
            iconsByFolder.other.forEach((iconName) => {
                const prefix = isFirstEntry ? '  | ' : '  | ';
                iconTypeLines.push(`${prefix}'${iconName}'`);
                isFirstEntry = false;
                totalIconsProcessed++;
            });
        }
        // Create the complete file content
        const header = `// This file is auto-generated. Do not edit manually.
// Run 'node scripts/update-icons-exports.js --fix-types' to update.
// Generated from baseIcons folders: ${FOLDER_CONFIG.include.join(', ')}
// Total icons: ${totalIconsProcessed}

`;
        const iconTypeContent = iconTypeLines.join('\n');
        // Add BaseIcon type and default export
        const additionalTypes = `

// Default export for convenience
export default BaseIcon
`;
        const fullContent = header + iconTypeContent + additionalTypes;
        // Write the file
        fs.writeFileSync(TYPES_FILE, fullContent, 'utf8');
        console.log('✅ Successfully updated baseIcons/types.ts');
        console.log(`📊 Generated IconName type with ${totalIconsProcessed} icons`);
        // Summary by folder
        Object.keys(iconsByFolder).forEach(folder => {
            const count = iconsByFolder[folder].length;
            console.log(`   ${folder}: ${count} icons`);
        });
        console.log(`💾 Types file written to: ${TYPES_FILE}`);
    }
    catch (error) {
        console.error('❌ Error updating types.ts:', error.message);
        console.error('Stack trace:', error.stack);
    }
}
// Helper function to search for an icon in all folders
function findIconInAllFolders(originalFilename, variableName) {
    const searchFolders = ['conc', 'brand', 'ui']; // Only existing folders
    for (const folder of searchFolders) {
        const folderPath = path.join(BASE_ICONS_DIR, folder);
        if (!fs.existsSync(folderPath))
            continue;
        const files = fs.readdirSync(folderPath)
            .filter(file => file.endsWith('.ts') && file !== 'types.ts')
            .map(file => file.replace('.ts', ''));
        // Try exact filename match first
        if (files.includes(originalFilename)) {
            return { folder, filename: originalFilename };
        }
        // Try to find by variable name
        if (files.includes(variableName)) {
            return { folder, filename: variableName };
        }
        // Try to find by checking file contents for matching name or oldName
        for (const filename of files) {
            const filePath = path.join(folderPath, `${filename}.ts`);
            try {
                const fileContent = fs.readFileSync(filePath, 'utf8');
                // Check if the file has the right name or oldName
                const nameMatch = fileContent.match(/name:\s*'([^']+)'/);
                const oldNameMatch = fileContent.match(/oldName:\s*'([^']+)'/);
                if (nameMatch && nameMatch[1] === variableName) {
                    return { folder, filename };
                }
                if (oldNameMatch && oldNameMatch[1] === variableName) {
                    return { folder, filename };
                }
                if (oldNameMatch && oldNameMatch[1] === originalFilename) {
                    return { folder, filename };
                }
            }
            catch (err) {
                // Skip files that can't be read
                continue;
            }
        }
    }
    return null;
}
function fixConstsOnly() {
    findAndFixConstsImports();
}
function fixTypesOnly() {
    updateTypesFile();
}
function runAll() {
    const allIcons = updateIconsFile();
    updateTypesFile(); // Always run types update, even if no icons found
}
// Command line options
const args = process.argv.slice(2);
if (args.includes('--help')) {
    console.log(`
Usage: node scripts/update-icons-exports.js [options]

Options:
  --include <folders>   Comma-separated list of folders to include (available: conc,brand,ui)
  --exclude <folders>   Comma-separated list of folders to exclude
  --comment <folders>   Comma-separated list of folders to comment out
  --fix-consts         Only fix import paths in consts.ts (don't update icons.ts)
  --fix-types          Only update the IconName type in baseIcons/types.ts
  --all                Update icons.ts and types.ts (default behavior)
  --help               Show this help message

Files updated:
  - baseIcons/icons.ts       (icon exports)
  - baseIcons/types.ts       (TypeScript types)
  - consts.ts               (import fixes)

Examples:
  node scripts/update-icons-exports.js
  node scripts/update-icons-exports.js --fix-consts
  node scripts/update-icons-exports.js --fix-types
  node scripts/update-icons-exports.js --include brand,ui
  node scripts/update-icons-exports.js --all --exclude conc
`);
    process.exit(0);
}
// Parse command line arguments
const includeIndex = args.indexOf('--include');
if (includeIndex !== -1 && args[includeIndex + 1]) {
    const requestedFolders = args[includeIndex + 1].split(',');
    // Only include folders that actually exist
    FOLDER_CONFIG.include = requestedFolders.filter(folder => ['conc', 'brand', 'ui'].includes(folder));
    if (FOLDER_CONFIG.include.length === 0) {
        console.error('❌ No valid folders specified. Available folders: conc, brand, ui');
        process.exit(1);
    }
}
const excludeIndex = args.indexOf('--exclude');
if (excludeIndex !== -1 && args[excludeIndex + 1]) {
    FOLDER_CONFIG.exclude = args[excludeIndex + 1].split(',');
    // Remove excluded folders from include list
    FOLDER_CONFIG.include = FOLDER_CONFIG.include.filter(folder => !FOLDER_CONFIG.exclude.includes(folder));
}
const commentIndex = args.indexOf('--comment');
if (commentIndex !== -1 && args[commentIndex + 1]) {
    FOLDER_CONFIG.commentOut = args[commentIndex + 1].split(',');
}
// Add command line option to only fix consts
if (args.includes('--fix-consts')) {
    fixConstsOnly();
    process.exit(0);
}
// Add command line option to only fix types
if (args.includes('--fix-types')) {
    fixTypesOnly();
    process.exit(0);
}
// Run all updates (default behavior)
if (args.includes('--all') || args.length === 0 ||
    (args.length > 0 && !args.some(arg => arg.startsWith('--fix')))) {
    runAll();
}
else {
    // Just run the icons update if no specific fix flag is provided
    updateIconsFile();
}
//# sourceMappingURL=update-icons-exports.js.map