type Clue = {
  number: number
  points: number
  song: string | null
  answer: string | null
}

type Category = {
  name: string
  songs: Record<number, string>
  answers: Record<number, string>
  clues: Clue[]
}

type Game = {
  name: string
  categories: Category[]
}

type GameMap = Record<
  string,
  {
    name: string
    categories: Record<string, Category>
  }
>

const songFiles = import.meta.globEager('./Data/*/*/Songs/*.mp3') as Record<
  string,
  { default: string }
>

const answerFiles = import.meta.globEager('./Data/*/*/Answers/*.mp3') as Record<
  string,
  { default: string }
>

const getParts = (path: string) => {
  const normalized = path.replace(/\\/g, '/')
  const parts = normalized.split('/')
  const dataIndex = parts.indexOf('Data')
  if (dataIndex === -1) return null
  const game = parts[dataIndex + 1]
  const category = parts[dataIndex + 2]
  const type = parts[dataIndex + 3]
  const file = parts[dataIndex + 4]
  return { game, category, type, file }
}

const addEntry = (target: GameMap, info: ReturnType<typeof getParts>, url: string) => {
  if (!info) return
  const { game, category, type, file } = info
  const number = Number(file.replace('.mp3', ''))
  if (!Number.isFinite(number)) return

  if (!target[game]) {
    target[game] = {
      name: game,
      categories: {}
    }
  }
  if (!target[game].categories[category]) {
    target[game].categories[category] = {
      name: category,
      songs: {},
      answers: {},
      clues: []
    }
  }
  const bucket = type === 'Songs' ? 'songs' : 'answers'
  target[game].categories[category][bucket][number] = url
}

const buildGameData = (): Game[] => {
  const games: GameMap = {}
  Object.entries(songFiles).forEach(([path, module]) => {
    addEntry(games, getParts(path), module.default)
  })
  Object.entries(answerFiles).forEach(([path, module]) => {
    addEntry(games, getParts(path), module.default)
 })

  return Object.values(games).map((game) => {
    const categories = Object.values(game.categories).map((category) => {
      const clues = Array.from({ length: 5 }, (_, index) => {
        const number = index + 1
        return {
          number,
          points: number * 100,
          song: category.songs[number] || null,
          answer: category.answers[number] || null
        }
      })
      return { ...category, clues }
    })
    return { ...game, categories }
  })
}

export const gameData = buildGameData()
export type { Game, Category, Clue }
