import type { BaseItemDto } from '../api/types'

/**
 * Tally the user's most-watched genre from a given list of played
 * library items, returning the leader plus a runner-up. We weight
 * each item equally - shows watched once still count once - so the
 * result is "what flavour of media you tend to pick" rather than
 * "what filled the most hours".
 */
export function topGenre(items: BaseItemDto[] | null | undefined): {
  primary: string | null
  runnerUp: string | null
  counts: Record<string, number>
} {
  const counts: Record<string, number> = {}
  for (const it of items || []) {
    for (const g of it.Genres || []) {
      counts[g] = (counts[g] || 0) + 1
    }
  }
  const sorted = Object.entries(counts).sort((a, b) => b[1] - a[1])
  return {
    primary: sorted[0]?.[0] || null,
    runnerUp: sorted[1]?.[0] || null,
    counts,
  }
}
