#!/usr/bin/env node

import { promises as fs } from 'node:fs'
import path from 'node:path'

const ROOT = process.cwd()
const DOCS_SOURCE = path.resolve(ROOT, '../docs')
const CONTENT_TARGET = path.resolve(ROOT, 'content')

async function ensureDir(dirPath) {
  await fs.mkdir(dirPath, { recursive: true })
}

async function clearDir(dirPath) {
  await fs.rm(dirPath, { recursive: true, force: true })
  await ensureDir(dirPath)
}

async function walk(dir) {
  const entries = await fs.readdir(dir, { withFileTypes: true })
  const out = []
  for (const entry of entries) {
    const full = path.join(dir, entry.name)
    if (entry.isDirectory()) {
      out.push(...(await walk(full)))
    } else if (entry.isFile() && entry.name.endsWith('.md')) {
      out.push(full)
    }
  }
  return out
}

function toPosix(p) {
  return p.split(path.sep).join('/')
}

async function main() {
  await clearDir(CONTENT_TARGET)
  const files = await walk(DOCS_SOURCE)

  for (const file of files) {
    const rel = toPosix(path.relative(DOCS_SOURCE, file))
    let targetRel = rel

    if (rel === 'README.md') {
      targetRel = 'index.md'
    } else if (rel.endsWith('/README.md')) {
      targetRel = `${rel.slice(0, -'/README.md'.length)}/index.md`
    }

    const target = path.join(CONTENT_TARGET, targetRel)
    await ensureDir(path.dirname(target))
    await fs.copyFile(file, target)
  }

  console.log(`Nuxt-Content Synchronisierung abgeschlossen: ${files.length} Dateien`) 
}

main().catch((err) => {
  console.error('Fehler bei der Content-Synchronisierung', err)
  process.exit(1)
})
