// Seed skills table from frontend's SKILL_HIERARCHY definition
// Usage: from backend dir: npm run seed-skills

const fs = require('fs')
const path = require('path')
const vm = require('vm')
const Database = require('better-sqlite3')

function parseFrontendHierarchy() {
  const tsPath = path.join(process.cwd(), '..', 'frontend', 'src', 'data', 'skillCategories.ts')
  const src = fs.readFileSync(tsPath, 'utf8')
  // Remove interface declarations and LANGUAGE_LEVELS export, keep the array literal
  let code = src
    .replace(/export interface[\s\S]*?\n\}/g, '')
    .replace(/export const LANGUAGE_LEVELS[\s\S]*?\n\n/, '')
    .replace(/export const SKILL_HIERARCHY:[^=]*=/, 'module.exports =')

  const sandbox = { module: {}, exports: {} }
  vm.createContext(sandbox)
  vm.runInContext(code, sandbox)
  return sandbox.module.exports || sandbox.exports
}

function main() {
  const dbPath = path.join(process.cwd(), 'skillmate.dev.encrypted.db')
  const db = new Database(dbPath)
  try {
    const hierarchy = parseFrontendHierarchy()
    if (!Array.isArray(hierarchy)) {
      throw new Error('Parsed hierarchy is not an array')
    }

    const insert = db.prepare(`
      INSERT OR IGNORE INTO skills (id, name, category, description, expires_after)
      VALUES (?, ?, ?, ?, ?)
    `)

    let count = 0
    for (const cat of hierarchy) {
      for (const sub of (cat.subcategories || [])) {
        const categoryKey = `${cat.id}.${sub.id}`
        for (const sk of (sub.skills || [])) {
          const id = `${categoryKey}.${sk.id}`
          const name = sk.name
          const description = null
          const expires = cat.id === 'certifications' ? 36 : null
          const res = insert.run(id, name, categoryKey, description, expires)
          if (res.changes > 0) count++
        }
      }
    }

    console.log(`✅ Seed abgeschlossen. Neue Skills eingefügt: ${count}`)
  } catch (err) {
    console.error('❌ Seed fehlgeschlagen:', err)
    process.exitCode = 1
  } finally {
    db.close()
  }
}

main()

