/**
 * Copy SVG icons from FEUKOS source to public/signaturen/
 * Filters to German (_de) and universal (no _fr/_it suffix) files only
 */
const fs = require('fs')
const path = require('path')

const SOURCE_DIR = path.join(__dirname, '..', 'Signaturen', 'Markierungsmoglichkeiten', 'Markierungsmöglichkeiten Icons', 'SVG')
const OUTPUT_DIR = path.join(__dirname, '..', 'public', 'signaturen')

// Only German (_de) and universal (no _fr/_it suffix) files
function isRelevant(filename) {
  if (!filename.endsWith('.svg')) return false
  if (filename.match(/_fr\.svg$/i)) return false
  if (filename.match(/_it\.svg$/i)) return false
  return true
}

// Clean up name: remove _de/_DE suffix, replace underscores/hyphens with spaces
function cleanName(filename) {
  let name = filename.replace('.svg', '')
  name = name.replace(/_de$/i, '').replace(/_DE$/i, '').replace(/-de$/i, '')
  return name.replace(/[_-]/g, ' ').replace(/\s+/g, ' ').trim()
}

function copyIcons() {
  // Ensure output dir exists
  if (!fs.existsSync(OUTPUT_DIR)) {
    fs.mkdirSync(OUTPUT_DIR, { recursive: true })
  }

  // Clean old SVGs/PNGs from output dir
  const oldFiles = fs.readdirSync(OUTPUT_DIR).filter(f => f.endsWith('.svg') || f.endsWith('.png'))
  for (const f of oldFiles) {
    fs.unlinkSync(path.join(OUTPUT_DIR, f))
  }
  console.log(`🗑️  Removed ${oldFiles.length} old files from ${OUTPUT_DIR}`)

  const files = fs.readdirSync(SOURCE_DIR).filter(isRelevant).sort()
  console.log(`📂 Found ${files.length} relevant SVG files`)

  let copied = 0
  for (const file of files) {
    const inputPath = path.join(SOURCE_DIR, file)
    const outputPath = path.join(OUTPUT_DIR, file)

    try {
      fs.copyFileSync(inputPath, outputPath)
      copied++
    } catch (err) {
      console.error(`  ❌ Failed: ${file}:`, err.message)
    }
  }

  console.log(`\n🎉 Done! Copied ${copied}/${files.length} SVG icons to ${OUTPUT_DIR}`)

  // Generate a manifest file for the seed script
  const manifest = files.map(f => ({
    file: f,
    name: cleanName(f),
    originalFile: f,
  }))
  fs.writeFileSync(
    path.join(OUTPUT_DIR, 'manifest.json'),
    JSON.stringify(manifest, null, 2)
  )
  console.log(`📋 Manifest written with ${manifest.length} entries`)
}

copyIcons()
