import { parseSSC } from '../../game/sscParser'
import { AUDIO_EXTS, CHART_EXTS, IMAGE_EXTS, easiestDifficulty, ext, generateId } from './file-utils'
import type { SongBundle } from './types'

export async function parseBundleFromFiles(files: File[]): Promise<SongBundle[]> {
  const chartFiles = files.filter((f) => CHART_EXTS.includes(ext(f.name)))
  const audioFiles = files.filter((f) => AUDIO_EXTS.includes(ext(f.name)))
  const imageFiles = files.filter((f) => IMAGE_EXTS.includes(ext(f.name)))

  if (chartFiles.length === 0) throw new Error('No chart file (.ssc or .sm) found')
  if (audioFiles.length === 0) throw new Error('No audio file (.ogg, .mp3, .wav) found')

  const chartText = await chartFiles[0].text()
  const chart = parseSSC(chartText)

  if (chart.difficulties.length === 0) throw new Error('No playable difficulties found in chart')

  const bgFile = imageFiles.find((f) => /bg/i.test(f.name)) ?? imageFiles[0] ?? null
  const bannerFile = imageFiles.find((f) => /bn|banner/i.test(f.name)) ?? bgFile

  return [
    {
      id: generateId(),
      chart,
      chartFile: chartFiles[0],
      audioFile: audioFiles[0],
      bgFile,
      bannerFile,
      selectedDifficulty: easiestDifficulty(chart),
      simplify: true,
    },
  ]
}
