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

interface RegistryComponent {
  type?: string
  name?: string
  export?: string
}

interface RegistryData {
  components?: RegistryComponent[]
}

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootDir = path.resolve(__dirname, '..')
const registryPath = path.join(rootDir, 'json-components-registry.json')
const outputPath = path.join(rootDir, 'src/types/json-ui-component-types.ts')

const registryData = JSON.parse(fs.readFileSync(registryPath, 'utf8')) as RegistryData
const components = registryData.components ?? []

const seen = new Set<string>()
const componentTypes = components.flatMap((component) => {
  const typeName = component.type ?? component.name ?? component.export
  if (!typeName || typeof typeName !== 'string') {
    throw new Error('Registry component is missing a valid type/name/export entry.')
  }
  if (seen.has(typeName)) {
    return []
  }
  seen.add(typeName)
  return [typeName]
})

const lines = [
  '// This file is auto-generated by scripts/generate-json-ui-component-types.ts.',
  '// Do not edit this file directly.',
  '',
  'export const jsonUIComponentTypes = [',
  ...componentTypes.map((typeName) => `  ${JSON.stringify(typeName)},`),
  '] as const',
  '',
  'export type JSONUIComponentType = typeof jsonUIComponentTypes[number]',
  '',
]

fs.writeFileSync(outputPath, `${lines.join('\n')}`)

console.log(`✅ Wrote ${componentTypes.length} component types to ${outputPath}`)
