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

const root = path.resolve(process.argv[process.argv.indexOf('--root') + 1] ?? 'frontend')
const featureRoot = path.join(root, 'src', 'features')
const indexPath = path.join(root, 'src', 'shared', 'ui', 'components', 'index.ts')
const failures = []
const files = []
function walk(directory) {
  if (!fs.existsSync(directory)) return
  for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
    const file = path.join(directory, entry.name)
    if (entry.isDirectory()) walk(file)
    else if (entry.name.endsWith('.vue')) files.push(file)
  }
}
walk(featureRoot)
const exported = new Set([...fs.readFileSync(indexPath, 'utf8').matchAll(/export\s+\{\s*default\s+as\s+(Ks\w+)/g)].map(match => match[1]))
const commonAttributes = new Set(['class', 'style', 'id', 'title', 'role', 'tabindex', 'key', 'ref', 'aria-label', 'aria-describedby', 'aria-live', 'data-testid'])
const componentProps = new Map()
for (const name of exported) {
  const componentPath = path.join(root, 'src', 'shared', 'ui', 'components', `${name}.vue`)
  if (!fs.existsSync(componentPath)) continue
  const source = fs.readFileSync(componentPath, 'utf8')
  const propsBlock = source.match(/defineProps\s*<\s*\{([\s\S]*?)\}\s*>/)?.[1] ?? ''
  componentProps.set(name, new Set([...propsBlock.matchAll(/([A-Za-z_$][\w$]*)\s*\??\s*:/g)].map(match => match[1])))
}
for (const file of files) {
  const source = fs.readFileSync(file, 'utf8')
  for (const match of source.matchAll(/<\/(K(?:s|bx)\w+)|<(K(?:s|bx)\w+)(?=[\s>])/g)) {
    const name = match[1] ?? match[2]
    if (!exported.has(name)) failures.push(`${path.relative(process.cwd(), file).replaceAll('\\', '/')}: unknown KBX component ${name}`)
    else {
      const tagStart = match.index + match[0].length
      const tagEnd = source.indexOf('>', tagStart)
      const tag = source.slice(tagStart, tagEnd < 0 ? source.length : tagEnd)
      const props = componentProps.get(name) ?? new Set()
      for (const attr of tag.matchAll(/(?:^|\s)(?::|v-bind:)?([A-Za-z][\w-]*)(?=\s*=)/g)) {
        const prop = attr[1]
        if (commonAttributes.has(prop) || prop.startsWith('v-') || prop.startsWith('aria-') || prop.startsWith('data-') || ['if','else','else-if','for','show','model','on','slot'].includes(prop)) continue
        const camel = prop.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
        if (!props.has(camel)) failures.push(`${path.relative(process.cwd(), file).replaceAll('\\', '/')}: unknown prop ${prop} on ${name}`)
      }
    }
  }
  if (/(?:primevue(?:\/|$)|ag-grid(?:-vue3)?(?:\/|$))/.test(source)) failures.push(`${path.relative(process.cwd(), file).replaceAll('\\', '/')}: vendor import in AI-scan scope`)
}
console.log(`KBX_AI_COMPONENTS files=${files.length} known=${exported.size} failures=${failures.length}`)
for (const failure of failures) console.log(`FAIL ${failure}`)
process.exitCode = failures.length ? 1 : 0
