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

const rootDir = process.cwd()
const aiSummaryPath = path.join(rootDir, 'docs/ai-summary.json')
const outDir = path.join(rootDir, 'docs/composables-md')

if (!fs.existsSync(aiSummaryPath)) {
  console.error('docs/ai-summary.json not found. Run: npm run docs:ai:summary')
  process.exit(1)
}

const ai = JSON.parse(fs.readFileSync(aiSummaryPath, 'utf8'))
const composables = ai.composables || []

function safeName(filePath) {
  return filePath
    .replace(/^src\/runtime\/composables\//, '')
    .replace(/\//g, '__')
    .replace(/\.ts$/, '')
}

function mdEscape(str) {
  return String(str ?? '').replace(/\|/g, '\\|')
}

fs.mkdirSync(outDir, { recursive: true })

const index = []
index.push('# Composables (Markdown)')
index.push('')
index.push(`Generated at: ${ai.generatedAt}`)
index.push('')
index.push('| Composable | Source |')
index.push('| ---------- | ------ |')

for (const c of composables) {
  const fileBase = safeName(c.path)
  const outFile = path.join(outDir, `${fileBase}.md`)
  const content = []

  content.push(`# ${fileBase}`)
  content.push('')
  content.push(`- Source: \`${c.path}\``)
  content.push(`- Summary: ${c.summary || ''}`)
  content.push('')

  const exp = c.exports || {}
  const functions = exp.functions || []
  const interfaces = exp.interfaces || []
  const types = exp.types || []
  const consts = exp.constants || []
  const enums = exp.enums || []

  content.push('## Exported Functions')
  content.push('')
  if (functions.length) {
    content.push('| Name | Signature | Returns |')
    content.push('| ---- | --------- | ------- |')
    for (const fn of functions) {
      content.push(`| \`${mdEscape(fn.name)}\` | \`${mdEscape(fn.signature || '')}\` | \`${mdEscape(fn.returns || '')}\` |`)
    }
  } else {
    content.push('No exported functions.')
  }
  content.push('')

  content.push('## Exported Interfaces')
  content.push('')
  if (interfaces.length) {
    for (const i of interfaces) {
      content.push(`### \`${i.name}\``)
      content.push('')
      content.push('```ts')
      content.push(i.shape || '')
      content.push('```')
      content.push('')
    }
  } else {
    content.push('No exported interfaces.')
    content.push('')
  }

  content.push('## Exported Types')
  content.push('')
  if (types.length) {
    content.push('| Name | Definition |')
    content.push('| ---- | ---------- |')
    for (const t of types) {
      content.push(`| \`${mdEscape(t.name)}\` | \`${mdEscape(t.definition || '')}\` |`)
    }
  } else {
    content.push('No exported types.')
  }
  content.push('')

  content.push('## Exported Constants')
  content.push('')
  if (consts.length) {
    content.push('| Name | Type |')
    content.push('| ---- | ---- |')
    for (const k of consts) {
      content.push(`| \`${mdEscape(k.name)}\` | \`${mdEscape(k.type || '')}\` |`)
    }
  } else {
    content.push('No exported constants.')
  }
  content.push('')

  content.push('## Exported Enums')
  content.push('')
  if (enums.length) {
    for (const e of enums) {
      content.push(`### \`${e.name}\``)
      content.push('')
      for (const m of e.members || []) content.push(`- \`${m}\``)
      content.push('')
    }
  } else {
    content.push('No exported enums.')
    content.push('')
  }

  fs.writeFileSync(outFile, content.join('\n'))
  index.push(`| [\`${fileBase}\`](${fileBase}.md) | \`${c.path}\` |`)
}

fs.writeFileSync(path.join(outDir, 'README.md'), index.join('\n'))
console.log(`Generated markdown docs for ${composables.length} composables at docs/composables-md`)
