package eu.friedcutlet.yokan.ui.screens.home import androidx.compose.runtime.Immutable import eu.friedcutlet.yokan.data.toDomainChapter import eu.friedcutlet.yokan.data.toDomainMangas import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.services.discovery.DiscoveryIssue import eu.friedcutlet.yokan.services.discovery.DiscoveryMedia import eu.friedcutlet.yokan.services.discovery.TmdbSeed import eu.friedcutlet.yokan.services.tracking.TmdbTrackerSyncId import eu.friedcutlet.yokan.services.tracking.tmdbMediaOf import eu.friedcutlet.yokan.ui.navigation.hiddenNavigationSections import eu.friedcutlet.yokan.ui.navigation.librarySection import eu.friedcutlet.yokan.services.library.readingChapterSequence @Immutable internal data class HomeCard( val media: DiscoveryMedia, val mangaId: Long? = null, val chapterId: Long? = null, val coverBytes: ByteArray? = null, val completed: Boolean = false, val chapterName: String? = null, val position: Long = 0, val progress: Float? = null, val novelProgress: Float? = null, ) internal data class HomeLocalData( val library: List = emptyList(), val resume: List = emptyList(), val seed: HomeCard? = null, val titlesByTypeAndName: Map, Manga> = emptyMap(), val titlesBySourceUrl: Map, Manga> = emptyMap(), val sources: List = emptyList(), val presets: List = emptyList(), val hiddenTypes: Set = emptySet(), /** Most recently updated/watched TMDB-tracked titles feeding [HomeSection.TmdbRecommended]. */ val tmdbSeeds: List = emptyList(), /** Every TMDB-tracked [TmdbSeed.key]; never recommended back. */ val tmdbTracked: Set = emptySet(), ) internal data class HomeRemoteShelf( val id: String, val section: HomeSection, val items: List = emptyList(), val loading: Boolean = false, val issue: DiscoveryIssue? = null, val sourceName: String? = null, ) internal data class HomeShelf( val id: String, val section: HomeSection, val cards: List, val loading: Boolean = false, val issue: DiscoveryIssue? = null, val sourceName: String? = null, ) internal data class HomeState( val preferences: DbHomePreferences = DbHomePreferences(), val shelves: List = emptyList(), val featured: List = emptyList(), val seedTitle: String? = null, val sources: List = emptyList(), val presets: List = emptyList(), val feeds: List = emptyList(), val tmdbConfigured: Boolean = false, val refreshing: Boolean = false, val customizeOpen: Boolean = false, val searchOpen: Boolean = false, val searchQuery: String = "", val openIssue: DiscoveryIssue? = null, ) internal fun ItemType.homeKind(): HomeMediaFilter = when (this) { ItemType.Manga -> HomeMediaFilter.Manga ItemType.Anime -> HomeMediaFilter.Anime ItemType.Novel -> HomeMediaFilter.Novel } internal fun projectHomeLocal(snapshot: YokanDatabaseSnapshot, trackerScoreRanges: Map = emptyMap()): HomeLocalData { val settings = snapshot.settings val hidden = hiddenNavigationSections(settings) val hiddenTypes = ItemType.entries.filterTo(mutableSetOf()) { it.librarySection() in hidden } val blockedSources = snapshot.sources.filter { !settings.showNsfw && it.isNsfw }.mapTo(mutableSetOf()) { it.id } val mangas = snapshot.mangas.toDomainMangas(settings).filter { it.itemType !in hiddenTypes && it.sourceId !in blockedSources } val byId = mangas.associateBy { it.id } val chapters = snapshot.chapters.groupBy { it.mangaId } val pageCounts = snapshot.pageCache.associate { it.chapterId to it.urls.orEmpty().size } val downloads = snapshot.downloads.filter { it.isDownload == true }.mapNotNullTo(mutableSetOf()) { it.chapterId } val scores = snapshot.tracks.groupBy { it.mangaId }.mapValues { (_, rows) -> rows.mapNotNull { track -> eu.friedcutlet.yokan.services.tracking.normalizedTrackerScore(track.syncId, track.score, trackerScoreRanges[track.syncId]?.last ?: eu.friedcutlet.yokan.services.tracking.trackerScoreMaximum(track.syncId)) }.average().takeIf { !it.isNaN() } } fun card(manga: Manga): HomeCard = HomeCard( media = DiscoveryMedia("library:${manga.id}", manga.name, manga.itemType.homeKind(), manga.imageUrl, description = manga.description, genres = manga.genres, rating = scores[manga.id], aliases = manga.alternativeTitles), mangaId = manga.id, coverBytes = manga.customCoverImage, completed = chapters[manga.id].orEmpty().let { it.isNotEmpty() && it.all { chapter -> chapter.isRead } }, ) val recent = snapshot.histories.sortedByDescending { it.updatedAt }.distinctBy { it.mangaId } val resume = recent.mapNotNull { history -> val manga = byId[history.mangaId] ?: return@mapNotNull null val all = chapters[manga.id].orEmpty().map(::toDomainChapter) val current = all.firstOrNull { it.id == history.chapterId } ?: return@mapNotNull null val sequence = readingChapterSequence(manga, current.id, all, settings, downloads) val chapter = if (!current.isRead) sequence.firstOrNull { it.id == current.id } else { val index = sequence.indexOfFirst { it.id == current.id } sequence.drop(index + 1).firstOrNull { !it.isRead } } ?: return@mapNotNull null val position = chapter.lastPageRead.toLongOrNull()?.coerceAtLeast(0) ?: 0L val totalPages = pageCounts[chapter.id] ?: 0 card(manga).copy(chapterId = chapter.id, chapterName = chapter.name, position = position, novelProgress = if (manga.itemType == ItemType.Novel) chapter.lastPageRead.toFloatOrNull()?.coerceIn(0f, 1f) ?: 0f else null, progress = when { manga.itemType == ItemType.Novel -> chapter.lastPageRead.toFloatOrNull()?.coerceIn(0f, 1f) manga.itemType == ItemType.Manga && totalPages > 0 -> ((position + 1f) / totalPages).coerceIn(0f, 1f) else -> null }) }.take(24) val index = buildMap { mangas.sortedByDescending { it.favorite }.forEach { manga -> (listOf(manga.name) + manga.alternativeTitles).forEach { name -> val key = manga.itemType to normalizedHomeTitle(name) if (key !in this) put(key, manga) } } } val tmdbTracks = snapshot.tracks.mapNotNull { track -> if (track.syncId != TmdbTrackerSyncId) null else tmdbMediaOf(track)?.let { (type, id) -> track to TmdbSeed(type, id) } } val lastWatched = recent.associate { it.mangaId to it.updatedAt } return HomeLocalData( library = mangas.filter { it.favorite && it.parentId == null }.sortedByDescending { it.lastReadMillis }.map(::card), resume = resume, seed = recent.firstNotNullOfOrNull { byId[it.mangaId]?.let(::card) }, titlesByTypeAndName = index, titlesBySourceUrl = mangas.associateBy { it.sourceId to it.link }, sources = snapshot.sources.filter { it.isAdded && it.isActive && (settings.showNsfw || !it.isNsfw) }, presets = settings.savedSearches.orEmpty(), hiddenTypes = hiddenTypes, tmdbSeeds = tmdbTracks.filter { (track, _) -> track.mangaId in byId } .sortedByDescending { (track, _) -> maxOf(track.updatedAt, lastWatched[track.mangaId] ?: 0L) } .map { it.second }.distinct().take(TmdbSeedLimit), tmdbTracked = tmdbTracks.mapTo(mutableSetOf()) { it.second.key }, ) } private const val TmdbSeedLimit = 8 internal fun normalizedHomeTitle(title: String): String = title.trim().lowercase().replace(Regex("\\s+"), " ") internal fun buildHomeState(local: HomeLocalData, remote: List, settings: DbSettings): HomeState { val prefs = settings.home val limit = prefs.itemsPerShelf.coerceIn(6, 24) val libraryById = local.library.associateBy { it.mangaId } fun match(media: DiscoveryMedia): HomeCard { val manga = if (media.sourceId != null) local.titlesBySourceUrl[media.sourceId to media.sourceUrl.orEmpty()] else (listOf(media.title) + media.aliases).firstNotNullOfOrNull { local.titlesByTypeAndName[media.itemType to normalizedHomeTitle(it)] } return HomeCard(media, manga?.id, coverBytes = manga?.customCoverImage, completed = libraryById[manga?.id]?.completed == true) } fun visible(card: HomeCard) = card.media.itemType !in local.hiddenTypes && (prefs.filter == HomeMediaFilter.All || prefs.filter == card.media.kind) && (!prefs.hideCompleted || !card.completed) fun sectionKind(section: HomeSection): HomeMediaFilter? = when (section) { HomeSection.PopularAnime -> HomeMediaFilter.Anime HomeSection.PopularManga -> HomeMediaFilter.Manga HomeSection.PopularNovels -> HomeMediaFilter.Novel HomeSection.PopularMovies -> HomeMediaFilter.Movie HomeSection.PopularSeries -> HomeMediaFilter.Series HomeSection.BecauseYouRead -> local.seed?.media?.kind else -> null } val remoteShelves = remote.filter { it.section !in prefs.hiddenSections && (prefs.filter == HomeMediaFilter.All || sectionKind(it.section) == null || sectionKind(it.section) == prefs.filter) && sectionKind(it.section)?.let { kind -> DiscoveryMedia("", "", kind).itemType !in local.hiddenTypes } != false && (it.section != HomeSection.TmdbRecommended || (prefs.filter in TmdbFilters && ItemType.Anime !in local.hiddenTypes)) }.map { shelf -> // Source feeds honour Browse's per-type "hide entries already in library" (re-applied on every settings/library change). fun hiddenInLibrary(card: HomeCard) = shelf.section == HomeSection.Sources && card.mangaId in libraryById && settings.features.browse.hidesLibrary(card.media.itemType) // TMDB recommendations never suggest what the user already tracks or keeps in the library. fun known(card: HomeCard) = shelf.section == HomeSection.TmdbRecommended && (card.media.key in local.tmdbTracked || card.mangaId in libraryById) HomeShelf(shelf.id, shelf.section, shelf.items.map(::match).filter { visible(it) && !hiddenInLibrary(it) && !known(it) } .distinctBy { it.mangaId?.let { id -> "library:$id" } ?: it.media.key }.take(limit), shelf.loading, shelf.issue, shelf.sourceName) } val seedGenres = local.seed?.media?.genres.orEmpty().mapTo(mutableSetOf()) { it.lowercase() } val recommendationCandidates = remote.flatMap { it.items }.map(::match) + local.library val recommended = recommendationCandidates.filter(::visible).filter { it.mangaId == null || it.mangaId != local.seed?.mangaId } .distinctBy { it.mangaId?.let { id -> "library:$id" } ?: it.media.key } .sortedByDescending { card -> card.media.genres.count { it.lowercase() in seedGenres } }.take(limit) val shelves = buildList { if (HomeSection.Continue !in prefs.hiddenSections) add(HomeShelf("continue", HomeSection.Continue, local.resume.filter(::visible).take(limit))) if (HomeSection.Recommended !in prefs.hiddenSections) add(HomeShelf("recommended", HomeSection.Recommended, recommended, loading = remote.any { it.loading } && recommended.isEmpty())) addAll(remoteShelves) } val featuredPool = if (prefs.featuredLibraryOnly) local.library else local.resume + recommended + remoteShelves.flatMap { it.cards } val featured = if (prefs.showFeatured) featuredPool.filter(::visible).distinctBy { it.mangaId?.let { id -> "library:$id" } ?: it.media.key }.take(7) else emptyList() return HomeState(prefs.forPresentation(), shelves, featured, local.seed?.media?.title, local.sources, local.presets, prefs.sourceFeeds, prefs.tmdbReadAccessToken.isNotBlank(), remote.any { it.loading }) } private val TmdbFilters = setOf(HomeMediaFilter.All, HomeMediaFilter.Movie, HomeMediaFilter.Series)