import fs from 'fs/promises'
import path from 'path'
import { randomUUID } from 'crypto'

const allowed = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg'])

const getDataRoot = () => {
  const cwd = process.cwd()
  return cwd.endsWith('.output') ? `${cwd}/../server/data` : `${cwd}/server/data`
}

const DATA_ROOT = getDataRoot()
const GALERIE_DIR = `${DATA_ROOT}/galerie`
const GALERIE_METADATA = `${DATA_ROOT}/galerie-metadata.json`
const PUBLIC_GALERIE_DIR = path.join(process.cwd(), 'public', 'galerie')

function titleFromFilename(filename) {
  const nameWithoutExt = path.parse(filename).name
  return nameWithoutExt.replace(/[-_]/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
}

async function readJsonArray(file) {
  try {
    const data = await fs.readFile(file, 'utf-8')
    const parsed = JSON.parse(data)
    return Array.isArray(parsed) ? parsed : []
  } catch (e) {
    if (e.code === 'ENOENT') return []
    throw e
  }
}

async function ensureDirs() {
  await fs.mkdir(path.join(GALERIE_DIR, 'originals'), { recursive: true })
  await fs.mkdir(path.join(GALERIE_DIR, 'previews'), { recursive: true })
}

async function main() {
  await ensureDirs()

  const entries = await readJsonArray(GALERIE_METADATA)
  const existingByName = new Map(entries.map(e => [e.filename, e]))

  let files = []
  try {
    files = await fs.readdir(PUBLIC_GALERIE_DIR)
  } catch (e) {
    console.error('public/galerie nicht gefunden:', PUBLIC_GALERIE_DIR)
    process.exit(1)
  }

  const candidates = files.filter(f => allowed.has(path.extname(f).toLowerCase()))
  let migrated = 0
  let skipped = 0

  for (const filename of candidates) {
    if (existingByName.has(filename)) {
      skipped++
      continue
    }

    const id = randomUUID()
    const title = titleFromFilename(filename)

    const src = path.join(PUBLIC_GALERIE_DIR, filename)
    const dest = path.join(GALERIE_DIR, 'originals', filename)

    await fs.rename(src, dest)

    const meta = {
      id,
      filename,
      previewFilename: `preview_${filename}`,
      title,
      description: '',
      isPublic: true,
      uploadedBy: 'migration',
      uploadedAt: new Date().toISOString(),
      originalName: filename
    }

    entries.push(meta)
    existingByName.set(filename, meta)
    migrated++
  }

  await fs.writeFile(GALERIE_METADATA, JSON.stringify(entries, null, 2), 'utf-8')

  console.log(`Fertig. Migriert: ${migrated}, übersprungen: ${skipped}`)
  console.log('Hinweis: previews werden nicht automatisch erzeugt. Für echte previews bitte neu hochladen oder ein separates preview-generator script verwenden.')
}

main().catch(e => {
  console.error(e)
  process.exit(1)
})
