/* eslint-disable */
/**
 * Script to regenerate the icons.ts file from existing icon files
 * This will fix any duplicate exports or other issues in the auto-generated 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',
}

main()

async function main() {
  try {
    console.log('🚀 Regenerating icons.ts file...')

    const allIconNames = await getAllIconNames()

    if (allIconNames.length === 0) {
      console.error('❌ No icon files found')
      return
    }

    await updateIconsList(allIconNames)

    console.log('✅ Successfully regenerated icons.ts')
  } catch (error) {
    console.error('❌ Error during regeneration:', error.message)
    process.exit(1)
  }
}

/** Gets all icon names from the library folder structure */
async function getAllIconNames() {
  try {
    const items = await 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 = await 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 []
  }
}

/** Updates the icons.ts file with all icon exports organized by prefix */
async function updateIconsList(iconNames) {
  try {
    if (iconNames.length === 0) {
      console.log('⚠️  No icons to export')
      return
    }

    // Group icons by their normalized prefix
    const iconsByPrefix = 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
    }, {})

    // Sort prefixes for consistent output (base, brand, conc, ui)
    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() // Sort icons within each group
      const exports = icons.map(iconName => `export { default as ${iconName} } from './${prefix}/${iconName}'`)

      return [`// ${prefix.toUpperCase()} icons (${icons.length})`, ...exports].join('\n')
    })

    const iconsFileContent =
      [
        '// This file is auto-generated. Do not edit manually.',
        '// Run the icon transformation script to update.',
        '',
        ...exportSections,
      ].join('\n') + '\n'

    const iconsFilePath = path.join(libraryIconsPath, 'icons.ts')

    // Create backup
    const backupPath = iconsFilePath + '.backup'
    if (await fs.pathExists(iconsFilePath)) {
      await fs.copy(iconsFilePath, backupPath)
      console.log(`📋 Created backup: ${backupPath}`)
    }

    await fs.writeFile(iconsFilePath, iconsFileContent)

    console.log(`✅ Updated icons.ts with ${iconNames.length} exports across ${sortedPrefixes.length} categories`)
    sortedPrefixes.forEach(prefix => {
      console.log(`   ${prefix}: ${iconsByPrefix[prefix].length} icons`)
    })
  } catch (error) {
    console.error('❌ Error updating icons list:', error.message)
    throw error
  }
}

/** Optimized prefix normalization with constant time lookup */
function normalizeIconPrefix(prefix) {
  return PREFIX_MAP[prefix] || (prefix.startsWith('ui') ? 'ui' : prefix)
}
