import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const ICONS_DIR = path.resolve(__dirname, '../src/assets/icons')
const OUTPUT_FILE = path.resolve(__dirname, '../src/components/icons/icon-names.d.ts')

const readNames = () =>
  fs
    .readdirSync(ICONS_DIR)
    .filter((f) => f.endsWith('.svg'))
    .map((f) => f.replace(/\.svg$/, ''))
    .sort()

const buildContent = (names) => {
  const union = names.length > 0 ? names.map((n) => `  | '${n}'`).join('\n') : '  | never'
  return `// AUTO-GENERATED — do not edit by hand.
// Regenerated whenever src/assets/icons/*.svg changes (via scripts/vite-icon-names.js).

export type IconName =
${union}

export const iconNames: readonly IconName[]
`
}

const writeIfChanged = () => {
  const content = buildContent(readNames())
  const prev = fs.existsSync(OUTPUT_FILE) ? fs.readFileSync(OUTPUT_FILE, 'utf8') : ''
  if (prev !== content) fs.writeFileSync(OUTPUT_FILE, content)
}

export default function viteIconNames() {
  return {
    name: 'vite-icon-names',
    buildStart() {
      writeIfChanged()
    },
    configureServer(server) {
      writeIfChanged()
      server.watcher.add(path.join(ICONS_DIR, '*.svg'))
      const handler = (file) => {
        if (file.startsWith(ICONS_DIR) && file.endsWith('.svg')) writeIfChanged()
      }
      server.watcher.on('add', handler)
      server.watcher.on('unlink', handler)
    },
  }
}

export { writeIfChanged as generateIconNames }
