import fs from 'fs'
import path from 'path'
import { eventHandler } from 'h3'
import { getCardFromDate } from '../../../utils/cards'

export default eventHandler(async (event) => {
  const basePath = path.join(process.cwd(), '/mnt/media/files/music')

  try {
    let allTracks: any[] = []

    const dirPath = basePath
    const urlPrefix = `https://files.erudi.fr/music`

    let files = await fs.promises.readdir(dirPath)
    files = files.filter((f) => !f.startsWith('.') && !f.endsWith('.jpg'))

    const tracks = files.map((file, index) => {
      const EXT_RE = /\.(mp3|flac|wav|opus)$/i
      const nameWithoutExt = file.replace(EXT_RE, '')

      // On split sur __
      const parts = nameWithoutExt.split('__')
      let stamp = parts[0] || ''
      let artist = parts[1] || ''
      let title = parts[2] || ''

      title = title.replaceAll('_', ' ')
      artist = artist.replaceAll('_', ' ')

      // Parser la date depuis le stamp
      let year = 2020,
        month = 1,
        day = 1,
        hour = 0
      if (stamp.length === 10) {
        year = Number(stamp.slice(0, 4))
        month = Number(stamp.slice(4, 6))
        day = Number(stamp.slice(6, 8))
        hour = Number(stamp.slice(8, 10))
      }

      const date = new Date(year, month - 1, day, hour)
      const card = getCardFromDate(date)
      const url = `${urlPrefix}/${encodeURIComponent(file)}`
      const coverId = `${urlPrefix}/${encodeURIComponent(file).replace(EXT_RE, '.jpg')}`

      return {
        id: Number(`${year}${index + 1}`),
        boxId: `ES${year}`,
        date,
        title: title.trim(),
        artist: artist.trim(),
        url,
        coverId,
        card,
        order: 0,
        type: 'playlist',
      }
    })

    tracks.sort((a, b) => b.date.getTime() - a.date.getTime())
    // assign a stable order after sort (1..N)
    tracks.forEach((t, i) => (t.order = i + 1))
    allTracks.push(...tracks)

    return allTracks
  } catch (error) {
    return {
      success: false,
      error: (error as Error).message
    }
  }
})
