import fs from 'node:fs'
import path from 'node:path'

const root = process.cwd()
const sourceRoot = path.join(root, 'apps/web/src/modules')
const out = path.join(root, 'apps/web/src/registry/screens.generated.ts')

function walk(dir) {
  return fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
    const full = path.join(dir, entry.name)
    return entry.isDirectory() ? walk(full) : [full]
  })
}

const entries = []
for (const file of walk(sourceRoot).filter(f => /definition\.ts$/.test(f))) {
  const text = fs.readFileSync(file, 'utf8')
  const match = text.match(/export\s+const\s+(\w+)\s*=\s*defineKbxScreen\s*\(\s*\{/)
  if (!match) continue
  const body = text.slice(match.index ?? 0)
  const id = body.match(/\bid:\s*['"]([^'"]+)['"]/)?.[1]
  if (!id) continue
  let rel = path.relative(path.dirname(out), file).replaceAll('\\', '/')
  if (!rel.startsWith('.')) rel = './' + rel
  rel = rel.replace(/\.ts$/, '')
  entries.push({ id, exportName: match[1], importPath: rel })
}

entries.sort((a, b) => a.id.localeCompare(b.id))
const imports = entries.map((entry, i) => `import { ${entry.exportName} as screen${i} } from '${entry.importPath}'`).join('\n')
const list = entries.map((_, i) => `  screen${i},`).join('\n')
const output = `// AUTO-GENERATED by scripts/generate-app-screen-registry.mjs. Do not edit.\n${imports}\n\nexport const generatedScreens = [\n${list}\n] as const\n`
fs.writeFileSync(out, output)
console.log(`generated app screen registry with ${entries.length} screens`)
