package com.fabledsword.minstrel.metadata

import java.util.Collections
import javax.inject.Inject
import javax.inject.Singleton

private const val TOP_N = 8

/**
 * Pre-warms the Room cache for likely-tap artist tiles on Home. Mirrors
 * Flutter's `MetadataPrefetcher`: conservative — artists only (a single
 * round-trip per id), top-8 per call, and once per id per session so
 * repeated index refreshes don't re-fetch. Albums are intentionally not
 * pre-warmed (their detail fetch fans out a track list).
 *
 * Fetches go through [MetadataProvider.refreshArtist], so they share the
 * same per-id dedup AND the 4-slot concurrency gate as on-render
 * hydration — the prewarm can't starve the tiles the user is looking at.
 */
@Singleton
class HomeArtistPrewarmer @Inject constructor(
    private val metadataProvider: MetadataProvider,
) {
    private val warmed = Collections.synchronizedSet(mutableSetOf<String>())

    fun warm(artistIds: List<String>) {
        artistIds.asSequence()
            .filter { it.isNotEmpty() }
            .filter { warmed.add(it) }
            .take(TOP_N)
            .forEach { metadataProvider.refreshArtist(it) }
    }
}
