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

export default defineEventHandler(async (event) => {
  try {
    const cwd = process.cwd()

    // Prefer internal server/data, fallback to public/data
    let csvPath
    if (cwd.endsWith('.output')) {
      csvPath = path.join(cwd, '../server/data/termine.csv')
      // fallback
      if (!(await fs.access(csvPath).then(()=>true).catch(()=>false))) {
        csvPath = path.join(cwd, '../public/data/termine.csv')
      }
    } else {
      csvPath = path.join(cwd, 'server/data/termine.csv')
      if (!(await fs.access(csvPath).then(()=>true).catch(()=>false))) {
        csvPath = path.join(cwd, 'public/data/termine.csv')
      }
    }

    const csv = await fs.readFile(csvPath, 'utf-8')
    const lines = csv.split('\n').filter(line => line.trim() !== '')

    if (lines.length < 2) {
      return { success: true, termine: [] }
    }

    const termine = []
    for (let i = 1; i < lines.length; i++) {
      const values = []
      let current = ''
      let inQuotes = false

      for (let j = 0; j < lines[i].length; j++) {
        const char = lines[i][j]

        if (char === '"') {
          inQuotes = !inQuotes
        } else if (char === ',' && !inQuotes) {
          values.push(current.trim())
          current = ''
        } else {
          current += char
        }
      }
      values.push(current.trim())

      if (values.length >= 4) {
        termine.push({
          datum: values[0],
          uhrzeit: values[1] || '',
          titel: values[2] || '',
          beschreibung: values[3] || '',
          kategorie: values[4] || 'Sonstiges'
        })
      }
    }

    return {
      success: true,
      termine
    }
  } catch (error) {
    console.error('Fehler beim Laden der Termine:', error)
    return { success: true, termine: [] }
  }
})

