# 09 — repository-and-library: file workbook

[Implementation chapter](../chapters/09-repository-and-library.md) · [Coverage index](README.md)

Each text entry includes the complete pinned file to write at the displayed path, plus an exact-byte download. Read the chapter for implementation order and behavior, then connect callers and reproduce the tests. Platform variants preserve their platform capabilities. Binary assets are retained with applicable licenses or independently recreated, not transcribed as code.

**Pinned baseline for comparison.** Use the reviewed listings in the [implementation chapters](../README.md#reading-order) and the [reviewed source archive](reviewed-source.zip) when reconstructing the app. See the [architecture review](architecture-review.md) for changes.

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/DbMappers.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/DbMappers.kt) · implementation · 305 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
36: internal fun DbCategory.toDomain(): Category = Category(
45: internal fun DbManga.toDomain(settings: DbSettings): Manga = toDomain(settings.titleMetadataFor(id))
48: internal fun Iterable<DbManga>.toDomainMangas(settings: DbSettings): List<Manga> {
54: private fun DbManga.toDomain(metadata: DbTitleMetadata?): Manga {
93: internal fun DbSettings.titleMetadataFor(mangaId: Long): DbTitleMetadata? =
96: internal fun mergedDistinct(values: List<String>): List<String> =
100: internal fun ItemType.toDb(): DbItemType = when (this) {
106: internal fun DbItemType.toDomain(): ItemType = when (this) {
112: internal fun DbStatus.toDomain(): Status = when (this) {
123: internal fun DbSourceCodeLanguage.toDomain(): SourceCodeLanguage = when (this) {
130: internal fun DbSettings.toDomain(): UserSettings = UserSettings(
149: internal fun DbSettings.withUserSettings(settings: UserSettings): DbSettings = copy(
168: internal fun DbDisplayType.toDomain(): DisplayType = when (this) {
175: internal fun DisplayType.toDb(): DbDisplayType = when (this) {
182: internal fun DbReaderMode.toDomain(): ReaderMode = when (this) {
192: internal fun ReaderMode.toDb(): DbReaderMode = when (this) {
199: internal fun DbTrackStatus.toDomain(): TrackStatus = when (this) {
211: internal fun DbSource.toDomain(): Source = Source(
234: internal fun DbRepo.toDomain(): Repo = Repo(
241: internal fun DbHistory.toDomain(manga: DbManga?, chapter: DbChapter?): History? = History(
256: internal fun DbUpdate.toDomain(manga: DbManga?, chapter: DbChapter?): UpdateEntry? = UpdateEntry(
269: internal fun DbTrack.toDomain(): Track = Track(
284: internal fun toDomainChapter(it: DbChapter) = eu.friedcutlet.yokan.domain.Chapter(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/DbMappers.kt) · SHA-256 `68f3d11eb154ed093d6e2eac261a15c124b5cf24de42736b6f0bfb9cba602ae4`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbDisplayType
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbRepo
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.DbStatus
import eu.friedcutlet.yokan.database.DbTitleMetadata
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.DbUpdate
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.DisplayType
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.History
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.ReaderMode
import eu.friedcutlet.yokan.domain.Repo
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.domain.SourceCodeLanguage
import eu.friedcutlet.yokan.domain.Status
import eu.friedcutlet.yokan.domain.Track
import eu.friedcutlet.yokan.domain.TrackStatus
import eu.friedcutlet.yokan.domain.UpdateEntry
import eu.friedcutlet.yokan.domain.UserSettings

// Database ↔ domain model conversions; reuse these instead of adding local copies.

internal fun DbCategory.toDomain(): Category = Category(
    id = id,
    name = name,
    forItemType = forItemType.toDomain(),
    position = position ?: 0,
    hidden = hidden ?: false,
    shouldUpdate = shouldUpdate ?: true,
)

internal fun DbManga.toDomain(settings: DbSettings): Manga = toDomain(settings.titleMetadataFor(id))

/** One metadata index per list mapping; preserve the first match used by single-title reads. */
internal fun Iterable<DbManga>.toDomainMangas(settings: DbSettings): List<Manga> {
    val metadata = HashMap<Long, DbTitleMetadata>()
    settings.titleMetadata.orEmpty().forEach { metadata.getOrPut(it.mangaId) { it } }
    return map { it.toDomain(metadata[it.id]) }
}

private fun DbManga.toDomain(metadata: DbTitleMetadata?): Manga {
    val titles = mergedDistinct(listOf(name.orEmpty()) + metadata?.titles.orEmpty())
    return Manga(
        id = id,
        name = name.orEmpty(),
        alternativeTitles = titles,
        link = link.orEmpty(),
        imageUrl = imageUrl,
        customCoverImage = customCoverImage,
        customCoverFromTracker = customCoverFromTracker,
        description = description.orEmpty(),
        privateNote = privateNote,
        nextEpisodeAiringAt = nextEpisodeAiringAt,
        nextEpisodeNumber = nextEpisodeNumber,
        cast = cast,
        parentId = parentId,
        fetchesSeasons = fetchType == eu.friedcutlet.yokan.database.DbFetchType.Seasons,
        seasonNumber = seasonNumber,
        author = author,
        artist = artist,
        status = status.toDomain(),
        itemType = itemType.toDomain(),
        genres = genre.orEmpty(),
        favorite = favorite,
        source = source.orEmpty(),
        lang = lang.orEmpty(),
        dateAddedMillis = dateAdded ?: 0,
        lastUpdateMillis = lastUpdate ?: 0,
        lastReadMillis = lastRead,
        categories = categories.orEmpty(),
        isLocalArchive = isLocalArchive,
        smartUpdateDays = smartUpdateDays,
        sourceId = sourceId,
        metadataServerId = metadata?.metadataServerId,
        metadataSource = metadata?.metadataSource,
        metadataUpdatedAt = metadata?.updatedAt ?: 0L,
    )
}

internal fun DbSettings.titleMetadataFor(mangaId: Long): DbTitleMetadata? =
    titleMetadata.orEmpty().firstOrNull { it.mangaId == mangaId }

internal fun mergedDistinct(values: List<String>): List<String> =
    values.mapNotNull { value -> value.trim().takeIf { it.isNotBlank() } }
        .distinctBy { it.lowercase() }

internal fun ItemType.toDb(): DbItemType = when (this) {
    ItemType.Manga -> DbItemType.Manga
    ItemType.Anime -> DbItemType.Anime
    ItemType.Novel -> DbItemType.Novel
}

internal fun DbItemType.toDomain(): ItemType = when (this) {
    DbItemType.Manga -> ItemType.Manga
    DbItemType.Anime -> ItemType.Anime
    DbItemType.Novel -> ItemType.Novel
}

internal fun DbStatus.toDomain(): Status = when (this) {
    DbStatus.Ongoing -> Status.Ongoing
    DbStatus.Completed -> Status.Completed
    DbStatus.Canceled -> Status.Canceled
    DbStatus.Unknown -> Status.Unknown
    DbStatus.OnHiatus -> Status.OnHiatus
    DbStatus.PublishingFinished -> Status.PublishingFinished
    DbStatus.Licensed -> Status.Licensed
    DbStatus.Upcoming -> Status.Upcoming
}

internal fun DbSourceCodeLanguage.toDomain(): SourceCodeLanguage = when (this) {
    DbSourceCodeLanguage.JavaScript -> SourceCodeLanguage.JavaScript
    DbSourceCodeLanguage.Mihon -> SourceCodeLanguage.Mihon
    DbSourceCodeLanguage.LnReader -> SourceCodeLanguage.LnReader
    DbSourceCodeLanguage.Aidoku -> SourceCodeLanguage.Aidoku
}

internal fun DbSettings.toDomain(): UserSettings = UserSettings(
    displayType = displayType.toDomain(),
    followSystemTheme = followSystemTheme,
    darkTheme = themeIsDark,
    incognitoMode = incognitoMode,
    downloadedOnly = downloadedOnlyMode,
    defaultReaderMode = defaultReaderMode.toDomain(),
    libraryShowCategoryTabs = libraryShowCategoryTabs,
    libraryShowLanguage = libraryShowLanguage,
    libraryShowSource = libraryShowSource,
    libraryShowNumbersOfItems = libraryShowNumbersOfItems,
    showPagesNumber = showPagesNumber,
    concurrentDownloads = concurrentDownloads,
    allowConcurrentDownloads = allowConcurrentDownloads,
    downloadDelaySeconds = downloadDelaySeconds,
    checkForAppUpdates = checkForAppUpdates,
    checkForExtensionUpdates = checkForExtensionUpdates,
)

internal fun DbSettings.withUserSettings(settings: UserSettings): DbSettings = copy(
    displayType = settings.displayType.toDb(),
    followSystemTheme = settings.followSystemTheme,
    themeIsDark = settings.darkTheme,
    incognitoMode = settings.incognitoMode,
    downloadedOnlyMode = settings.downloadedOnly,
    defaultReaderMode = settings.defaultReaderMode.toDb(),
    libraryShowCategoryTabs = settings.libraryShowCategoryTabs,
    libraryShowLanguage = settings.libraryShowLanguage,
    libraryShowSource = settings.libraryShowSource,
    libraryShowNumbersOfItems = settings.libraryShowNumbersOfItems,
    showPagesNumber = settings.showPagesNumber,
    concurrentDownloads = settings.concurrentDownloads,
    allowConcurrentDownloads = settings.allowConcurrentDownloads,
    downloadDelaySeconds = settings.downloadDelaySeconds,
    checkForAppUpdates = settings.checkForAppUpdates,
    checkForExtensionUpdates = settings.checkForExtensionUpdates,
)

internal fun DbDisplayType.toDomain(): DisplayType = when (this) {
    DbDisplayType.CompactGrid -> DisplayType.CompactGrid
    DbDisplayType.ComfortableGrid -> DisplayType.ComfortableGrid
    DbDisplayType.CoverOnlyGrid -> DisplayType.CoverOnlyGrid
    DbDisplayType.List -> DisplayType.List
}

internal fun DisplayType.toDb(): DbDisplayType = when (this) {
    DisplayType.CompactGrid -> DbDisplayType.CompactGrid
    DisplayType.ComfortableGrid -> DbDisplayType.ComfortableGrid
    DisplayType.CoverOnlyGrid -> DbDisplayType.CoverOnlyGrid
    DisplayType.List -> DbDisplayType.List
}

internal fun DbReaderMode.toDomain(): ReaderMode = when (this) {
    DbReaderMode.Vertical,
    DbReaderMode.VerticalContinuous -> ReaderMode.ContinuousVertical
    DbReaderMode.Webtoon -> ReaderMode.Webtoon
    DbReaderMode.Ltr,
    DbReaderMode.Rtl,
    DbReaderMode.HorizontalContinuous,
    DbReaderMode.HorizontalContinuousRtl -> ReaderMode.Paged
}

internal fun ReaderMode.toDb(): DbReaderMode = when (this) {
    ReaderMode.Paged -> DbReaderMode.Ltr
    ReaderMode.ContinuousVertical -> DbReaderMode.VerticalContinuous
    ReaderMode.Webtoon -> DbReaderMode.Webtoon
    ReaderMode.Novel -> DbReaderMode.Vertical
}

internal fun DbTrackStatus.toDomain(): TrackStatus = when (this) {
    DbTrackStatus.Reading -> TrackStatus.Reading
    DbTrackStatus.Completed -> TrackStatus.Completed
    DbTrackStatus.OnHold -> TrackStatus.OnHold
    DbTrackStatus.Dropped -> TrackStatus.Dropped
    DbTrackStatus.PlanToRead -> TrackStatus.PlanToRead
    DbTrackStatus.ReReading -> TrackStatus.ReReading
    DbTrackStatus.Watching -> TrackStatus.Watching
    DbTrackStatus.PlanToWatch -> TrackStatus.PlanToWatch
    DbTrackStatus.ReWatching -> TrackStatus.ReWatching
}

internal fun DbSource.toDomain(): Source = Source(
    id = id,
    name = name,
    baseUrl = baseUrl,
    lang = lang,
    itemType = itemType.toDomain(),
    typeSource = typeSource,
    iconUrl = iconUrl,
    isActive = isActive,
    isAdded = isAdded,
    isPinned = isPinned,
    isNsfw = isNsfw,
    hasCloudflare = hasCloudflare,
    supportLatest = supportLatest == true,
    version = version,
    versionLast = versionLast,
    lastUsed = lastUsed,
    isObsolete = isObsolete,
    sourceCodeLanguage = sourceCodeLanguage.toDomain(),
    repo = repo?.toDomain(),
    notes = notes,
)

internal fun DbRepo.toDomain(): Repo = Repo(
    name = name.orEmpty(),
    jsonUrl = jsonUrl.orEmpty(),
    website = website,
)

/** `null` when the row lost its title or chapter link. */
internal fun DbHistory.toDomain(manga: DbManga?, chapter: DbChapter?): History? = History(
    id = id,
    mangaId = mangaId ?: return null,
    chapterId = chapterId ?: return null,
    itemType = itemType.toDomain(),
    title = manga?.name.orEmpty(),
    chapterName = chapter?.name.orEmpty(),
    date = date.orEmpty(),
    readingTimeSeconds = readingTimeSeconds ?: 0,
    updatedAt = updatedAt,
    lastPageRead = chapter?.lastPageRead.orEmpty(),
    chapterIsRead = chapter?.isRead ?: false,
)

/** `null` when the row lost its title link. */
internal fun DbUpdate.toDomain(manga: DbManga?, chapter: DbChapter?): UpdateEntry? = UpdateEntry(
    id = id,
    mangaId = mangaId ?: return null,
    chapterId = chapterId ?: 0L,
    itemType = manga?.itemType?.toDomain() ?: ItemType.Manga,
    title = manga?.name.orEmpty(),
    chapterName = chapterName.orEmpty(),
    source = manga?.source.orEmpty(),
    date = date.orEmpty(),
    isRead = chapter?.isRead ?: false,
    updatedAt = updatedAt,
)

internal fun DbTrack.toDomain(): Track = Track(
    id = id,
    libraryId = libraryId ?: 0,
    mediaId = mediaId ?: 0,
    mangaId = mangaId ?: 0,
    syncId = syncId ?: 0,
    title = title.orEmpty(),
    progress = lastChapterRead ?: 0,
    total = totalChapter ?: 0,
    score = score ?: 0,
    status = status.toDomain(),
    trackingUrl = trackingUrl.orEmpty(),
    itemType = itemType.toDomain(),
)

internal fun toDomainChapter(it: DbChapter) = eu.friedcutlet.yokan.domain.Chapter(
    id = it.id,
    mangaId = it.mangaId ?: 0,
    name = it.name.orEmpty(),
    url = it.url,
    dateUpload = it.dateUpload,
    scanlator = it.scanlator,
    isBookmarked = it.isBookmarked,
    isRead = it.isRead,
    lastPageRead = it.lastPageRead,
    archivePath = it.archivePath,
    isFiller = it.fillerOverride ?: it.isFiller,
    thumbnailUrl = it.thumbnailUrl,
    description = it.description,
    downloadSize = it.downloadSize,
    duration = it.duration,
    fetchedAt = it.fetchedAt,
    number = it.number,
    season = it.season,
    numberingName = it.numberingName,
    fillerOverride = it.fillerOverride,
)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/DefaultYokanRepository.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/DefaultYokanRepository.kt) · implementation · 839 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
44: class DefaultYokanRepository(
63: override fun settings(): UserSettings = database.settings().toDomain()
65: override fun dbSettings(): DbSettings = database.settings()
67: override fun updateSettings(transform: (UserSettings) -> UserSettings): UserSettings {
73: override fun updateDbSettings(transform: (DbSettings) -> DbSettings): DbSettings = database.batch {
79: override fun syncPreference(syncId: Long): DbSyncPreference =
82: override fun updateSyncPreference(syncId: Long, transform: (DbSyncPreference) -> DbSyncPreference): DbSyncPreference {
88: override fun library(itemType: ItemType): List<Manga> =
91: override fun chapters(mangaId: Long): List<Chapter> =
94: override fun allChapters(): List<Chapter> =
97: override fun categories(itemType: ItemType): List<Category> =
100: override fun createCategory(itemType: ItemType, name: String): Category {
115: override fun updateCategory(categoryId: Long, name: String?, hidden: Boolean?, shouldUpdate: Boolean?): Category? {
127: override fun moveCategory(itemType: ItemType, categoryId: Long, offset: Int) {
141: override fun removeCategory(categoryId: Long) = database.batch {
170: override fun sources(itemType: ItemType): List<Source> =
173: override fun source(sourceId: Long): Source? = database.source(sourceId)?.toDomain()
175: override fun setSourceActive(sourceId: Long, active: Boolean) {
181: override fun setSourcePinned(sourceId: Long, pinned: Boolean) {
187: override fun setSourceAdded(sourceId: Long, added: Boolean) {
193: override fun markSourceUsed(sourceId: Long) {
208: override fun updateSourceCode(sourceId: Long, code: String) {
214: override fun removeSource(sourceId: Long) {
218: override fun repositories(itemType: ItemType): List<DbRepo> = when (itemType) {
224: override fun upsertRepository(itemType: ItemType, repo: DbRepo) {
233: override fun removeRepository(itemType: ItemType, jsonUrl: String) {
238: override fun allTitles(itemType: ItemType): List<Manga> =
241: override fun manga(mangaId: Long): Manga? = database.manga(mangaId)?.toDomain(database.settings())
243: override fun pageUrls(chapterId: Long): List<DbPageUrl> =
257: override fun cachePageUrls(
287: override fun clearPageCache() = database.clearPageCache()
289: override fun upsertRemoteTitle(source: Source, remote: RemoteManga, favorite: Boolean?): Manga =
292: override fun upsertRemoteDetail(source: Source, detail: RemoteDetail, favorite: Boolean?): Manga =
295: override fun applyMetadata(mangaId: Long, metadata: MetadataMedia): Manga? {
327: override fun applyLocalMetadataFields(mangaId: Long, metadata: MetadataMedia, fields: Set<LocalMetadataField>): Manga? {
367: override fun setMangaPrivateNote(mangaId: Long, note: String): Manga? = database.batch {
373: override fun setMangaDisplayTitle(mangaId: Long, title: String): Manga? {
390: override fun setMangaCustomCover(mangaId: Long, bytes: ByteArray): Manga? {
401: override fun history(): List<History> =
406: override fun updates(): List<UpdateEntry> =
411: override fun tracks(): List<Track> = database.tracks().map { it.toDomain() }
413: override fun downloads(): List<DbDownload> = database.downloads()
415: override fun removeDownload(downloadId: Long) {
428: override fun cancelDownload(downloadId: Long) {
434: override fun clearChapterDownloads(chapterIds: Set<Long>) {
453: override fun setMangaCategories(mangaId: Long, categories: List<Long>, favorite: Boolean) {
475: override fun setLibraryEntriesRead(mangaIds: Set<Long>, isRead: Boolean) {
498: override fun chapterOpened(chapterId: Long) {
504: private fun emitRead(mangaIds: Collection<Long>) =
507: override fun chapterClosed(chapterId: Long) { downloadAutomation?.chapterClosed(chapterId) }
508: override fun recordChapterConsumption(chapterIds: Set<Long>) {
514: override fun setChaptersRead(
597: override fun setChaptersBookmarked(chapterIds: Set<Long>, bookmarked: Boolean) {
606: override fun setChaptersFillerOverride(chapterIds: Set<Long>, filler: Boolean?) {
615: override fun setMangaFavorite(mangaId: Long, favorite: Boolean) {
641: override fun setMangaSmartUpdateDays(mangaId: Long, days: Int?) {
647: override fun removeLibraryEntries(mangaIds: Set<Long>) {
658: override fun deleteChapters(chapterIds: Set<Long>) {
667: override fun setUpdateRead(updateId: Long, isRead: Boolean) {
674: override fun clearUpdates(itemType: ItemType) {
688: override fun removeHistory(historyId: Long) {
692: override fun clearHistory(itemType: ItemType) {
701: override fun clearLibrary(itemType: ItemType) {
709: override fun clearLocalLibrary(): Int = database.batch {
733: override fun cleanDatabase(): Int = database.batch {
746: override fun pruneBrowsedTitles(): Int {
782: override fun bindTrack(mangaId: Long, search: DbTrackSearch, itemType: ItemType) {
787: override fun updateTrack(trackId: Long, progress: Int, status: DbTrackStatus, score: Int) {
801: override fun removeTrack(trackId: Long, removeRemote: Boolean) {
807: override fun refreshTracks(mangaId: Long) {
812: private fun DbSettings.withRepositories(itemType: ItemType, repos: List<DbRepo>): DbSettings = when (itemType) {
818: private fun DbSettings.withTitleMetadata(metadata: DbTitleMetadata): DbSettings =
827: private fun String.isSensitivePageHeader(): Boolean =
830: private fun Map<String, String>.encodePageHeaders(): String =
833: private fun String.decodePageHeaders(): Map<String, String>? {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/DefaultYokanRepository.kt) · SHA-256 `3d3912be563da3b7fc7f5ef88a702e62d957cc47341482eb0e8bae9c06a5971a`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbRepo
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbStatus
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.DbTitleMetadata
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SnapshotReplacementConflictException
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.adoptLegacySourcePresets
import eu.friedcutlet.yokan.database.seasonsOwnedByLibrary
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.History
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.domain.Status
import eu.friedcutlet.yokan.domain.Track
import eu.friedcutlet.yokan.domain.UpdateEntry
import eu.friedcutlet.yokan.domain.UserSettings
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceRepositoryUrls
import eu.friedcutlet.yokan.services.metadata.LocalMetadataField
import eu.friedcutlet.yokan.services.metadata.MetadataMedia
import eu.friedcutlet.yokan.util.nowMillis
import eu.friedcutlet.yokan.services.download.DownloadAutomation
import eu.friedcutlet.yokan.services.tracking.TrackerAccounts
import eu.friedcutlet.yokan.services.tracking.toDbTrack
import eu.friedcutlet.yokan.services.sync.SyncTriggerKind
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

class DefaultYokanRepository(
    private val database: YokanDatabase = InMemoryYokanDatabase(),
    /** Download side effects of opening, reading and marking chapters, including "delete after reading". */
    private val downloadAutomation: DownloadAutomation? = null,
    /** Remote side of tracking, notified after each local track/progress/library change. */
    private val trackerAccounts: TrackerAccounts? = null,
    /** Chapter/episode open and read events for [eu.friedcutlet.yokan.services.sync.SyncTriggerCoordinator]. */
    private val onSyncTrigger: (SyncTriggerKind) -> Unit = {},
) : YokanRepository {
    override val snapshots = database.snapshots()

    init {
        database.batch {
            val before = database.settings()
            val adopted = before.adoptLegacySourcePresets(database.sources())
            if (adopted != before) database.updateSettings(adopted)
        }
    }

    override fun settings(): UserSettings = database.settings().toDomain()

    override fun dbSettings(): DbSettings = database.settings()

    override fun updateSettings(transform: (UserSettings) -> UserSettings): UserSettings {
        val updated = transform(database.settings().toDomain())
        database.updateSettings(database.settings().withUserSettings(updated).copy(updatedAt = nowMillis()))
        return updated
    }

    override fun updateDbSettings(transform: (DbSettings) -> DbSettings): DbSettings = database.batch {
        val updated = transform(database.settings()).copy(updatedAt = nowMillis())
        database.updateSettings(updated)
        updated
    }

    override fun syncPreference(syncId: Long): DbSyncPreference =
        database.syncPreferences().firstOrNull { it.syncId == syncId } ?: DbSyncPreference(syncId = syncId)

    override fun updateSyncPreference(syncId: Long, transform: (DbSyncPreference) -> DbSyncPreference): DbSyncPreference {
        val updated = transform(syncPreference(syncId)).copy(syncId = syncId)
        database.upsertSyncPreference(updated)
        return updated
    }

    override fun library(itemType: ItemType): List<Manga> =
        database.mangas(itemType.toDb()).filter { it.favorite && it.parentId == null }.toDomainMangas(database.settings())

    override fun chapters(mangaId: Long): List<Chapter> =
        database.chapters(mangaId).map(::toDomainChapter)

    override fun allChapters(): List<Chapter> =
        database.chapters().map(::toDomainChapter)

    override fun categories(itemType: ItemType): List<Category> =
        database.categories(itemType.toDb()).map { it.toDomain() }

    override fun createCategory(itemType: ItemType, name: String): Category {
        val normalized = name.trim().ifBlank { "New category" }
        val position = database.categories(itemType.toDb()).maxOfOrNull { it.position ?: 0 }?.plus(1) ?: 0
        return database.upsertCategory(
            DbCategory(
                name = normalized,
                forItemType = itemType.toDb(),
                position = position,
                hidden = false,
                shouldUpdate = true,
                updatedAt = nowMillis(),
            ),
        ).toDomain()
    }

    override fun updateCategory(categoryId: Long, name: String?, hidden: Boolean?, shouldUpdate: Boolean?): Category? {
        val current = database.categories().firstOrNull { it.id == categoryId } ?: return null
        return database.upsertCategory(
            current.copy(
                name = name?.trim()?.takeIf { it.isNotBlank() } ?: current.name,
                hidden = hidden ?: current.hidden,
                shouldUpdate = shouldUpdate ?: current.shouldUpdate,
                updatedAt = nowMillis(),
            ),
        ).toDomain()
    }

    override fun moveCategory(itemType: ItemType, categoryId: Long, offset: Int) {
        if (offset == 0) return
        val ordered = database.categories(itemType.toDb()).toMutableList()
        val index = ordered.indexOfFirst { it.id == categoryId }
        if (index < 0) return
        val target = (index + offset).coerceIn(0, ordered.lastIndex)
        if (target == index) return
        val moved = ordered.removeAt(index)
        ordered.add(target, moved)
        ordered.forEachIndexed { position, category ->
            database.upsertCategory(category.copy(position = position, updatedAt = nowMillis()))
        }
    }

    override fun removeCategory(categoryId: Long) = database.batch {
        database.removeCategory(categoryId)
        val settings = database.settings()
        val library = settings.features.library
        val retainedLibrary = library.copy(
            defaultCategoryIds = library.defaultCategoryIds.filterValues { it != categoryId },
            categoryPreferences = library.categoryPreferences.mapValues { (_, preferences) -> preferences - categoryId }
                .filterValues { it.isNotEmpty() },
        )
        if (retainedLibrary != library) {
            database.updateSettings(settings.copy(features = settings.features.copy(
                library = retainedLibrary,
            )))
        }
        database.recordChange(
            eu.friedcutlet.yokan.database.DbChangedPart(
                actionType = eu.friedcutlet.yokan.database.DbActionType.RemoveCategory,
                isarId = categoryId,
                data = "category-$categoryId",
                clientDate = nowMillis(),
            ),
        )
        database.mangas().forEach { manga ->
            if (categoryId in manga.categories.orEmpty()) {
                database.upsertManga(manga.copy(categories = manga.categories.orEmpty() - categoryId, updatedAt = nowMillis()))
            }
        }
    }

    override fun sources(itemType: ItemType): List<Source> =
        database.sources(itemType.toDb()).map { it.toDomain() }

    override fun source(sourceId: Long): Source? = database.source(sourceId)?.toDomain()

    override fun setSourceActive(sourceId: Long, active: Boolean) {
        database.source(sourceId)?.let { source ->
            database.upsertSource(source.copy(isActive = active, updatedAt = nowMillis()))
        }
    }

    override fun setSourcePinned(sourceId: Long, pinned: Boolean) {
        database.source(sourceId)?.let { source ->
            database.upsertSource(source.copy(isPinned = pinned, updatedAt = nowMillis()))
        }
    }

    override fun setSourceAdded(sourceId: Long, added: Boolean) {
        database.source(sourceId)?.let { source ->
            database.upsertSource(source.copy(isAdded = added, isActive = source.isActive || added, updatedAt = nowMillis()))
        }
    }

    override fun markSourceUsed(sourceId: Long) {
        val target = database.source(sourceId) ?: return
        val updatedAt = nowMillis()
        database.sources(target.itemType)
            .filter { source -> source.lastUsed != (source.id == sourceId) }
            .forEach { source ->
                database.upsertSource(
                    source.copy(
                        lastUsed = source.id == sourceId,
                        updatedAt = updatedAt,
                    ),
                )
            }
    }

    override fun updateSourceCode(sourceId: Long, code: String) {
        database.source(sourceId)?.let { source ->
            database.upsertSource(source.copy(sourceCode = code, isFullData = true, updatedAt = nowMillis()))
        }
    }

    override fun removeSource(sourceId: Long) {
        database.removeSource(sourceId)
    }

    override fun repositories(itemType: ItemType): List<DbRepo> = when (itemType) {
        ItemType.Manga -> database.settings().mangaExtensionsRepo.orEmpty()
        ItemType.Anime -> database.settings().animeExtensionsRepo.orEmpty()
        ItemType.Novel -> database.settings().novelExtensionsRepo.orEmpty()
    }

    override fun upsertRepository(itemType: ItemType, repo: DbRepo) {
        val normalizedUrl = SourceRepositoryUrls.normalizeUrl(repo.jsonUrl)
        if (normalizedUrl.isBlank()) return
        val resolvedName = SourceRepositoryUrls.resolveDisplayName(repo.name, normalizedUrl, "${itemType.label} repository")
        val normalized = repo.copy(jsonUrl = normalizedUrl, name = resolvedName)
        val next = repositories(itemType).filterNot { SourceRepositoryUrls.areUrlsEquivalent(it.jsonUrl, normalizedUrl) } + normalized
        database.updateSettings(database.settings().withRepositories(itemType, next))
    }

    override fun removeRepository(itemType: ItemType, jsonUrl: String) {
        val next = repositories(itemType).filterNot { SourceRepositoryUrls.areUrlsEquivalent(it.jsonUrl, jsonUrl) }
        database.updateSettings(database.settings().withRepositories(itemType, next))
    }

    override fun allTitles(itemType: ItemType): List<Manga> =
        database.mangas(itemType.toDb()).toDomainMangas(database.settings())

    override fun manga(mangaId: Long): Manga? = database.manga(mangaId)?.toDomain(database.settings())

    override fun pageUrls(chapterId: Long): List<DbPageUrl> =
        database.pageCache(chapterId).firstOrNull()?.let { cache ->
            val urls = cache.urls.orEmpty()
            val headers = cache.headers.orEmpty()
            // One entry = headers shared by every page (see cachePageUrls).
            val shared = headers.singleOrNull()?.decodePageHeaders()
            urls.mapIndexed { index, url ->
                DbPageUrl(
                    url = url,
                    headers = if (headers.size == 1) shared else headers.getOrNull(index)?.decodePageHeaders(),
                )
            }
        }.orEmpty()

    override fun cachePageUrls(
        chapterId: Long,
        chapterUrl: String,
        pageUrls: List<DbPageUrl>,
        source: DbSource?,
        fetchedAt: Long,
    ) {
        // Cookies are re-added from the cookie jar at request time; nothing re-adds Authorization,
        // so a list that needed it is kept stale and always refetched with live credentials.
        // ponytail: such sources never hit the cache; re-derive their credentials at load time if that matters.
        val headers = pageUrls.map { page -> page.headers.orEmpty().filterKeys { !it.isSensitivePageHeader() } }
        val needsAuthorization = pageUrls.any { page -> page.headers.orEmpty().keys.any { it.equals("Authorization", ignoreCase = true) } }
        val encodedHeaders = if (headers.all { it == headers.first() }) {
            headers.take(1).map { it.encodePageHeaders() }
        } else {
            headers.map { it.encodePageHeaders() }
        }
        database.upsertPageCache(
            eu.friedcutlet.yokan.database.DbChapterPageUrls(
                chapterId = chapterId,
                chapterUrl = chapterUrl,
                urls = pageUrls.map { it.url },
                headers = encodedHeaders,
                fetchedAt = fetchedAt.takeUnless { needsAuthorization },
                sourceId = source?.id,
                sourceVersion = source?.version,
            ),
        )
    }

    override fun clearPageCache() = database.clearPageCache()

    override fun upsertRemoteTitle(source: Source, remote: RemoteManga, favorite: Boolean?): Manga =
        database.ingestRemoteTitle(source, remote, favorite)

    override fun upsertRemoteDetail(source: Source, detail: RemoteDetail, favorite: Boolean?): Manga =
        database.ingestRemoteDetail(source, detail, favorite)

    override fun applyMetadata(mangaId: Long, metadata: MetadataMedia): Manga? {
        val current = database.manga(mangaId) ?: return null
        val now = nowMillis()
        val settings = database.settings()
        val existingMetadata = settings.titleMetadataFor(mangaId)
        val titles = mergedDistinct(
            listOf(current.name.orEmpty()) + existingMetadata?.titles.orEmpty() + metadata.titles,
        )
        val genres = mergedDistinct(current.genre.orEmpty() + metadata.genres)
        val saved = database.upsertManga(
            current.copy(
                name = current.name?.takeIf { it.isNotBlank() } ?: metadata.title,
                imageUrl = current.imageUrl ?: metadata.coverUrl,
                description = current.description?.takeIf { it.isNotBlank() } ?: metadata.description.orEmpty(),
                genre = genres,
                updatedAt = now,
            ),
        )
        database.updateSettings(
            settings.withTitleMetadata(
                DbTitleMetadata(
                    mangaId = mangaId,
                    metadataServerId = metadata.id,
                    metadataSource = metadata.source,
                    titles = titles,
                    updatedAt = now,
                ),
            ),
        )
        return saved.toDomain(database.settings())
    }

    override fun applyLocalMetadataFields(mangaId: Long, metadata: MetadataMedia, fields: Set<LocalMetadataField>): Manga? {
        val current = database.manga(mangaId) ?: return null
        val now = nowMillis()
        val saved = database.upsertManga(
            current.copy(
                name = current.name.takeIf { LocalMetadataField.Title !in fields } ?: metadata.title,
                imageUrl = current.imageUrl.takeIf { LocalMetadataField.Cover !in fields } ?: metadata.coverUrl,
                description = current.description.takeIf { LocalMetadataField.Description !in fields } ?: metadata.description,
                genre = current.genre.takeIf { LocalMetadataField.Genres !in fields } ?: metadata.genres,
                status = current.status.takeIf { LocalMetadataField.Status !in fields }
                    ?: metadata.status?.let { label ->
                        DbStatus.entries.firstOrNull { it.name.equals(label, ignoreCase = true) }
                            ?: when (label.lowercase()) {
                                "ongoing" -> DbStatus.Ongoing
                                "completed", "complete" -> DbStatus.Completed
                                "cancelled", "canceled" -> DbStatus.Canceled
                                "hiatus", "on hiatus" -> DbStatus.OnHiatus
                                else -> DbStatus.Unknown
                            }
                    } ?: current.status,
                updatedAt = now,
            ),
        )
        if (LocalMetadataField.MetadataLink in fields && database.settings().titleMetadata.orEmpty().none { it.mangaId == mangaId }) {
            database.updateSettings(
                database.settings().copy(
                    titleMetadata = database.settings().titleMetadata.orEmpty()
                        .filterNot { it.mangaId == mangaId } + DbTitleMetadata(
                        mangaId = mangaId,
                        metadataServerId = metadata.id,
                        metadataSource = metadata.source,
                        titles = metadata.titles,
                        updatedAt = now,
                    ),
                ),
            )
        }
        return saved.toDomain(database.settings())
    }

    override fun setMangaPrivateNote(mangaId: Long, note: String): Manga? = database.batch {
        val current = database.manga(mangaId)?.takeIf { it.favorite } ?: return@batch null
        // Do not advance sync timestamps for a device-local edit.
        database.upsertManga(current.copy(privateNote = note)).toDomain(database.settings())
    }

    override fun setMangaDisplayTitle(mangaId: Long, title: String): Manga? {
        val trimmed = title.trim().takeIf { it.isNotBlank() } ?: return manga(mangaId)
        val current = database.manga(mangaId) ?: return null
        val settings = database.settings()
        val existingMetadata = settings.titleMetadataFor(mangaId)
        val titles = mergedDistinct(listOf(trimmed, current.name.orEmpty()) + existingMetadata?.titles.orEmpty())
        val saved = database.upsertManga(current.copy(name = trimmed, updatedAt = nowMillis()))
        database.updateSettings(
            settings.withTitleMetadata(
                (existingMetadata ?: DbTitleMetadata(mangaId = mangaId)).copy(
                    titles = titles,
                    updatedAt = nowMillis(),
                ),
            ),
        )
        return saved.toDomain(database.settings())
    }
    override fun setMangaCustomCover(mangaId: Long, bytes: ByteArray): Manga? {
        if (bytes.isEmpty()) return manga(mangaId)
        val current = database.manga(mangaId) ?: return null
        return database.upsertManga(
            current.copy(
                customCoverImage = bytes,
                updatedAt = nowMillis(),
            ),
        ).toDomain(database.settings())
    }

    override fun history(): List<History> =
        database.histories().mapNotNull { history ->
            history.toDomain(history.mangaId?.let(database::manga), history.chapterId?.let(database::chapter))
        }

    override fun updates(): List<UpdateEntry> =
        database.updates().mapNotNull { update ->
            update.toDomain(update.mangaId?.let(database::manga), update.chapterId?.let(database::chapter))
        }

    override fun tracks(): List<Track> = database.tracks().map { it.toDomain() }

    override fun downloads(): List<DbDownload> = database.downloads()

    override fun removeDownload(downloadId: Long) {
        val download = database.downloads().firstOrNull { it.id == downloadId }
        download?.chapterId?.let { chapterId ->
            val chapter = database.chapter(chapterId)
            if (chapter != null && (chapter.downloadSize != null || chapter.archivePath.isNotBlank())) {
                database.upsertChapter(
                    chapter.copy(downloadSize = null, archivePath = "", updatedAt = nowMillis())
                )
            }
        }
        database.removeDownload(downloadId)
    }

    override fun cancelDownload(downloadId: Long) {
        database.downloads().firstOrNull { it.id == downloadId }?.let { download ->
            database.upsertDownload(download.copy(isStartDownload = false))
        }
    }

    override fun clearChapterDownloads(chapterIds: Set<Long>) {
        if (chapterIds.isEmpty()) return
        database.batch {
            val settings = database.settings()
            val policy = settings.features.downloads
            val consumed = policy.consumedChapterIds - chapterIds
            val manual = policy.manuallyMarkedChapterIds - chapterIds
            if (consumed != policy.consumedChapterIds || manual != policy.manuallyMarkedChapterIds) database.updateSettings(settings.copy(features = settings.features.copy(downloads = policy.copy(consumedChapterIds = consumed, manuallyMarkedChapterIds = manual))))
            chapterIds.forEach { chapterId ->
                val chapter = database.chapter(chapterId)
                if (chapter != null && (chapter.downloadSize != null || chapter.archivePath.isNotBlank())) {
                    database.upsertChapter(
                        chapter.copy(downloadSize = null, archivePath = "", updatedAt = nowMillis())
                    )
                }
            }
        }
    }

    override fun setMangaCategories(mangaId: Long, categories: List<Long>, favorite: Boolean) {
        val added = database.batch {
            database.manga(mangaId)?.let { manga ->
                val cleaned = categories.distinct()
                // Assigning any category implies the item is in the library — the
                // detail-screen UX shows "In library" + a category picker side by
                // side, and a category without favorite=true would never appear
                // anywhere in the library tabs.
                val nextFavorite = favorite || manga.favorite || cleaned.isNotEmpty()
                database.upsertManga(
                    manga.copy(
                        categories = cleaned,
                        favorite = nextFavorite,
                        updatedAt = nowMillis(),
                    ),
                )
                nextFavorite && !manga.favorite
            } ?: false
        }
        if (added) trackerAccounts?.addedToLibrary(mangaId)
    }

    override fun setLibraryEntriesRead(mangaIds: Set<Long>, isRead: Boolean) {
        if (mangaIds.isEmpty()) return
        val newlyRead = mutableSetOf<Long>()
        database.batch {
            database.chapters()
                .filter { it.mangaId?.let(mangaIds::contains) == true }
                .forEach { chapter ->
                    val updated = chapter.copy(
                        isRead = isRead,
                        lastPageRead = when {
                            isRead && chapter.lastPageRead.isBlank() -> "1"
                            !isRead -> ""
                            else -> chapter.lastPageRead
                        },
                    )
                    if (updated != chapter) database.upsertChapter(updated)
                    if (isRead && !chapter.isRead) chapter.mangaId?.let(newlyRead::add)
                }
        }
        emitRead(newlyRead)
        downloadAutomation?.chaptersMarked(database.chapters().filter { it.mangaId in mangaIds }.mapTo(mutableSetOf()) { it.id }, isRead, consumed = false)
    }

    override fun chapterOpened(chapterId: Long) {
        downloadAutomation?.chapterOpened(chapterId)
        if (database.settings().incognitoMode) return
        database.chapter(chapterId)?.mangaId?.let(database::manga)?.let { onSyncTrigger(SyncTriggerKind.opened(it.itemType)) }
    }

    private fun emitRead(mangaIds: Collection<Long>) =
        mangaIds.mapNotNullTo(mutableSetOf()) { database.manga(it)?.itemType }.forEach { onSyncTrigger(SyncTriggerKind.read(it)) }

    override fun chapterClosed(chapterId: Long) { downloadAutomation?.chapterClosed(chapterId) }
    override fun recordChapterConsumption(chapterIds: Set<Long>) {
        if (!database.settings().incognitoMode) downloadAutomation?.chaptersMarked(
            chapterIds.filterTo(mutableSetOf()) { database.chapter(it)?.isRead == true }, true, consumed = true,
        )
    }

    override fun setChaptersRead(
        chapterIds: Set<Long>,
        isRead: Boolean,
        lastPageRead: String?,
        readingTimeSeconds: Int,
        autoReadDuplicates: Boolean,
    ) {
        if (chapterIds.isEmpty() || database.settings().incognitoMode) return
        val progressed = mutableSetOf<Long>()
        chapterIds.mapNotNull(database::chapter).forEach { chapter ->
            val updated = database.upsertChapter(
                chapter.copy(
                    isRead = isRead,
                    lastPageRead = when {
                        lastPageRead != null -> lastPageRead
                        isRead && chapter.lastPageRead.isBlank() -> "1"
                        !isRead -> ""
                        else -> chapter.lastPageRead
                    },
                    updatedAt = nowMillis(),
                ),
            )
            val manga = updated.mangaId?.let(database::manga)
            if (autoReadDuplicates && isRead && !chapter.isRead && manga != null) {
                val episodeKey = eu.friedcutlet.yokan.domain.chapterReleaseKey(manga.name.orEmpty(), chapter.name.orEmpty(), number = chapter.number, season = chapter.season, numberingName = chapter.numberingName)
                if (episodeKey != null) {
                    database.chapters(manga.id)
                        .asSequence()
                        .filter { sibling -> sibling.id != chapter.id && !sibling.isRead }
                        .filter { sibling ->
                            eu.friedcutlet.yokan.domain.chapterReleaseKey(manga.name.orEmpty(), sibling.name.orEmpty(), number = sibling.number, season = sibling.season, numberingName = sibling.numberingName) == episodeKey
                        }
                        .forEach { sibling ->
                            database.upsertChapter(
                                sibling.copy(
                                    isRead = true,
                                    lastPageRead = "1",
                                    updatedAt = nowMillis(),
                                ),
                            )
                        }
                }
            }
            // Record / refresh a history entry on every progress save (not just
            // on completion). Opening or advancing a chapter updates the
            // "Last read" row so the user can resume mid-chapter.
            val progressing = lastPageRead != null || isRead
            if (manga != null && progressing) {
                database.upsertManga(manga.copy(lastRead = nowMillis(), updatedAt = nowMillis()))
                // Collapse history to ONE row per manga. Older per-chapter rows
                // get folded into a single entry that points at the most recent
                // chapter — total reading time is carried forward so the
                // Statistics screen-time stat stays monotonic across chapters.
                val allForManga = database.histories().filter { it.mangaId == manga.id }
                val carryReadingTime = allForManga.sumOf { it.readingTimeSeconds ?: 0 }
                val keptId = allForManga.maxByOrNull { it.updatedAt }?.id ?: 0L
                database.upsertHistory(
                    DbHistory(
                        id = keptId,
                        mangaId = manga.id,
                        chapterId = updated.id,
                        itemType = manga.itemType,
                        date = "Now",
                        updatedAt = nowMillis(),
                        readingTimeSeconds = carryReadingTime + readingTimeSeconds,
                    ),
                )
                allForManga.filter { it.id != keptId }.forEach { database.removeHistory(it.id) }
            }
            if (isRead && !chapter.isRead && manga != null) {
                val readCount = database.chapters(manga.id).count { it.isRead }
                // Progress never moves backwards on marking read (Animetail TrackChapter); remote pushes follow.
                database.tracks(manga.id).forEach { track ->
                    database.upsertTrack(track.copy(lastChapterRead = maxOf(track.lastChapterRead ?: 0, readCount), updatedAt = nowMillis()))
                }
                progressed += manga.id
            }
        }
        if (lastPageRead == null) downloadAutomation?.chaptersMarked(chapterIds, isRead, consumed = false)
        progressed.forEach { trackerAccounts?.progressed(it) }
        emitRead(progressed)
    }

    override fun setChaptersBookmarked(chapterIds: Set<Long>, bookmarked: Boolean) {
        if (chapterIds.isEmpty()) return
        database.batch {
            chapterIds.mapNotNull(database::chapter).forEach { chapter ->
                database.upsertChapter(chapter.copy(isBookmarked = bookmarked, updatedAt = nowMillis()))
            }
        }
    }

    override fun setChaptersFillerOverride(chapterIds: Set<Long>, filler: Boolean?) {
        if (chapterIds.isEmpty()) return
        database.batch {
            chapterIds.mapNotNull(database::chapter).filter { it.fillerOverride != filler }.forEach { chapter ->
                database.upsertChapter(chapter.copy(fillerOverride = filler, updatedAt = nowMillis()))
            }
        }
    }

    override fun setMangaFavorite(mangaId: Long, favorite: Boolean) {
        val added = database.batch {
            database.manga(mangaId)?.let { manga ->
                // Removing from library clears categories so a stale category
                // assignment can't keep an item visible in a category tab after
                // the user's already taken it out of the library.
                val defaultId = database.settings().features.library.defaultCategory(manga.itemType)
                val nextCategories = when {
                    !favorite -> emptyList()
                    !manga.favorite && manga.categories.isNullOrEmpty() && defaultId != null && defaultId > 0 &&
                        database.categories(manga.itemType).any { it.id == defaultId } -> listOf(defaultId)
                    else -> manga.categories
                }
                database.upsertManga(
                    manga.copy(
                        favorite = favorite,
                        categories = nextCategories,
                        updatedAt = nowMillis(),
                    ),
                )
                favorite && !manga.favorite
            } ?: false
        }
        if (added) trackerAccounts?.addedToLibrary(mangaId)
    }

    override fun setMangaSmartUpdateDays(mangaId: Long, days: Int?) {
        database.manga(mangaId)?.let { manga ->
            database.upsertManga(manga.copy(smartUpdateDays = days, updatedAt = nowMillis()))
        }
    }

    override fun removeLibraryEntries(mangaIds: Set<Long>) {
        if (mangaIds.isEmpty()) return
        database.batch {
            database.mangas()
                .filter { it.id in mangaIds }
                .forEach { manga ->
                    database.upsertManga(manga.copy(favorite = false))
                }
        }
    }

    override fun deleteChapters(chapterIds: Set<Long>) {
        if (chapterIds.isEmpty()) return
        database.batch {
            chapterIds.forEach { chapterId ->
                database.removeChapter(chapterId)
            }
        }
    }

    override fun setUpdateRead(updateId: Long, isRead: Boolean) {
        database.updates().firstOrNull { it.id == updateId }?.chapterId?.let(database::chapter)?.let { chapter ->
            database.upsertChapter(chapter.copy(isRead = isRead, updatedAt = nowMillis()))
            if (isRead && !chapter.isRead) chapter.mangaId?.let { emitRead(listOf(it)) }
        }
    }

    override fun clearUpdates(itemType: ItemType) {
        val dbType = itemType.toDb()
        database.batch {
            database.updates()
                .filter { update ->
                    val mangaId = update.mangaId
                        ?: update.chapterId?.let(database::chapter)?.mangaId
                        ?: return@filter false
                    database.manga(mangaId)?.itemType == dbType
                }
                .forEach { database.removeUpdate(it.id) }
        }
    }

    override fun removeHistory(historyId: Long) {
        database.removeHistory(historyId)
    }

    override fun clearHistory(itemType: ItemType) {
        val dbType = itemType.toDb()
        database.batch {
            database.histories()
                .filter { history -> history.itemType == dbType }
                .forEach { database.removeHistory(it.id) }
        }
    }

    override fun clearLibrary(itemType: ItemType) {
        database.batch {
            database.mangas(itemType.toDb()).forEach { manga ->
                database.upsertManga(manga.copy(favorite = false, updatedAt = nowMillis()))
            }
        }
    }

    override fun clearLocalLibrary(): Int = database.batch {
        val localMangas = database.mangas().filter { manga ->
            manga.source?.lowercase() in setOf("local", "archive")
        }
        if (localMangas.isEmpty()) return@batch 0

        val mangaIds = localMangas.mapTo(mutableSetOf()) { it.id }
        val chapters = database.chapters().filter { it.mangaId in mangaIds }
        val chapterIds = chapters.mapTo(mutableSetOf()) { it.id }

        database.histories()
            .filter { it.mangaId in mangaIds || it.chapterId in chapterIds }
            .forEach { database.removeHistory(it.id) }
        database.updates()
            .filter { it.mangaId in mangaIds || it.chapterId in chapterIds }
            .forEach { database.removeUpdate(it.id) }
        database.downloads()
            .filter { it.chapterId in chapterIds }
            .forEach { database.removeDownload(it.id) }
        chapters.forEach { database.removeChapter(it.id) }
        localMangas.forEach { database.removeManga(it.id) }
        localMangas.size
    }

    override fun cleanDatabase(): Int = database.batch {
        // Remove cached entries that aren't in the library (not favorited) along
        // with their chapter rows, freeing the space they take up. Retain private notes.
        val mangas = database.mangas()
        val seasons = mangas.seasonsOwnedByLibrary()
        val orphans = mangas.filter { !it.favorite && it.privateNote.isEmpty() && it.id !in seasons }
        orphans.forEach { manga ->
            database.chapters(manga.id).forEach { chapter -> database.removeChapter(chapter.id) }
            database.removeManga(manga.id)
        }
        orphans.size
    }

    override fun pruneBrowsedTitles(): Int {
        // Like cleanDatabase, but keeps anything the user interacted with:
        // titles with history, downloaded chapters, or a bound tracker.
        val snapshot = database.snapshot()
        val chapterOwner = snapshot.chapters.associate { it.id to it.mangaId }
        val keptIds = buildSet<Long> {
            snapshot.histories.forEach { history ->
                history.mangaId?.let(::add)
                history.chapterId?.let { chapterOwner[it] }?.let(::add)
            }
            snapshot.tracks.forEach { track -> track.mangaId?.let(::add) }
            snapshot.downloads.forEach { download ->
                download.chapterId?.let { chapterOwner[it] }?.let(::add)
            }
        }
        val seasons = snapshot.mangas.seasonsOwnedByLibrary()
        val staleIds = snapshot.mangas
            .filter { !it.favorite && it.privateNote.isEmpty() && it.id !in keptIds && it.id !in seasons }
            .mapTo(mutableSetOf()) { it.id }
        if (staleIds.isEmpty()) return 0
        // Bulk replace: a prune can touch thousands of rows, and per-row
        // removes emit a full snapshot copy each.
        try {
            database.replaceAll(
                snapshot.copy(
                    mangas = snapshot.mangas.filter { it.id !in staleIds },
                    chapters = snapshot.chapters.filter { it.mangaId == null || it.mangaId !in staleIds },
                ),
                expectedSnapshot = snapshot,
            )
        } catch (_: SnapshotReplacementConflictException) {
            return 0
        }
        return staleIds.size
    }

    override fun bindTrack(mangaId: Long, search: DbTrackSearch, itemType: ItemType) {
        val track = database.upsertTrack(search.toDbTrack(mangaId, itemType.toDb()))
        trackerAccounts?.bound(track.id)
    }

    override fun updateTrack(trackId: Long, progress: Int, status: DbTrackStatus, score: Int) {
        database.tracks().firstOrNull { it.id == trackId }?.let { track ->
            database.upsertTrack(
                track.copy(
                    lastChapterRead = progress.coerceAtLeast(0),
                    status = status,
                    score = score.coerceIn(0, 10),
                    updatedAt = nowMillis(),
                ),
            )
            trackerAccounts?.updated(trackId)
        }
    }

    override fun removeTrack(trackId: Long, removeRemote: Boolean) {
        val track = database.tracks().firstOrNull { it.id == trackId }
        database.removeTrack(trackId)
        if (removeRemote && track != null) trackerAccounts?.removed(track)
    }

    override fun refreshTracks(mangaId: Long) {
        trackerAccounts?.refresh(mangaId)
    }
}

private fun DbSettings.withRepositories(itemType: ItemType, repos: List<DbRepo>): DbSettings = when (itemType) {
    ItemType.Manga -> copy(mangaExtensionsRepo = repos)
    ItemType.Anime -> copy(animeExtensionsRepo = repos)
    ItemType.Novel -> copy(novelExtensionsRepo = repos)
}

private fun DbSettings.withTitleMetadata(metadata: DbTitleMetadata): DbSettings =
    copy(
        titleMetadata = titleMetadata.orEmpty()
            .filterNot { it.mangaId == metadata.mangaId } + metadata,
    )

private val pageHeadersJson = Json

/** Credentials are never written to the page cache. */
private fun String.isSensitivePageHeader(): Boolean =
    equals("Cookie", ignoreCase = true) || equals("Authorization", ignoreCase = true)

private fun Map<String, String>.encodePageHeaders(): String =
    if (isEmpty()) "" else pageHeadersJson.encodeToString(this)

private fun String.decodePageHeaders(): Map<String, String>? {
    if (isBlank()) return null
    if (!trimStart().startsWith('{')) return mapOf("User-Agent" to this)
    return runCatching { pageHeadersJson.decodeFromString<Map<String, String>>(this) }
        .getOrNull()
        ?.ifEmpty { null }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/LibraryIndex.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/LibraryIndex.kt) · implementation · 103 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
24: class LibraryIndex(
34: fun chapters(mangaId: Long): List<Chapter> = chaptersByManga[mangaId].orEmpty()
42: data class LibraryTrack(val providerId: Int?, val status: DbTrackStatus, val score: Int?, val scoreMaximum: Int? = trackerScoreMaximum(providerId))
44: private fun libraryTracks(tracks: List<DbTrack>, scales: Map<Int, IntRange>): Map<Long, List<LibraryTrack>> =
48: internal fun buildCompletedDownloadCountsByChapterId(downloads: List<DbDownload>): Map<Long, Int> =
59: class LibraryIndexStore(repository: YokanRepository, scope: CoroutineScope, dispatcher: CoroutineDispatcher = Dispatchers.Default,
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/LibraryIndex.kt) · SHA-256 `08ca5b2389f6308c25432e87c2bc0a53e3720b9e70f58a4fadaae3761830fd51`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.tracking.trackerScoreMaximum
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.stateIn

/**
 * Whole-library lookups grouped once per data change instead of once per composition.
 *
 * A plain class on purpose: equality is identity, so publishing a rebuilt index never deep-compares
 * hundreds of thousands of chapters.
 */
class LibraryIndex(
    val chaptersByManga: Map<Long, List<Chapter>> = emptyMap(),
    /** Chapter id → number of completed download records. */
    val completedDownloadCountsByChapterId: Map<Long, Int> = emptyMap(),
    val trackedMangaIds: Set<Long> = emptySet(),
    val tracksByManga: Map<Long, List<LibraryTrack>> = emptyMap(),
) {
    val downloadedChapterIds: Set<Long> get() = completedDownloadCountsByChapterId.keys

    /** The title's chapters in database order; sort them with the chapter sort helpers. */
    fun chapters(mangaId: Long): List<Chapter> = chaptersByManga[mangaId].orEmpty()

    companion object {
        val Empty = LibraryIndex()
    }
}

/** Only library-relevant track fields; token/account and refresh timestamps never enter this index. */
data class LibraryTrack(val providerId: Int?, val status: DbTrackStatus, val score: Int?, val scoreMaximum: Int? = trackerScoreMaximum(providerId))

private fun libraryTracks(tracks: List<DbTrack>, scales: Map<Int, IntRange>): Map<Long, List<LibraryTrack>> =
    tracks.filter { it.mangaId != null }.groupBy { requireNotNull(it.mangaId) }
        .mapValues { (_, rows) -> rows.map { LibraryTrack(it.syncId, it.status, it.score, scales[it.syncId]?.last ?: trackerScoreMaximum(it.syncId)) } }

internal fun buildCompletedDownloadCountsByChapterId(downloads: List<DbDownload>): Map<Long, Int> =
    downloads.asSequence()
        .filter { it.isDownload == true }
        .mapNotNull { it.chapterId }
        .groupingBy { it }
        .eachCount()

/**
 * Publishes [LibraryIndex] rebuilt on [Dispatchers.Default]. Each part is regrouped only when its
 * snapshot list changed, so download-progress writes never regroup the chapters.
 */
class LibraryIndexStore(repository: YokanRepository, scope: CoroutineScope, dispatcher: CoroutineDispatcher = Dispatchers.Default,
    private val trackerScoreRanges: Map<Int, IntRange> = emptyMap()) {
    val index: StateFlow<LibraryIndex> = flow {
        var chapters: List<DbChapter>? = null
        var downloads: List<DbDownload>? = null
        var tracks: List<DbTrack>? = null
        var current = LibraryIndex.Empty
        // StateFlow collection is conflated: a slow rebuild skips to the newest snapshot.
        repository.snapshots.collect { snapshot ->
            if (snapshot.chapters === chapters && snapshot.downloads === downloads && snapshot.tracks === tracks) {
                return@collect
            }
            val next = LibraryIndex(
                chaptersByManga = if (snapshot.chapters === chapters) {
                    current.chaptersByManga
                } else {
                    snapshot.chapters.map(::toDomainChapter).groupBy { it.mangaId }
                },
                completedDownloadCountsByChapterId = if (snapshot.downloads === downloads) {
                    current.completedDownloadCountsByChapterId
                } else {
                    buildCompletedDownloadCountsByChapterId(snapshot.downloads)
                },
                trackedMangaIds = if (snapshot.tracks === tracks) {
                    current.trackedMangaIds
                } else {
                    snapshot.tracks.mapTo(HashSet()) { it.mangaId ?: 0L }
                },
                tracksByManga = if (snapshot.tracks === tracks) current.tracksByManga else libraryTracks(snapshot.tracks, trackerScoreRanges),
            )
            chapters = snapshot.chapters
            downloads = snapshot.downloads
            tracks = snapshot.tracks
            if (current === LibraryIndex.Empty || next.chaptersByManga !== current.chaptersByManga ||
                next.completedDownloadCountsByChapterId != current.completedDownloadCountsByChapterId ||
                next.trackedMangaIds != current.trackedMangaIds || next.tracksByManga != current.tracksByManga
            ) {
                current = next
                emit(current)
            }
        }
    }
        .flowOn(dispatcher)
        .stateIn(scope, SharingStarted.Eagerly, LibraryIndex.Empty)
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/RemoteTitleIngest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/RemoteTitleIngest.kt) · implementation · 134 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
18: internal fun YokanDatabase.ingestRemoteTitle(source: Source, remote: RemoteManga, favorite: Boolean?): Manga {
46: internal fun YokanDatabase.ingestRemoteDetail(source: Source, detail: RemoteDetail, favorite: Boolean?): Manga = batch {
81: private fun YokanDatabase.findExistingRemote(source: Source, url: String): DbManga? {
87: private fun YokanDatabase.upsertRemoteChapters(mangaId: Long, remote: List<RemoteChapter>) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/RemoteTitleIngest.kt) · SHA-256 `f625b86a1ab687fb56e8779f08033623962b94f20412f61db54a6936d9f35c72`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbFetchType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.domain.chapterReleaseKey
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.normalizeSourceCast
import eu.friedcutlet.yokan.util.nowMillis

// Writes extension (browse/detail) results into the library, keeping local-only fields.

internal fun YokanDatabase.ingestRemoteTitle(source: Source, remote: RemoteManga, favorite: Boolean?): Manga {
    val existing = findExistingRemote(source, remote.url)
    val now = nowMillis()
    val saved = upsertManga(
        (existing ?: DbManga()).copy(
            name = remote.title,
            link = remote.url,
            imageUrl = remote.thumbnailUrl ?: existing?.imageUrl,
            description = remote.description ?: existing?.description.orEmpty(),
            itemType = source.itemType.toDb(),
            genre = existing?.genre.orEmpty(),
            favorite = favorite ?: existing?.favorite ?: false,
            source = source.name,
            lang = source.lang,
            dateAdded = existing?.dateAdded ?: now,
            lastUpdate = now,
            categories = existing?.categories.orEmpty(),
            isLocalArchive = source.baseUrl.startsWith("file://") || existing?.isLocalArchive == true,
            customCoverImage = existing?.customCoverImage,
            customCoverFromTracker = existing?.customCoverFromTracker,
            smartUpdateDays = existing?.smartUpdateDays,
            sourceId = source.id,
            updatedAt = now,
        ),
    )
    return saved.toDomain(settings())
}

internal fun YokanDatabase.ingestRemoteDetail(source: Source, detail: RemoteDetail, favorite: Boolean?): Manga = batch {
    val existing = findExistingRemote(source, detail.url)
    val now = nowMillis()
    val saved = upsertManga(
        (existing ?: DbManga()).copy(
            name = detail.title,
            link = detail.url,
            imageUrl = detail.thumbnailUrl ?: existing?.imageUrl,
            description = detail.description.ifBlank { existing?.description.orEmpty() },
            author = detail.author ?: existing?.author,
            artist = detail.artist ?: existing?.artist,
            cast = detail.cast?.let { normalizeSourceCast(it, source.baseUrl) }
                ?: existing?.cast.orEmpty(),
            itemType = source.itemType.toDb(),
            genre = existing?.genre.orEmpty(),
            favorite = favorite ?: existing?.favorite ?: false,
            source = source.name,
            lang = source.lang,
            dateAdded = existing?.dateAdded ?: now,
            lastUpdate = now,
            categories = existing?.categories.orEmpty(),
            isLocalArchive = source.baseUrl.startsWith("file://") || existing?.isLocalArchive == true,
            customCoverImage = existing?.customCoverImage,
            customCoverFromTracker = existing?.customCoverFromTracker,
            smartUpdateDays = existing?.smartUpdateDays,
            sourceId = source.id,
            fetchType = if (detail.seasons != null) DbFetchType.Seasons else DbFetchType.Episodes,
            updatedAt = now,
        ),
    )
    if (detail.seasons != null) upsertSeasonRecords(saved, detail.seasons, now)
    else upsertRemoteChapters(saved.id, detail.chapters)
    saved.toDomain(settings())
}

private fun YokanDatabase.findExistingRemote(source: Source, url: String): DbManga? {
    val candidates = mangas(source.itemType.toDb()).filter { it.link == url }
    return candidates.firstOrNull { it.sourceId == source.id }
        ?: candidates.firstOrNull { it.sourceId == null && it.source == source.name }
}

private fun YokanDatabase.upsertRemoteChapters(mangaId: Long, remote: List<RemoteChapter>) {
    if (remote.isEmpty()) return
    val mangaTitle = manga(mangaId)?.name.orEmpty()
    val existingChapters = chapters(mangaId)
    val existingByUrl = existingChapters.associateBy { it.url }
    val existingByComposite = existingChapters.mapNotNull { c ->
        chapterReleaseKey(mangaTitle, c.name, c.scanlator, c.number, c.season, c.numberingName)?.let { it to c }
    }.toMap()
    val readByEpisode = existingChapters.filter { it.isRead }.mapNotNull { c ->
        chapterReleaseKey(mangaTitle, c.name, number = c.number, season = c.season, numberingName = c.numberingName)
    }.toSet()

    val seenUrls = mutableSetOf<String>()
    val seenCompositeKeys = mutableSetOf<String>()

    remote.forEach { chapter ->
        val compositeKey = chapterReleaseKey(mangaTitle, chapter.title, chapter.scanlator)
        val episodeKey = chapterReleaseKey(mangaTitle, chapter.title)

        if (!seenUrls.add(chapter.url)) return@forEach
        if (compositeKey != null && !seenCompositeKeys.add(compositeKey)) return@forEach

        val existing = existingByUrl[chapter.url] ?: compositeKey?.let { existingByComposite[it] }
        val carryRead = existing?.isRead ?: (episodeKey != null && episodeKey in readByEpisode)

        val next = (existing ?: DbChapter()).copy(
            mangaId = mangaId,
            name = chapter.title,
            url = chapter.url,
            dateUpload = chapter.dateUpload,
            scanlator = chapter.scanlator,
            isBookmarked = existing?.isBookmarked ?: false,
            isRead = carryRead,
            lastPageRead = existing?.lastPageRead ?: if (carryRead) "1" else "",
            archivePath = existing?.archivePath.orEmpty(),
            isFiller = existing?.isFiller ?: false,
            thumbnailUrl = existing?.thumbnailUrl,
            description = existing?.description,
            downloadSize = existing?.downloadSize,
            duration = existing?.duration,
            fetchedAt = existing?.fetchedAt ?: nowMillis(),
            updatedAt = existing?.updatedAt ?: 0,
        )
        // An unchanged chapter is not rewritten: `updatedAt` is a synced path, so bumping it
        // alone would cost a write and a hub op per chapter on every refresh.
        if (next != existing) upsertChapter(next.copy(updatedAt = nowMillis()))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/SeasonRecords.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/SeasonRecords.kt) · implementation · 41 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
13: internal fun YokanDatabase.upsertSeasonRecords(parent: DbManga, seasons: List<RemoteManga>, now: Long): List<DbManga> {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/SeasonRecords.kt) · SHA-256 `98c76be9c247c5bf6b3a8e84624f9b14f9ae3eea240b29d2628cca95498e36f6`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbFetchType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.extensions.RemoteManga

/**
 * Writes the Animetail season records of a Seasons-type [parent]; call inside `database.batch`.
 * Each season is its own title linked by [DbManga.parentId]; favorites, covers and progress stay.
 * Seasons absent from a response are kept, so a partial source reply never drops progress.
 */
internal fun YokanDatabase.upsertSeasonRecords(parent: DbManga, seasons: List<RemoteManga>, now: Long): List<DbManga> {
    val byLink = mangas(parent.itemType)
        .filter { it.id != parent.id && it.sourceId == parent.sourceId && it.source == parent.source }
        .groupBy { it.link }
    return seasons.map { season ->
        val candidates = byLink[season.url].orEmpty()
        // A previously browsed, non-library title with the season's URL becomes the season record.
        val existing = candidates.firstOrNull { it.parentId == parent.id }
            ?: candidates.firstOrNull { it.parentId == null && !it.favorite }
        val next = (existing ?: DbManga()).copy(
            name = season.title,
            link = season.url,
            imageUrl = season.thumbnailUrl ?: existing?.imageUrl,
            description = season.description ?: existing?.description,
            itemType = parent.itemType,
            source = parent.source,
            sourceId = parent.sourceId,
            lang = parent.lang,
            isLocalArchive = parent.isLocalArchive,
            parentId = parent.id,
            seasonNumber = season.seasonNumber ?: existing?.seasonNumber,
            fetchType = if (season.fetchesSeasons) DbFetchType.Seasons else existing?.fetchType ?: DbFetchType.Episodes,
            favorite = existing?.favorite ?: false,
            dateAdded = existing?.dateAdded ?: now,
            lastUpdate = existing?.lastUpdate ?: now,
        )
        if (existing != null && next == existing) existing else upsertManga(next.copy(updatedAt = now))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/SettingsStore.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/SettingsStore.kt) · implementation · 76 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
22: class SettingsStore(
55: fun updateDb(transform: (DbSettings) -> DbSettings) {
60: fun update(transform: (UserSettings) -> UserSettings) {
67: fun updateSync(transform: (DbSyncPreference) -> DbSyncPreference) {
72: private fun publishSettings(settings: DbSettings) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/SettingsStore.kt) · SHA-256 `0c6cb1ef8fcd5ac91b29614a140baf562c6b02d14587371705727a86ff516ff4`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.domain.UserSettings
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch

/**
 * App-wide settings holder. Updates persist through [repository] and publish synchronously, so
 * text fields bound to a setting never lag; external writes (sync, restore, background jobs) are
 * picked up from the database snapshots. Safe to call from any thread.
 *
 * [onSchedulingChanged] runs after every [updateDb]/[updateSync]; the receiver decides whether the
 * periodic-task schedule actually changed.
 */
class SettingsStore(
    private val repository: YokanRepository,
    scope: CoroutineScope,
    private val onSchedulingChanged: () -> Unit,
) {
    // Serializes read-transform-write and publication, so a late snapshot can never overwrite a
    // newer value published by an update.
    private val lock = PlatformLock()

    private val _db = MutableStateFlow(repository.dbSettings())
    val db: StateFlow<DbSettings> = _db.asStateFlow()

    private val _user = MutableStateFlow(repository.settings())
    val user: StateFlow<UserSettings> = _user.asStateFlow()

    private val _sync = MutableStateFlow(repository.syncPreference())
    val sync: StateFlow<DbSyncPreference> = _sync.asStateFlow()

    init {
        scope.launch {
            repository.snapshots
                .distinctUntilChanged { old, new ->
                    old.settings === new.settings && old.syncPreferences === new.syncPreferences
                }
                .collect {
                    lock.withLock {
                        publishSettings(repository.dbSettings())
                        _sync.value = repository.syncPreference()
                    }
                }
        }
    }

    fun updateDb(transform: (DbSettings) -> DbSettings) {
        lock.withLock { publishSettings(repository.updateDbSettings(transform)) }
        onSchedulingChanged()
    }

    fun update(transform: (UserSettings) -> UserSettings) {
        lock.withLock {
            repository.updateSettings(transform)
            publishSettings(repository.dbSettings())
        }
    }

    fun updateSync(transform: (DbSyncPreference) -> DbSyncPreference) {
        lock.withLock { _sync.value = repository.updateSyncPreference(transform = transform) }
        onSchedulingChanged()
    }

    private fun publishSettings(settings: DbSettings) {
        _db.value = settings
        _user.value = settings.toDomain()
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/YokanRepository.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/YokanRepository.kt) · implementation · 172 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
34: interface YokanRepository {
36: fun settings(): UserSettings
37: fun dbSettings(): DbSettings
38: fun updateSettings(transform: (UserSettings) -> UserSettings): UserSettings
39: fun updateDbSettings(transform: (DbSettings) -> DbSettings): DbSettings
40: fun syncPreference(syncId: Long = 1): DbSyncPreference
41: fun updateSyncPreference(syncId: Long = 1, transform: (DbSyncPreference) -> DbSyncPreference): DbSyncPreference
42: fun library(itemType: ItemType): List<Manga>
43: fun chapters(mangaId: Long): List<Chapter>
50: fun allChapters(): List<Chapter>
51: fun categories(itemType: ItemType): List<Category>
52: fun createCategory(itemType: ItemType, name: String): Category
53: fun updateCategory(categoryId: Long, name: String? = null, hidden: Boolean? = null, shouldUpdate: Boolean? = null): Category?
54: fun moveCategory(itemType: ItemType, categoryId: Long, offset: Int)
55: fun removeCategory(categoryId: Long)
56: fun sources(itemType: ItemType): List<Source>
57: fun source(sourceId: Long): Source?
58: fun setSourceActive(sourceId: Long, active: Boolean)
59: fun setSourcePinned(sourceId: Long, pinned: Boolean)
60: fun setSourceAdded(sourceId: Long, added: Boolean)
61: fun markSourceUsed(sourceId: Long)
62: fun updateSourceCode(sourceId: Long, code: String)
63: fun removeSource(sourceId: Long)
64: fun repositories(itemType: ItemType): List<DbRepo>
65: fun upsertRepository(itemType: ItemType, repo: DbRepo)
66: fun removeRepository(itemType: ItemType, jsonUrl: String)
67: fun allTitles(itemType: ItemType): List<Manga>
68: fun manga(mangaId: Long): Manga?
69: fun history(): List<History>
70: fun updates(): List<UpdateEntry>
71: fun tracks(): List<Track>
72: fun downloads(): List<DbDownload>
73: fun removeDownload(downloadId: Long)
74: fun cancelDownload(downloadId: Long)
75: fun clearChapterDownloads(chapterIds: Set<Long>)
77: fun pageUrls(chapterId: Long): List<DbPageUrl>
80: fun cachePageUrls(
87: fun clearPageCache()
88: fun upsertRemoteTitle(source: Source, remote: RemoteManga, favorite: Boolean? = null): Manga
89: fun upsertRemoteDetail(source: Source, detail: RemoteDetail, favorite: Boolean? = null): Manga
90: fun applyMetadata(mangaId: Long, metadata: MetadataMedia): Manga?
91: fun applyLocalMetadataFields(mangaId: Long, metadata: MetadataMedia, fields: Set<LocalMetadataField>): Manga?
93: fun setMangaPrivateNote(mangaId: Long, note: String): Manga?
94: fun setMangaDisplayTitle(mangaId: Long, title: String): Manga?
95: fun setMangaCustomCover(mangaId: Long, bytes: ByteArray): Manga?
97: fun setMangaCategories(mangaId: Long, categories: List<Long>, favorite: Boolean = false)
98: fun setLibraryEntriesRead(mangaIds: Set<Long>, isRead: Boolean)
100: fun chapterOpened(chapterId: Long) = Unit
101: fun chapterClosed(chapterId: Long) = Unit
103: fun recordChapterConsumption(chapterIds: Set<Long>) = Unit
104: fun setChaptersRead(
111: fun setChaptersBookmarked(chapterIds: Set<Long>, bookmarked: Boolean)
113: fun setChaptersFillerOverride(chapterIds: Set<Long>, filler: Boolean?)
114: fun setMangaFavorite(mangaId: Long, favorite: Boolean)
121: fun setMangaSmartUpdateDays(mangaId: Long, days: Int?)
122: fun removeLibraryEntries(mangaIds: Set<Long>)
123: fun deleteChapters(chapterIds: Set<Long>)
124: fun setUpdateRead(updateId: Long, isRead: Boolean)
125: fun clearUpdates(itemType: ItemType)
126: fun removeHistory(historyId: Long)
127: fun clearHistory(itemType: ItemType)
128: fun clearLibrary(itemType: ItemType)
130: fun clearLocalLibrary(): Int
136: fun cleanDatabase(): Int
143: fun pruneBrowsedTitles(): Int
145: fun bindTrack(mangaId: Long, search: DbTrackSearch, itemType: ItemType)
146: fun updateTrack(trackId: Long, progress: Int, status: DbTrackStatus, score: Int)
149: fun removeTrack(trackId: Long, removeRemote: Boolean = false)
152: fun refreshTracks(mangaId: Long) {}
161: fun <K, T> YokanRepository.observe(
168: fun <K, T> YokanRepository.observeSnapshot(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/YokanRepository.kt) · SHA-256 `c0b9e621dbb17036f5e991aac2359a845fb56d5dc695b637ca509c87486661f7`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import kotlin.coroutines.CoroutineContext
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbRepo
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.History
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.domain.Track
import eu.friedcutlet.yokan.domain.UpdateEntry
import eu.friedcutlet.yokan.domain.UserSettings
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.metadata.LocalMetadataField
import eu.friedcutlet.yokan.services.metadata.MetadataMedia
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map

interface YokanRepository {
    val snapshots: StateFlow<YokanDatabaseSnapshot>
    fun settings(): UserSettings
    fun dbSettings(): DbSettings
    fun updateSettings(transform: (UserSettings) -> UserSettings): UserSettings
    fun updateDbSettings(transform: (DbSettings) -> DbSettings): DbSettings
    fun syncPreference(syncId: Long = 1): DbSyncPreference
    fun updateSyncPreference(syncId: Long = 1, transform: (DbSyncPreference) -> DbSyncPreference): DbSyncPreference
    fun library(itemType: ItemType): List<Manga>
    fun chapters(mangaId: Long): List<Chapter>

    /**
     * Returns every chapter in one call. Filter / sort paths that iterate
     * the entire library use this once and group by mangaId in-memory —
     * cheaper than 6 000 separate `chapters(id)` calls.
     */
    fun allChapters(): List<Chapter>
    fun categories(itemType: ItemType): List<Category>
    fun createCategory(itemType: ItemType, name: String): Category
    fun updateCategory(categoryId: Long, name: String? = null, hidden: Boolean? = null, shouldUpdate: Boolean? = null): Category?
    fun moveCategory(itemType: ItemType, categoryId: Long, offset: Int)
    fun removeCategory(categoryId: Long)
    fun sources(itemType: ItemType): List<Source>
    fun source(sourceId: Long): Source?
    fun setSourceActive(sourceId: Long, active: Boolean)
    fun setSourcePinned(sourceId: Long, pinned: Boolean)
    fun setSourceAdded(sourceId: Long, added: Boolean)
    fun markSourceUsed(sourceId: Long)
    fun updateSourceCode(sourceId: Long, code: String)
    fun removeSource(sourceId: Long)
    fun repositories(itemType: ItemType): List<DbRepo>
    fun upsertRepository(itemType: ItemType, repo: DbRepo)
    fun removeRepository(itemType: ItemType, jsonUrl: String)
    fun allTitles(itemType: ItemType): List<Manga>
    fun manga(mangaId: Long): Manga?
    fun history(): List<History>
    fun updates(): List<UpdateEntry>
    fun tracks(): List<Track>
    fun downloads(): List<DbDownload>
    fun removeDownload(downloadId: Long)
    fun cancelDownload(downloadId: Long)
    fun clearChapterDownloads(chapterIds: Set<Long>)
    /** The saved page list as stored, fresh or not; readers go through `ChapterPageResolver`. */
    fun pageUrls(chapterId: Long): List<DbPageUrl>

    /** Saves [pageUrls] as fetched from [source] at [fetchedAt], minus Cookie/Authorization headers. */
    fun cachePageUrls(
        chapterId: Long,
        chapterUrl: String,
        pageUrls: List<DbPageUrl>,
        source: DbSource? = null,
        fetchedAt: Long = nowMillis(),
    )
    fun clearPageCache()
    fun upsertRemoteTitle(source: Source, remote: RemoteManga, favorite: Boolean? = null): Manga
    fun upsertRemoteDetail(source: Source, detail: RemoteDetail, favorite: Boolean? = null): Manga
    fun applyMetadata(mangaId: Long, metadata: MetadataMedia): Manga?
    fun applyLocalMetadataFields(mangaId: Long, metadata: MetadataMedia, fields: Set<LocalMetadataField>): Manga?
    /** Notes may be edited only while the title is in the library. */
    fun setMangaPrivateNote(mangaId: Long, note: String): Manga?
    fun setMangaDisplayTitle(mangaId: Long, title: String): Manga?
    fun setMangaCustomCover(mangaId: Long, bytes: ByteArray): Manga?
    /** An explicit choice; [favorite] adds the entry in the same transaction, without applying defaults. */
    fun setMangaCategories(mangaId: Long, categories: List<Long>, favorite: Boolean = false)
    fun setLibraryEntriesRead(mangaIds: Set<Long>, isRead: Boolean)
    /** Active consumption protects files from cleanup and triggers configured download-ahead. */
    fun chapterOpened(chapterId: Long) = Unit
    fun chapterClosed(chapterId: Long) = Unit
    /** Completion observed by a reader/player, distinct from manual read state and progress saves. */
    fun recordChapterConsumption(chapterIds: Set<Long>) = Unit
    fun setChaptersRead(
        chapterIds: Set<Long>,
        isRead: Boolean,
        lastPageRead: String? = null,
        readingTimeSeconds: Int = 0,
        autoReadDuplicates: Boolean = false,
    )
    fun setChaptersBookmarked(chapterIds: Set<Long>, bookmarked: Boolean)
    /** Manual filler mark that wins over the source value; null clears it. */
    fun setChaptersFillerOverride(chapterIds: Set<Long>, filler: Boolean?)
    fun setMangaFavorite(mangaId: Long, favorite: Boolean)

    /**
     * Persist a per-manga "smart update" cadence. `null` or `0` means always
     * eligible for library updates; positive values are interpreted by
     * `DefaultLibraryUpdaterService.shouldRefresh` as a cooldown in days.
     */
    fun setMangaSmartUpdateDays(mangaId: Long, days: Int?)
    fun removeLibraryEntries(mangaIds: Set<Long>)
    fun deleteChapters(chapterIds: Set<Long>)
    fun setUpdateRead(updateId: Long, isRead: Boolean)
    fun clearUpdates(itemType: ItemType)
    fun removeHistory(historyId: Long)
    fun clearHistory(itemType: ItemType)
    fun clearLibrary(itemType: ItemType)
    /** Deletes local/archive titles and their dependent reading records. */
    fun clearLocalLibrary(): Int
    /**
     * Removes non-favorited entries (cached browsing results that were never
     * added to the library) and their chapter data. Returns the number of
     * entries deleted.
     */
    fun cleanDatabase(): Int
    /**
     * Conservative variant of [cleanDatabase] run automatically at app launch:
     * removes non-favorited titles only when the user never interacted with
     * them (no history, no downloads, no tracking) along with their chapters.
     * Returns the number of entries deleted.
     */
    fun pruneBrowsedTitles(): Int
    /** Binds locally; remote trackers then fetch-or-create their list entry. */
    fun bindTrack(mangaId: Long, search: DbTrackSearch, itemType: ItemType)
    fun updateTrack(trackId: Long, progress: Int, status: DbTrackStatus, score: Int)

    /** [removeRemote] also deletes the provider's list entry where the tracker supports it. */
    fun removeTrack(trackId: Long, removeRemote: Boolean = false)

    /** Pulls the remote state of [mangaId]'s bound trackers and syncs enhanced (server) progress both ways. */
    fun refreshTracks(mangaId: Long) {}
}

/**
 * Re-reads [read] off the main thread whenever the snapshot parts selected by [key] change, e.g.
 * `repository.observe({ it.histories }) { history() }`. Unchanged parts keep their list instance, so
 * the key comparison short-circuits on reference equality and unrelated writes are skipped. Tests pass
 * their test dispatcher as [context] so the re-read stays on the test scheduler.
 */
fun <K, T> YokanRepository.observe(
    key: (YokanDatabaseSnapshot) -> K,
    context: CoroutineContext = Dispatchers.Default,
    read: YokanRepository.() -> T,
): Flow<T> = snapshots.distinctUntilChangedBy(key).map { read() }.flowOn(context)

/** Derive a read model from the exact published revision whose dependencies changed. */
fun <K, T> YokanRepository.observeSnapshot(
    key: (YokanDatabaseSnapshot) -> K,
    context: CoroutineContext = Dispatchers.Default,
    read: (YokanDatabaseSnapshot) -> T,
): Flow<T> = snapshots.distinctUntilChangedBy(key).map(read).flowOn(context)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/ActivityCategoryMatcher.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/ActivityCategoryMatcher.kt) · implementation · 21 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
7: internal class ActivityCategoryMatcher(filter: DbActivityCategoryFilter, availableCategoryIds: Set<Long>) {
15: fun matches(categoryIds: List<Long>?): Boolean {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/ActivityCategoryMatcher.kt) · SHA-256 `3313fdaf54ac6c5dda28b8be6ef3d72ed0cb53232c5eb4376f8ff746c123a2f4`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbActivityCategoryFilter
import eu.friedcutlet.yokan.database.UncategorizedActivityCategoryId

/** Compile once for a media type. Deleted/foreign category IDs cannot hide its entire activity. */
internal class ActivityCategoryMatcher(filter: DbActivityCategoryFilter, availableCategoryIds: Set<Long>) {
    private val included = filter.states.filter { (id, value) ->
        value == 1 && (id in availableCategoryIds || id == UncategorizedActivityCategoryId)
    }.keys
    private val excluded = filter.states.filter { (id, value) ->
        value == 2 && (id in availableCategoryIds || id == UncategorizedActivityCategoryId)
    }.keys

    fun matches(categoryIds: List<Long>?): Boolean {
        val ids = categoryIds.orEmpty()
        if (ids.isEmpty()) return UncategorizedActivityCategoryId !in excluded &&
            (included.isEmpty() || UncategorizedActivityCategoryId in included)
        return ids.none(excluded::contains) && (included.isEmpty() || ids.any(included::contains))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/ChapterFilters.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/ChapterFilters.kt) · implementation · 157 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
16: enum class ChapterFilterKind(val label: String) {
25: data class ChapterFilterTypes(
31: fun value(kind: ChapterFilterKind): Int = when (kind) {
39: private fun DbSettings.chapterListDefault(manga: Manga) = features.library.chapterListDefault(manga.itemType.toDb())
42: fun DbSettings.chapterSort(manga: Manga): DbSortChapter = sortChapterList
47: fun DbSettings.withChapterSortToggled(manga: Manga, index: Int): DbSettings {
58: fun DbSettings.chapterFilters(manga: Manga): ChapterFilterTypes {
68: fun DbSettings.withChapterFilterCycled(manga: Manga, kind: ChapterFilterKind): DbSettings {
83: fun DbSettings.withChapterListDefaultFrom(manga: Manga, applyTo: List<Manga>): DbSettings {
99: fun DbSettings.scanlatorFilter(mangaId: Long): Set<String> = filterScanlatorList
106: fun DbSettings.withScanlatorToggled(mangaId: Long, scanlator: String): DbSettings {
117: fun visibleChapters(manga: Manga, all: List<Chapter>, db: DbSettings, downloadedIds: Set<Long>): List<Chapter> =
121: fun sortedChapters(manga: Manga, chapters: List<Chapter>, db: DbSettings): List<Chapter> {
135: internal fun filterChapters(manga: Manga, chapters: List<Chapter>, db: DbSettings, downloadedIds: Set<Long>, showAllReleases: Boolean = false): List<Chapter> {
147: private fun filterMatches(type: Int, value: Boolean): Boolean = when (type) {
153: private fun List<DbChapterFilter>?.filterValue(mangaId: Long): Int? =
156: private fun List<DbChapterFilter>?.withFilter(mangaId: Long, type: Int): List<DbChapterFilter> =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/ChapterFilters.kt) · SHA-256 `d23559b85e867b4fac250b8cf589ff453c151c7d85a55a7d2c6a6f286c5d0527`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.database.DbChapterFilter
import eu.friedcutlet.yokan.database.DbChapterListDefaults
import eu.friedcutlet.yokan.database.DbFilterScanlator
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSortChapter
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.chapterReadingOrder
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.normalizeScanlator
import eu.friedcutlet.yokan.domain.selectChapterReleases
import eu.friedcutlet.yokan.database.chapterReleasePreference

enum class ChapterFilterKind(val label: String) {
    Downloaded("Downloaded"),
    Unread("Unread"),
    Bookmarked("Bookmarked"),
    /** Anime only: the effective (manual or source) filler mark. */
    Filler("Filler"),
}

/** Per-title tri-state filters: 0 off, 1 only matching, 2 exclude matching. */
data class ChapterFilterTypes(
    val downloaded: Int,
    val unread: Int,
    val bookmarked: Int,
    val filler: Int = 0,
) {
    fun value(kind: ChapterFilterKind): Int = when (kind) {
        ChapterFilterKind.Downloaded -> downloaded
        ChapterFilterKind.Unread -> unread
        ChapterFilterKind.Bookmarked -> bookmarked
        ChapterFilterKind.Filler -> filler
    }
}

private fun DbSettings.chapterListDefault(manga: Manga) = features.library.chapterListDefault(manga.itemType.toDb())

/** The title's own sort, else its media type's default. */
fun DbSettings.chapterSort(manga: Manga): DbSortChapter = sortChapterList
    ?.firstOrNull { it.mangaId == manga.id }
    ?: chapterListDefault(manga).let { DbSortChapter(mangaId = manga.id, index = it.sortIndex, reverse = it.sortReverse) }

/** Selects sort [index]; selecting the current one flips its direction. */
fun DbSettings.withChapterSortToggled(manga: Manga, index: Int): DbSettings {
    val current = chapterSort(manga)
    val next = current.copy(
        mangaId = manga.id,
        index = index,
        reverse = if (current.index == index) !current.reverse else current.reverse,
    )
    return copy(sortChapterList = sortChapterList.orEmpty().filterNot { it.mangaId == manga.id } + next)
}

/** Each filter is the title's own value, else its media type's default. */
fun DbSettings.chapterFilters(manga: Manga): ChapterFilterTypes {
    val default = chapterListDefault(manga)
    return ChapterFilterTypes(
        downloaded = chapterFilterDownloadedList.filterValue(manga.id) ?: default.downloaded,
        unread = chapterFilterUnreadList.filterValue(manga.id) ?: default.unread,
        bookmarked = chapterFilterBookmarkedList.filterValue(manga.id) ?: default.bookmarked,
        filler = features.library.chapterFillerFilters[manga.id] ?: default.filler,
    )
}

fun DbSettings.withChapterFilterCycled(manga: Manga, kind: ChapterFilterKind): DbSettings {
    val next = (chapterFilters(manga).value(kind) + 1) % 3
    return when (kind) {
        ChapterFilterKind.Downloaded -> copy(chapterFilterDownloadedList = chapterFilterDownloadedList.withFilter(manga.id, next))
        ChapterFilterKind.Unread -> copy(chapterFilterUnreadList = chapterFilterUnreadList.withFilter(manga.id, next))
        ChapterFilterKind.Bookmarked -> copy(chapterFilterBookmarkedList = chapterFilterBookmarkedList.withFilter(manga.id, next))
        ChapterFilterKind.Filler -> copy(features = features.copy(library = features.library.copy(
            chapterFillerFilters = features.library.chapterFillerFilters + (manga.id to next))))
    }
}

/**
 * Animetail "Set as default": [manga]'s current sort and filters become the default of its media type.
 * Library titles of that type in [applyTo] drop their own sort/filter entries so they follow the new default.
 */
fun DbSettings.withChapterListDefaultFrom(manga: Manga, applyTo: List<Manga>): DbSettings {
    val sort = chapterSort(manga)
    val filters = chapterFilters(manga)
    val default = DbChapterListDefaults(sort.index, sort.reverse, filters.downloaded, filters.unread, filters.bookmarked, filters.filler)
    val reset = applyTo.filter { it.favorite && it.itemType == manga.itemType }.mapTo(mutableSetOf()) { it.id }
    return copy(
        features = features.copy(library = features.library.withChapterListDefault(manga.itemType.toDb(), default)
            .let { it.copy(chapterFillerFilters = it.chapterFillerFilters - reset) }),
        sortChapterList = sortChapterList?.filterNot { it.mangaId in reset },
        chapterFilterDownloadedList = chapterFilterDownloadedList?.filterNot { it.mangaId in reset },
        chapterFilterUnreadList = chapterFilterUnreadList?.filterNot { it.mangaId in reset },
        chapterFilterBookmarkedList = chapterFilterBookmarkedList?.filterNot { it.mangaId in reset },
    )
}

/** Scanlators hidden for the title. */
fun DbSettings.scanlatorFilter(mangaId: Long): Set<String> = filterScanlatorList
    .orEmpty()
    .firstOrNull { it.mangaId == mangaId }
    ?.scanlators
    .orEmpty()
    .map(::normalizeScanlator).toSet()

fun DbSettings.withScanlatorToggled(mangaId: Long, scanlator: String): DbSettings {
    val normalized = normalizeScanlator(scanlator)
    val current = scanlatorFilter(mangaId)
    val next = if (normalized in current) current - normalized else current + normalized
    return copy(
        filterScanlatorList = filterScanlatorList.orEmpty().filterNot { it.mangaId == mangaId } +
            DbFilterScanlator(mangaId = mangaId, scanlators = next.toList().sorted()),
    )
}

/** The title's chapters after its filters, in its chosen sort order. */
fun visibleChapters(manga: Manga, all: List<Chapter>, db: DbSettings, downloadedIds: Set<Long>): List<Chapter> =
    sortedChapters(manga, filterChapters(manga, all, db, downloadedIds), db)

/** [chapters] in the title's chosen sort order, ignoring its filters. */
fun sortedChapters(manga: Manga, chapters: List<Chapter>, db: DbSettings): List<Chapter> {
    val sort = db.chapterSort(manga)
    val sorted = when (sort.index) {
        0 -> {
            val positions = chapterReadingOrder(manga.name, chapters).withIndex().associate { it.value.id to it.index }
            chapters.sortedWith(compareBy<Chapter> { normalizeScanlator(it.scanlator) }.thenBy { positions.getValue(it.id) })
        }
        2 -> chapters.sortedWith(compareBy<Chapter> { it.dateUpload.toLongOrNull() ?: 0L }.thenBy { it.name.lowercase() })
        3 -> chapters.sortedWith(compareBy { it.name.lowercase() })
        else -> chapterReadingOrder(manga.name, chapters)
    }
    return if (sort.reverse) sorted else sorted.asReversed()
}

internal fun filterChapters(manga: Manga, chapters: List<Chapter>, db: DbSettings, downloadedIds: Set<Long>, showAllReleases: Boolean = false): List<Chapter> {
    val filters = db.chapterFilters(manga)
    val selected = selectChapterReleases(manga.name, chapters, db.chapterReleasePreference(manga.id).toPolicy(),
        db.scanlatorFilter(manga.id), downloadedIds, offlineOnly = db.downloadedOnlyMode, showAllReleases = showAllReleases)
    return selected.filter { chapter ->
        filterMatches(filters.downloaded, chapter.id in downloadedIds) &&
            filterMatches(filters.unread, !chapter.isRead) &&
            filterMatches(filters.bookmarked, chapter.isBookmarked) &&
            filterMatches(filters.filler, chapter.isFiller)
    }
}

private fun filterMatches(type: Int, value: Boolean): Boolean = when (type) {
    1 -> value
    2 -> !value
    else -> true
}

private fun List<DbChapterFilter>?.filterValue(mangaId: Long): Int? =
    orEmpty().firstOrNull { it.mangaId == mangaId }?.type

private fun List<DbChapterFilter>?.withFilter(mangaId: Long, type: Int): List<DbChapterFilter> =
    orEmpty().filterNot { it.mangaId == mangaId } + DbChapterFilter(mangaId = mangaId, type = type)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LibraryAiringService.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LibraryAiringService.kt) · implementation · 147 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
13: data class LibraryAiringRefreshResult(val updated: Int = 0, val unavailable: Int = 0, val failed: Int = 0)
16: class LibraryAiringService(
27: suspend fun refresh(): LibraryAiringRefreshResult = scope.runJoined { gate.withLock { refreshLocked() } }
29: private suspend fun refreshLocked(): LibraryAiringRefreshResult {
79: private suspend fun fetch(provider: Provider, ids: List<Int>): Map<Int, Schedule> {
130: private fun binding(tracks: List<DbTrack>, metadata: DbTitleMetadata?): Binding? {
141: private fun validId(id: Long?): Int? = id?.takeIf { it in 1..Int.MAX_VALUE.toLong() }?.toInt()
142: private enum class Provider { AniList, MyAnimeList }
143: private data class Binding(val provider: Provider, val id: Int)
144: private data class Candidate(val title: DbManga, val binding: Binding)
145: private data class Schedule(val at: Long, val episode: Int?)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LibraryAiringService.kt) · SHA-256 `c87804564e7207ad6a796c07bc1cb5323309aec0f457c345309c6e64824b27da`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.runJoined
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.json.*

data class LibraryAiringRefreshResult(val updated: Int = 0, val unavailable: Int = 0, val failed: Int = 0)

/** Explicit, public-ID-only refresh. Profile retirement and caller cancellation both join its work. */
class LibraryAiringService(
    private val database: YokanDatabase,
    private val http: HttpService,
    private val scope: CoroutineScope,
    private val clock: () -> Long = ::nowMillis,
    private val requestIntervalMillis: Long = 2100,
    private val requestTimeoutMillis: Long = 20_000,
) {
    private val gate = Mutex()
    private var lastRequestAt: Long? = null

    suspend fun refresh(): LibraryAiringRefreshResult = scope.runJoined { gate.withLock { refreshLocked() } }

    private suspend fun refreshLocked(): LibraryAiringRefreshResult {
        val snapshot = database.snapshot()
        val tracks = snapshot.tracks.groupBy { it.mangaId }
        val metadata = snapshot.settings.titleMetadata.orEmpty().associateBy { it.mangaId }
        val anime = snapshot.mangas.filter { it.favorite && it.itemType == DbItemType.Anime }
        val candidates = anime.mapNotNull { title ->
            binding(tracks[title.id].orEmpty(), metadata[title.id])?.let { Candidate(title, it) }
        }
        var result = LibraryAiringRefreshResult(unavailable = anime.size - candidates.size)
        val batches = candidates.groupBy { it.binding.provider }.values.flatMap { group ->
            // Several source entries can refer to one public anime ID; fetch that ID once.
            group.groupBy { it.binding.id }.values.chunked(50).map { it.flatten() }
        }
        for ((batchIndex, batch) in batches.withIndex()) {
            currentCoroutineContext().ensureActive()
            val rows = try {
                val elapsed = lastRequestAt?.let { (clock() - it).coerceAtLeast(0) } ?: requestIntervalMillis
                if (elapsed < requestIntervalMillis) delay(requestIntervalMillis - elapsed)
                lastRequestAt = clock()
                fetch(batch.first().binding.provider, batch.map { it.binding.id }.distinct())
            } catch (cancel: CancellationException) { throw cancel }
            catch (_: Exception) {
                // Stop on HTTP/rate-limit/protocol failure; keep every previously saved schedule.
                return result.copy(failed = batches.drop(batchIndex).sumOf { it.size })
            }
            currentCoroutineContext().ensureActive()
            database.batch {
                val current = database.snapshot()
                val titles = current.mangas.associateBy { it.id }
                val currentTracks = current.tracks.groupBy { it.mangaId }
                val currentMetadata = current.settings.titleMetadata.orEmpty().associateBy { it.mangaId }
                batch.forEach { candidate ->
                    val title = titles[candidate.title.id]
                    val schedule = rows[candidate.binding.id]
                    if (title == null || !title.favorite || title.itemType != DbItemType.Anime ||
                        title.sourceId != candidate.title.sourceId || title.link != candidate.title.link ||
                        binding(currentTracks[title.id].orEmpty(), currentMetadata[title.id]) != candidate.binding
                    ) return@forEach
                    if (schedule == null) { result = result.copy(unavailable = result.unavailable + 1); return@forEach }
                    database.upsertManga(title.copy(nextEpisodeAiringAt = schedule.at, nextEpisodeNumber = schedule.episode,
                        airingScheduleUpdatedAt = clock()))
                    result = if (schedule.at > 0) result.copy(updated = result.updated + 1)
                        else result.copy(unavailable = result.unavailable + 1)
                }
            }
            database.awaitPersistence()
        }
        return result
    }

    private suspend fun fetch(provider: Provider, ids: List<Int>): Map<Int, Schedule> {
        val field = if (provider == Provider.AniList) "id_in" else "idMal_in"
        val query = "query(\$ids:[Int]) { Page(page:1,perPage:50) { media(type:ANIME,$field:\$ids) { id idMal type nextAiringEpisode { airingAt episode } } } }"
        val body = buildJsonObject {
            put("query", query)
            putJsonObject("variables") { putJsonArray("ids") { ids.forEach { add(it) } } }
        }.toString()
        val parts = mutableListOf<ByteArray>()
        var bytes = 0
        val response = withTimeoutOrNull(requestTimeoutMillis) {
            http.stream(HttpRequest("https://graphql.anilist.co", method = "POST",
                headers = mapOf("Content-Type" to "application/json", "Accept" to "application/json"), body = body)) { chunk ->
                require(chunk.size <= MaximumResponseBytes - bytes) { "Airing response too large" }
                bytes += chunk.size
                parts += chunk.copyOf()
            }
        } ?: error("Airing request timed out")
        check(response.statusCode in 200..299) { "Airing request failed" }
        val payload = ByteArray(bytes)
        var offset = 0
        parts.forEach { it.copyInto(payload, offset); offset += it.size }
        val root = DatabaseJson.parseToJsonElement(payload.decodeToString()).jsonObject
        check((root["errors"] as? JsonArray).isNullOrEmpty()) { "Airing provider rejected the query" }
        val data = (root["data"] as? JsonObject)?.get("Page") as? JsonObject ?: error("Invalid airing response")
        val media = data["media"] as? JsonArray ?: error("Invalid airing response")
        require(media.size <= 50)
        val now = clock()
        val result = mutableMapOf<Int, Schedule>()
        media.forEach { value ->
            val row = value as? JsonObject ?: error("Invalid airing entry")
            check((row["type"] as? JsonPrimitive)?.content == "ANIME") { "Unexpected airing media type" }
            val id = (row[if (provider == Provider.AniList) "id" else "idMal"] as? JsonPrimitive)?.intOrNull
                ?: error("Invalid airing identity")
            if (id !in ids) return@forEach
            check(id !in result) { "Duplicate airing identity" }
            val next = row["nextAiringEpisode"]
            result[id] = when (next) {
                JsonNull -> Schedule(0, null)
                is JsonObject -> {
                    val seconds = (next["airingAt"] as? JsonPrimitive)?.longOrNull ?: error("Invalid airing time")
                    val episode = (next["episode"] as? JsonPrimitive)?.intOrNull ?: error("Invalid airing episode")
                    require(seconds in 1..Int.MAX_VALUE.toLong() && episode > 0)
                    val at = seconds * 1000
                    if (at > now) Schedule(at, episode) else Schedule(0, null)
                }
                else -> error("Missing airing schedule")
            }
        }
        return result
    }

    private fun binding(tracks: List<DbTrack>, metadata: DbTitleMetadata?): Binding? {
        tracks.firstOrNull { it.syncId == 2 && it.itemType == DbItemType.Anime && validId(it.mediaId) != null }?.let { return Binding(Provider.AniList, requireNotNull(validId(it.mediaId))) }
        tracks.firstOrNull { it.syncId == 1 && it.itemType == DbItemType.Anime && validId(it.mediaId) != null }?.let { return Binding(Provider.MyAnimeList, requireNotNull(validId(it.mediaId))) }
        val id = validId(metadata?.metadataServerId?.toLongOrNull()) ?: return null
        return when (metadata?.metadataSource?.lowercase()?.replace("-", "")?.replace("_", "")?.replace(" ", "")) {
            "anilist" -> Binding(Provider.AniList, id)
            "myanimelist", "mal" -> Binding(Provider.MyAnimeList, id)
            else -> null
        }
    }

    private fun validId(id: Long?): Int? = id?.takeIf { it in 1..Int.MAX_VALUE.toLong() }?.toInt()
    private enum class Provider { AniList, MyAnimeList }
    private data class Binding(val provider: Provider, val id: Int)
    private data class Candidate(val title: DbManga, val binding: Binding)
    private data class Schedule(val at: Long, val episode: Int?)
    private companion object { const val MaximumResponseBytes = 256 * 1024 }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LibraryUpdaterService.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LibraryUpdaterService.kt) · implementation · 484 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
36: interface LibraryUpdaterService {
37: suspend fun updateLibrary(
45: suspend fun updateTitle(mangaId: Long): Boolean
48: data class LibraryUpdateResult(
57: data class LibraryUpdateProgress(
68: data class LibraryUpdateProgressState(
80: fun DbSettings.withoutUpdateError(mangaId: Long): DbSettings =
87: class LibraryUpdateController(
99: fun cancel() {
105: suspend fun run(itemType: ItemType, titleIds: Set<Long>? = null): LibraryUpdateResult {
155: private fun notifySummary(itemType: ItemType, result: LibraryUpdateResult, beforeRecent: Set<Long>) {
177: private fun scheduleClear(progress: LibraryUpdateProgressState) {
185: private fun LibraryUpdateProgress.toUiState(
200: class DefaultLibraryUpdaterService(
208: override suspend fun updateLibrary(
219: private suspend fun updateLibraryLocked(itemType: DbItemType, onProgress: (LibraryUpdateProgress) -> Unit,
373: override suspend fun updateTitle(mangaId: Long): Boolean = updateMutex.withLock {
381: private suspend fun updateOne(manga: DbManga, source: DbSource, depth: Int = 0): Boolean {
477: private fun writeUpdateErrors(scope: Set<Long>, failures: List<DbUpdateError>) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LibraryUpdaterService.kt) · SHA-256 `93f5a67f41a0eeb5e006d06b55a58f37e766617cb1def970c8dce44b00c202ce`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.data.upsertSeasonRecords
import eu.friedcutlet.yokan.database.DbFetchType
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbUpdate
import eu.friedcutlet.yokan.database.DbUpdateError
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.notifications.NotificationChannel
import eu.friedcutlet.yokan.services.notifications.NotificationPayload
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.util.nowMillis
import kotlin.concurrent.Volatile
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.updateAndGet
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

interface LibraryUpdaterService {
    suspend fun updateLibrary(
        itemType: DbItemType,
        onProgress: (LibraryUpdateProgress) -> Unit = {},
        shouldCancel: () -> Boolean = { false },
        titleIds: Set<Long>? = null,
        mayStartTitle: suspend () -> Boolean = { true },
    ): LibraryUpdateResult

    suspend fun updateTitle(mangaId: Long): Boolean
}

data class LibraryUpdateResult(
    val checked: Int,
    val updated: Int,
    val failed: Int,
    val cancelled: Boolean = false,
    val errors: List<DbUpdateError> = emptyList(),
    val deferred: Boolean = false,
)

data class LibraryUpdateProgress(
    val itemType: DbItemType,
    val checked: Int,
    val total: Int,
    val updated: Int,
    val failed: Int,
    val currentTitle: String? = null,
    val isRunning: Boolean = true,
)

/** UI projection of [LibraryUpdateProgress], kept visible for a few seconds after a run ends. */
data class LibraryUpdateProgressState(
    val itemType: ItemType,
    val checked: Int,
    val total: Int,
    val updated: Int,
    val failed: Int,
    val currentTitle: String? = null,
    val running: Boolean = true,
    val cancelRequested: Boolean = false,
    val cancelled: Boolean = false,
)

fun DbSettings.withoutUpdateError(mangaId: Long): DbSettings =
    copy(updateErrors = updateErrors.orEmpty().filterNot { it.mangaId == mangaId })

/**
 * App-scoped front of [LibraryUpdaterService]: one run at a time, observable [progress], a
 * summary notification, and cooperative [cancel].
 */
class LibraryUpdateController(
    private val updater: LibraryUpdaterService,
    private val repository: YokanRepository,
    private val notifications: NotificationService,
    private val scope: CoroutineScope,
) {
    private val _progress = MutableStateFlow<LibraryUpdateProgressState?>(null)
    val progress: StateFlow<LibraryUpdateProgressState?> = _progress.asStateFlow()

    @Volatile
    private var cancelRequested = false

    fun cancel() {
        cancelRequested = true
        _progress.update { it?.copy(cancelRequested = true) }
    }

    /** Runs in the caller's coroutine; returns an empty result while another run is active. */
    suspend fun run(itemType: ItemType, titleIds: Set<Long>? = null): LibraryUpdateResult {
        val capturedIds = titleIds?.toSet()
        val current = _progress.value
        val started = LibraryUpdateProgressState(
            itemType = itemType,
            checked = 0,
            total = 0,
            updated = 0,
            failed = 0,
            running = true,
        )
        if (current?.running == true || !_progress.compareAndSet(current, started)) {
            return LibraryUpdateResult(0, 0, 0)
        }
        cancelRequested = false
        val beforeRecent = repository.updates().map { it.id }.toSet()
        val result = try {
            updater.updateLibrary(
                itemType.toDb(),
                onProgress = { progress ->
                    _progress.value = progress.toUiState(cancelRequested = cancelRequested, cancelled = false)
                },
                shouldCancel = { cancelRequested },
                titleIds = capturedIds,
            )
        } catch (throwable: Throwable) {
            AppLogger.error("[library-update] $itemType run failed: ${throwable.message?.lineSequence()?.firstOrNull() ?: throwable::class.simpleName}")
            val failed = _progress.updateAndGet {
                it?.copy(running = false, currentTitle = throwable.message.orEmpty().ifBlank { "Update failed" })
            }
            failed?.let(::scheduleClear)
            throw throwable
        }
        val finalProgress = (_progress.value ?: LibraryUpdateProgressState(
            itemType = itemType,
            checked = result.checked,
            total = result.checked,
            updated = result.updated,
            failed = result.failed,
        )).copy(
            running = false,
            cancelRequested = false,
            cancelled = result.cancelled,
        )
        _progress.value = finalProgress
        scheduleClear(finalProgress)
        if (result.updated > 0) notifySummary(itemType, result, beforeRecent)
        return result
    }

    private fun notifySummary(itemType: ItemType, result: LibraryUpdateResult, beforeRecent: Set<Long>) {
        val newlyUpdatedTitles = repository.updates()
            .filter { it.id !in beforeRecent && it.itemType == itemType }
            .sortedByDescending { it.updatedAt }
            .map { it.title }
            .distinct()
        val sample = newlyUpdatedTitles.take(3).joinToString(", ")
        val extra = if (newlyUpdatedTitles.size > 3) " + ${newlyUpdatedTitles.size - 3} more" else ""
        val message = buildString {
            append("${result.updated} of ${result.checked} titles refreshed (${result.failed} failed)")
            if (sample.isNotBlank()) append("\nNew: $sample$extra")
        }
        notifications.notify(
            NotificationPayload(
                channel = NotificationChannel.LibraryUpdates,
                title = "${itemType.label} updates",
                message = message,
                tag = "library-${itemType.name}",
            ),
        )
    }

    private fun scheduleClear(progress: LibraryUpdateProgressState) {
        scope.launch {
            delay(if (progress.cancelled) 6_000L else 4_000L)
            _progress.compareAndSet(progress, null)
        }
    }
}

private fun LibraryUpdateProgress.toUiState(
    cancelRequested: Boolean,
    cancelled: Boolean,
): LibraryUpdateProgressState = LibraryUpdateProgressState(
    itemType = itemType.toDomain(),
    checked = checked,
    total = total,
    updated = updated,
    failed = failed,
    currentTitle = currentTitle,
    running = isRunning,
    cancelRequested = cancelRequested,
    cancelled = cancelled,
)

class DefaultLibraryUpdaterService(
    private val database: YokanDatabase,
    private val runtimeFactory: ExtensionRuntimeFactory,
    private val downloadAutomation: eu.friedcutlet.yokan.services.download.DownloadAutomation? = null,
    private val clock: () -> Long = ::nowMillis,
) : LibraryUpdaterService {
    private val updateMutex = Mutex()

    override suspend fun updateLibrary(
        itemType: DbItemType,
        onProgress: (LibraryUpdateProgress) -> Unit,
        shouldCancel: () -> Boolean,
        titleIds: Set<Long>?,
        mayStartTitle: suspend () -> Boolean,
    ): LibraryUpdateResult {
        val capturedIds = titleIds?.toSet()
        return updateMutex.withLock { updateLibraryLocked(itemType, onProgress, shouldCancel, capturedIds, mayStartTitle) }
    }

    private suspend fun updateLibraryLocked(itemType: DbItemType, onProgress: (LibraryUpdateProgress) -> Unit,
        shouldCancel: () -> Boolean, titleIds: Set<Long>?, mayStartTitle: suspend () -> Boolean): LibraryUpdateResult {
        // Evaluate after waiting for the service lock, before any source work or report mutation.
        if (!mayStartTitle()) {
            onProgress(LibraryUpdateProgress(itemType, 0, 0, 0, 0, isRunning = false))
            return LibraryUpdateResult(0, 0, 0, deferred = true)
        }
        val settings = database.settings()
        val rules = settings.features.library.updateRules(itemType)
        val library = database.mangas(itemType)
        val errorScope = library.asSequence().filter { titleIds == null || it.id in titleIds }.map { it.id }.toSet()
        val pinnedOnly = settings.onlyIncludePinnedSources
        val excludedCategoryIds = database.categories(itemType)
            .filter { it.shouldUpdate == false }
            .mapNotNull { category -> category.id.takeIf { it > 0 } }
            .toSet()
        val chaptersByTitle by lazy { database.chapters().groupBy { it.mangaId } }
        val candidates = library
            .filter { it.favorite && (titleIds == null || it.id in titleIds) }
            .filter { manga ->
                val needsChapters = rules.onlyCaughtUp || rules.onlyStarted ||
                    (rules.respectExpectedReleasePeriod && manga.smartUpdateDays == null)
                rules.permits(manga, if (needsChapters) chaptersByTitle[manga.id].orEmpty() else emptyList(), clock())
            }
            .filter { manga ->
                val mangaCategories = manga.categories.orEmpty()
                excludedCategoryIds.isEmpty() ||
                    mangaCategories.isEmpty() ||
                    mangaCategories.any { it !in excludedCategoryIds }
            }
        val workItems = candidates.mapNotNull { manga ->
            val source = manga.sourceId?.let(database::source)
            if (source == null || !source.isActive || (pinnedOnly && !source.isPinned)) {
                null
            } else {
                manga to source
            }
        }
        if (workItems.isEmpty()) {
            onProgress(
                LibraryUpdateProgress(
                    itemType = itemType,
                    checked = 0,
                    total = 0,
                    updated = 0,
                    failed = 0,
                    isRunning = false,
                ),
            )
            writeUpdateErrors(errorScope, emptyList())
            return LibraryUpdateResult(0, 0, 0, errors = emptyList())
        }
        var checked = 0
        var updated = 0
        var failed = 0
        val failures = mutableListOf<DbUpdateError>()
        onProgress(
            LibraryUpdateProgress(
                itemType = itemType,
                checked = checked,
                total = workItems.size,
                updated = updated,
                failed = failed,
                isRunning = true,
            ),
        )
        workItems.forEach { (manga, source) ->
            if (shouldCancel()) {
                onProgress(
                    LibraryUpdateProgress(
                        itemType = itemType,
                        checked = checked,
                        total = workItems.size,
                        updated = updated,
                        failed = failed,
                        currentTitle = manga.name,
                        isRunning = false,
                    ),
                )
                writeUpdateErrors(errorScope, failures)
                AppLogger.info("[library-update] $itemType cancelled: $updated of $checked/${workItems.size} updated, $failed failed")
                return LibraryUpdateResult(
                    checked = checked,
                    updated = updated,
                    failed = failed,
                    cancelled = true,
                    errors = failures,
                )
            }
            if (!mayStartTitle()) {
                // Preserve error reports for unchecked titles when constraints change mid-run.
                writeUpdateErrors(workItems.take(checked).mapTo(mutableSetOf()) { it.first.id }, failures)
                onProgress(LibraryUpdateProgress(itemType, checked, workItems.size, updated, failed, isRunning = false))
                return LibraryUpdateResult(checked, updated, failed, errors = failures, deferred = true)
            }
            checked += 1
            var errorMsg: String? = null
            val success = catchingNonCancellation {
                updateOne(manga, source)
            }.fold(
                onSuccess = { ok ->
                    if (!ok) errorMsg = "Update failed (invalid link or source error)"
                    ok
                },
                onFailure = { err ->
                    errorMsg = err.message?.ifBlank { null } ?: err.toString()
                    false
                },
            )
            if (success) {
                updated += 1
            } else {
                failed += 1
                failures.add(
                    DbUpdateError(
                        mangaId = manga.id,
                        name = manga.name ?: "Unknown title",
                        error = errorMsg ?: "Unknown error",
                    ),
                )
            }
            onProgress(
                LibraryUpdateProgress(
                    itemType = itemType,
                    checked = checked,
                    total = workItems.size,
                    updated = updated,
                    failed = failed,
                    currentTitle = manga.name,
                    isRunning = true,
                ),
            )
        }
        writeUpdateErrors(errorScope, failures)
        val summary = "[library-update] $itemType done: $updated of $checked updated, $failed failed"
        val firstFailure = failures.firstOrNull()
        if (firstFailure == null) {
            AppLogger.info(summary)
        } else {
            AppLogger.warn("$summary; first: ${firstFailure.name}: ${firstFailure.error.lineSequence().firstOrNull().orEmpty()}")
        }
        onProgress(
            LibraryUpdateProgress(
                itemType = itemType,
                checked = checked,
                total = workItems.size,
                updated = updated,
                failed = failed,
                isRunning = false,
            ),
        )
        return LibraryUpdateResult(checked = checked, updated = updated, failed = failed, errors = failures)
    }

    override suspend fun updateTitle(mangaId: Long): Boolean = updateMutex.withLock {
        val manga = database.manga(mangaId) ?: return@withLock false
        val source = manga.sourceId?.let(database::source) ?: return@withLock false
        catchingNonCancellation { updateOne(manga, source) }
            .onFailure { AppLogger.warn("[library-update] title $mangaId failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }
            .getOrDefault(false)
    }

    private suspend fun updateOne(manga: DbManga, source: DbSource, depth: Int = 0): Boolean {
        val link = manga.link ?: return false
        val detail = runtimeFactory.withRuntime(source) { it.detail(link) }
        val now = clock()
        detail.seasons?.let { seasons ->
            val parent = database.batch {
                val current = database.manga(manga.id) ?: return@batch null
                if (current.sourceId != manga.sourceId || current.link != link) return@batch null
                val saved = database.upsertManga(current.copy(
                    description = detail.description.ifBlank { current.description.orEmpty() },
                    author = detail.author ?: current.author,
                    artist = detail.artist ?: current.artist,
                    imageUrl = detail.thumbnailUrl ?: current.imageUrl,
                    fetchType = DbFetchType.Seasons,
                    lastUpdate = now,
                    updatedAt = now,
                ))
                database.upsertSeasonRecords(saved, seasons, now)
                saved
            } ?: return false
            // Each season is its own title: refreshing it records new episodes (or nested seasons) under it.
            // ponytail: nesting capped at 4 levels and seasons refresh sequentially; parallelize if large franchises stall runs.
            if (depth >= 4) return true
            return database.mangas(manga.itemType).filter { it.parentId == parent.id }
                .fold(true) { ok, season -> updateOne(season, source, depth + 1) && ok }
        }
        val seenUrls = mutableSetOf<String>()
        val seenCompositeKeys = mutableSetOf<String>()
        val newChapterIds = mutableSetOf<Long>()
        return database.batch {
            // Re-read after the network request: local edits (and deletion) win.
            val currentManga = database.manga(manga.id) ?: return@batch false
            if (currentManga.sourceId != manga.sourceId || currentManga.link != link) return@batch false
            val currentChapters = database.chapters(manga.id)
            val mangaTitle = currentManga.name
            val chaptersByUrl = currentChapters.associateByTo(mutableMapOf(), DbChapter::url)
            val chaptersByComposite = currentChapters.mapNotNull { c ->
                eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, c.name, c.scanlator, c.number, c.season, c.numberingName)?.let { it to c }
            }.toMap()
            val readByEpisode = currentChapters.filter { it.isRead }.mapNotNull { c ->
                eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, c.name, number = c.number, season = c.season, numberingName = c.numberingName)
            }.toSet()
            val beforeUrls = chaptersByUrl.keys.toSet()
            database.upsertManga(
                currentManga.copy(
                    description = detail.description.ifBlank { currentManga.description.orEmpty() },
                    author = detail.author ?: currentManga.author,
                    artist = detail.artist ?: currentManga.artist,
                    imageUrl = detail.thumbnailUrl ?: currentManga.imageUrl,
                    lastUpdate = now,
                    updatedAt = now,
                ),
            )
            detail.chapters.forEach { remote ->
                val compositeKey = eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, remote.title, remote.scanlator)
                val episodeKey = eu.friedcutlet.yokan.domain.chapterReleaseKey(mangaTitle, remote.title)

                if (!seenUrls.add(remote.url)) return@forEach
                if (compositeKey != null && !seenCompositeKeys.add(compositeKey)) return@forEach

                val existing = chaptersByUrl[remote.url] ?: compositeKey?.let { chaptersByComposite[it] }
                val carryRead = existing?.isRead ?: (episodeKey != null && episodeKey in readByEpisode)

                val next = (existing ?: DbChapter(mangaId = manga.id)).copy(
                    mangaId = manga.id,
                    name = remote.title,
                    url = remote.url,
                    dateUpload = remote.dateUpload.ifBlank { existing?.dateUpload.orEmpty() },
                    scanlator = remote.scanlator.ifBlank { existing?.scanlator.orEmpty() },
                    isBookmarked = existing?.isBookmarked ?: false,
                    isRead = carryRead,
                    lastPageRead = existing?.lastPageRead ?: if (carryRead) "1" else "",
                    fetchedAt = existing?.fetchedAt ?: now,
                )
                // Unchanged chapters are not rewritten: bumping the synced `updatedAt` alone would
                // cost a write and a hub op per chapter on every library update.
                val saved = if (existing != null && next == existing) existing else database.upsertChapter(next.copy(updatedAt = now))
                chaptersByUrl[remote.url] = saved
                if (existing == null && remote.url !in beforeUrls) {
                    newChapterIds += saved.id
                    database.upsertUpdate(
                        DbUpdate(
                            mangaId = manga.id,
                            chapterId = saved.id,
                            chapterName = saved.name,
                            date = "Now",
                            updatedAt = now,
                        ),
                    )
                }
            }
            downloadAutomation?.recordDiscoveredChapters(newChapterIds)
            true
        }
    }

    private fun writeUpdateErrors(scope: Set<Long>, failures: List<DbUpdateError>) {
        database.batch {
            val current = database.settings()
            val next = current.updateErrors.orEmpty().filterNot { it.mangaId in scope } + failures
            if (next != current.updateErrors.orEmpty()) database.updateSettings(current.copy(updateErrors = next))
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/ReaderChapterSequence.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/ReaderChapterSequence.kt) · implementation · 50 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
16: fun readingChapterSequence(
33: internal fun resolveReadingChapterSequence(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/ReaderChapterSequence.kt) · SHA-256 `095089279d9b0573ec788bf8df242afbd91169f9e8dc8e3f291fe9758102e1ac`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.chapterReleasePreference
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ChapterReleasePreferences
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.chapterReadingOrder
import eu.friedcutlet.yokan.domain.chapterReleaseIdentity
import eu.friedcutlet.yokan.domain.selectChapterReleases

/**
 * A directly opened alternate remains readable; it never enables the whole excluded raw list.
 * Reader policies may keep title-filtered chapters and skip read ones; the current chapter always stays.
 */
fun readingChapterSequence(
    manga: Manga,
    currentChapterId: Long,
    all: List<Chapter>,
    db: DbSettings,
    downloadedIds: Set<Long>,
): List<Chapter> {
    val policy = db.features.reader
    return resolveReadingChapterSequence(
        manga.name, currentChapterId,
        if (policy.skipFilteredChapters) filterChapters(manga, all, db, downloadedIds) else all,
        all,
        db.chapterReleasePreference(manga.id).skipDuplicateReleases,
        policy.skipReadChapters,
    )
}

internal fun resolveReadingChapterSequence(
    mangaTitle: String,
    currentChapterId: Long,
    filteredChapters: List<Chapter>,
    allChapters: List<Chapter>,
    skipDuplicates: Boolean = true,
    skipRead: Boolean = false,
): List<Chapter> {
    // Releases are chosen before dropping read ones, so a read chapter never falls back to an unread alternate.
    val selected = selectChapterReleases(mangaTitle, filteredChapters, ChapterReleasePreferences(skipDuplicates = skipDuplicates))
        .let { releases -> if (skipRead) releases.filter { !it.isRead || it.id == currentChapterId } else releases }
    if (selected.any { it.id == currentChapterId }) return chapterReadingOrder(mangaTitle, selected)
    val current = allChapters.firstOrNull { it.id == currentChapterId } ?: return chapterReadingOrder(mangaTitle, selected)
    val identity = chapterReleaseIdentity(mangaTitle, current.name, current.number, current.season, current.numberingName)
    val others = if (skipDuplicates && identity != null) selected.filterNot { chapterReleaseIdentity(mangaTitle, it.name, it.number, it.season, it.numberingName) == identity }
        else selected
    return chapterReadingOrder(mangaTitle, others + current)
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/SelectiveDataClearService.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/SelectiveDataClearService.kt) · implementation · 217 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
10: data class ClearResult(
21: class SelectiveDataClearService(
26: suspend fun clearLibrary(types: Set<ItemType>): ClearResult {
43: suspend fun clearSources(types: Set<ItemType>): ClearResult {
60: private suspend fun commit(
87: private fun hasAffectedDownloads(
94: fun affected(chapterId: Long?): Boolean {
102: private fun activeProgressAffected(
115: internal data class ClearPlan(
123: internal fun planLibraryClear(before: YokanDatabaseSnapshot, types: Set<DbItemType>): ClearPlan {
168: internal fun planSourceClear(before: YokanDatabaseSnapshot, types: Set<DbItemType>): ClearPlan {
180: internal fun removeTitleWithDependents(database: YokanDatabase, mangaId: Long, recordChange: Boolean = false) {
213: private fun toDbType(type: ItemType): DbItemType = when (type) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/SelectiveDataClearService.kt) · SHA-256 `24cece03abb676db12610f1ddc1f55a7908b94b486cd0fc00352e58f5148c564`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.database.sync.SyncPaths
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.download.DownloadService
import eu.friedcutlet.yokan.services.download.DownloadProgress
import kotlinx.coroutines.CancellationException

data class ClearResult(
    val cleared: Boolean,
    val titlesRemoved: Int = 0,
    val chaptersRemoved: Int = 0,
    val dependentRowsRemoved: Int = 0,
    val sourcesRemoved: Int = 0,
    val deliveryPending: Boolean = false,
    val error: String? = null,
)

/** Removes logical database data only. Downloaded media files are deliberately untouched. */
class SelectiveDataClearService(
    private val database: YokanDatabase,
    private val downloader: DownloadService,
    private val onSourcesCommitted: (Set<Long>) -> Unit = {},
) {
    suspend fun clearLibrary(types: Set<ItemType>): ClearResult {
        require(types.isNotEmpty()) { "Select at least one library type to clear." }
        val before = database.snapshot()
        val selected = types.mapTo(mutableSetOf(), ::toDbType)
        val plan = planLibraryClear(before, selected)
        plan.error?.let { return ClearResult(cleared = false, error = it) }
        if (hasAffectedDownloads(before, plan.removedChapters, selected)) {
            return ClearResult(cleared = false, error = "Cancel or finish queued, paused, and active downloads for the selected library types before clearing them.")
        }
        val hubConfigured = before.syncPreferences.any { !it.server.isNullOrBlank() && !it.server.startsWith("cloud://") }
        val activeHub = SyncPaths.activeHubEpoch(before.syncPreferences)
        if (hubConfigured && (activeHub == null || before.syncPreferences.none { it.syncOn && !it.authToken.isNullOrBlank() && !it.server.isNullOrBlank() && it.hubEpoch > 0 && it.hubBootstrapComplete })) {
            return ClearResult(cleared = false, error = "Reconnect and complete hub sync setup before clearing library data, so deletions can be delivered.")
        }
        return commit(before, plan.after, plan, deliveryPending = activeHub != null)
    }

    suspend fun clearSources(types: Set<ItemType>): ClearResult {
        require(types.isNotEmpty()) { "Select at least one source type to clear." }
        val before = database.snapshot()
        val selected = types.mapTo(mutableSetOf(), ::toDbType)
        val sourceIds = before.sources.filter { it.itemType in selected }.mapTo(mutableSetOf()) { it.id }
        val chapterIds = before.mangas.filter { it.sourceId?.let(sourceIds::contains) == true }.flatMap { title ->
            before.chapters.filter { it.mangaId == title.id }.map { it.id }
        }.toSet()
        if (hasAffectedDownloads(before, chapterIds, selected, sourceIds)) {
            return ClearResult(cleared = false, error = "Cancel or finish queued, paused, and active downloads using the selected sources before clearing them.")
        }
        val after = planSourceClear(before, selected).after
        val result = commit(before, after, ClearPlan(after), removedSourceIds = sourceIds)
        if (result.cleared && sourceIds.isNotEmpty()) onSourcesCommitted(sourceIds)
        return result.copy(sourcesRemoved = if (result.cleared) sourceIds.size else 0)
    }

    private suspend fun commit(
        before: YokanDatabaseSnapshot,
        after: YokanDatabaseSnapshot,
        plan: ClearPlan,
        removedSourceIds: Set<Long> = emptySet(),
        deliveryPending: Boolean = false,
    ): ClearResult {
        if (!database.supportsAtomicSnapshotPersistence()) {
            return ClearResult(cleared = false, error = "This database backend cannot atomically clear data; nothing was changed.")
        }
        return try {
            val withOutbox = after.copy(outbox = SyncPaths.outboxForReplacement(before, after))
            database.replaceAllAtomically(withOutbox, expectedSnapshot = before, removedSourceIds = removedSourceIds)
            ClearResult(
                cleared = true,
                titlesRemoved = plan.removedTitles.size,
                chaptersRemoved = plan.removedChapters.size,
                dependentRowsRemoved = plan.dependentRowsRemoved,
                deliveryPending = deliveryPending,
            )
        } catch (error: CancellationException) {
            throw error
        } catch (error: Throwable) {
            ClearResult(cleared = false, error = error.message ?: "Database clear failed; no change was committed.")
        }
    }

    private fun hasAffectedDownloads(
        snapshot: YokanDatabaseSnapshot,
        chapterIds: Set<Long>,
        types: Set<DbItemType>,
        sourceIds: Set<Long> = emptySet(),
    ): Boolean {
        val titles = snapshot.mangas.associateBy { it.id }
        fun affected(chapterId: Long?): Boolean {
            val title = snapshot.chapters.firstOrNull { it.id == chapterId }?.mangaId?.let(titles::get) ?: return false
            return chapterId in chapterIds || title.itemType in types || title.sourceId?.let(sourceIds::contains) == true
        }
        return snapshot.downloads.any { it.isStartDownload == true && it.isDownload != true && affected(it.chapterId) } ||
            downloader.activeDownloads().any { !it.isCompleted && activeProgressAffected(it, snapshot, chapterIds, types, sourceIds) }
    }

    private fun activeProgressAffected(
        progress: DownloadProgress,
        snapshot: YokanDatabaseSnapshot,
        chapterIds: Set<Long>,
        types: Set<DbItemType>,
        sourceIds: Set<Long>,
    ): Boolean {
        val chapterId = progress.taskId.removePrefix("chapter-").toLongOrNull() ?: return progress.itemType in types
        val title = snapshot.chapters.firstOrNull { it.id == chapterId }?.mangaId?.let { id -> snapshot.mangas.firstOrNull { it.id == id } }
        return chapterId in chapterIds || title?.itemType?.let(types::contains) == true || title?.sourceId?.let(sourceIds::contains) == true
    }
}

internal data class ClearPlan(
    val after: YokanDatabaseSnapshot,
    val removedTitles: Set<Long> = emptySet(),
    val removedChapters: Set<Long> = emptySet(),
    val dependentRowsRemoved: Int = 0,
    val error: String? = null,
)

internal fun planLibraryClear(before: YokanDatabaseSnapshot, types: Set<DbItemType>): ClearPlan {
    val titleIds = before.mangas.filter { it.itemType in types }.mapTo(mutableSetOf()) { it.id }
    val titleById = before.mangas.associateBy { it.id }
    val chapters = before.chapters.filter { it.mangaId in titleIds }
    val chapterIds = chapters.mapTo(mutableSetOf()) { it.id }
    // A row with conflicting explicit ownership is not safe to cascade.
    if (before.histories.any { it.mangaId in titleIds && it.itemType != titleById[it.mangaId]?.itemType }) {
        return ClearPlan(before, error = "A history row has conflicting media-type ownership; resolve it before clearing.")
    }
    if (before.tracks.any { it.mangaId in titleIds && it.itemType != titleById[it.mangaId]?.itemType }) {
        return ClearPlan(before, error = "A tracker row has conflicting media-type ownership; resolve it before clearing.")
    }
    val histories = before.histories.filter { it.mangaId in titleIds || it.chapterId in chapterIds }
    val updates = before.updates.filter { it.mangaId in titleIds || it.chapterId in chapterIds }
    val tracks = before.tracks.filter { it.mangaId in titleIds }
    val downloads = before.downloads.filter { it.chapterId in chapterIds }
    val searches = before.trackSearches.filter { it.libraryId in titleIds }
    val settings = before.settings.copy(
        sortChapterList = before.settings.sortChapterList?.filterNot { it.mangaId in titleIds },
        chapterFilterDownloadedList = before.settings.chapterFilterDownloadedList?.filterNot { it.mangaId in titleIds },
        chapterFilterUnreadList = before.settings.chapterFilterUnreadList?.filterNot { it.mangaId in titleIds },
        chapterFilterBookmarkedList = before.settings.chapterFilterBookmarkedList?.filterNot { it.mangaId in titleIds },
        chapterPageIndexList = before.settings.chapterPageIndexList?.filterNot { it.chapterId in chapterIds },
        personalReaderModeList = before.settings.personalReaderModeList?.filterNot { it.mangaId in titleIds },
        filterScanlatorList = before.settings.filterScanlatorList?.filterNot { it.mangaId in titleIds },
        personalPageModeList = before.settings.personalPageModeList?.filterNot { it.mangaId in titleIds },
        autoScrollPages = before.settings.autoScrollPages?.filterNot { it.mangaId in titleIds },
        titleMetadata = before.settings.titleMetadata?.filterNot { it.mangaId in titleIds },
        updateErrors = before.settings.updateErrors?.filterNot { it.mangaId in titleIds },
        downloadQueueOrder = before.settings.downloadQueueOrder.filterNot { id -> downloads.any { it.id == id } },
    )
    val after = before.copy(
        settings = settings,
        mangas = before.mangas.filterNot { it.id in titleIds },
        chapters = before.chapters.filterNot { it.id in chapterIds },
        histories = before.histories.filterNot { it in histories },
        updates = before.updates.filterNot { it in updates },
        tracks = before.tracks.filterNot { it in tracks },
        trackSearches = before.trackSearches.filterNot { it in searches },
        downloads = before.downloads.filterNot { it in downloads },
        pageCache = before.pageCache.filterNot { it.chapterId in chapterIds },
    )
    return ClearPlan(after, titleIds, chapterIds, histories.size + updates.size + tracks.size + searches.size + downloads.size + (before.pageCache.size - after.pageCache.size))
}

internal fun planSourceClear(before: YokanDatabaseSnapshot, types: Set<DbItemType>): ClearPlan {
    val sourceIds = before.sources.filter { it.itemType in types }.mapTo(mutableSetOf()) { it.id }
    val after = before.copy(
        sources = before.sources.filterNot { it.id in sourceIds },
        settings = before.settings.copy(sourcePreferences = before.settings.sourcePreferences?.filterNot { it.sourceId in sourceIds }),
        pageCache = before.pageCache.filterNot { it.sourceId in sourceIds },
    )
    return ClearPlan(after)
}

/** Remote tombstones use this with [recordChange] false while inside applyRemote, so they do not echo. */
@Suppress("UNUSED_PARAMETER")
internal fun removeTitleWithDependents(database: YokanDatabase, mangaId: Long, recordChange: Boolean = false) {
    if (database.manga(mangaId) == null) return
    val before = database.snapshot()
    val chapterIds = before.chapters.filter { it.mangaId == mangaId }.mapTo(mutableSetOf()) { it.id }
    val removedDownloadIds = before.downloads.filter { it.chapterId in chapterIds }.mapTo(mutableSetOf()) { it.id }
    val after = before.copy(
        mangas = before.mangas.filterNot { it.id == mangaId },
        chapters = before.chapters.filterNot { it.id in chapterIds },
        histories = before.histories.filterNot { it.mangaId == mangaId || it.chapterId in chapterIds },
        updates = before.updates.filterNot { it.mangaId == mangaId || it.chapterId in chapterIds },
        downloads = before.downloads.filterNot { it.id in removedDownloadIds },
        tracks = before.tracks.filterNot { it.mangaId == mangaId },
        trackSearches = before.trackSearches.filterNot { it.libraryId == mangaId },
        pageCache = before.pageCache.filterNot { it.chapterId in chapterIds },
        settings = before.settings.copy(
            sortChapterList = before.settings.sortChapterList?.filterNot { it.mangaId == mangaId },
            chapterFilterDownloadedList = before.settings.chapterFilterDownloadedList?.filterNot { it.mangaId == mangaId },
            chapterFilterUnreadList = before.settings.chapterFilterUnreadList?.filterNot { it.mangaId == mangaId },
            chapterFilterBookmarkedList = before.settings.chapterFilterBookmarkedList?.filterNot { it.mangaId == mangaId },
            chapterPageIndexList = before.settings.chapterPageIndexList?.filterNot { it.chapterId in chapterIds },
            personalReaderModeList = before.settings.personalReaderModeList?.filterNot { it.mangaId == mangaId },
            filterScanlatorList = before.settings.filterScanlatorList?.filterNot { it.mangaId == mangaId },
            personalPageModeList = before.settings.personalPageModeList?.filterNot { it.mangaId == mangaId },
            autoScrollPages = before.settings.autoScrollPages?.filterNot { it.mangaId == mangaId },
            titleMetadata = before.settings.titleMetadata?.filterNot { it.mangaId == mangaId },
            updateErrors = before.settings.updateErrors?.filterNot { it.mangaId == mangaId },
            downloadQueueOrder = before.settings.downloadQueueOrder.filterNot { it in removedDownloadIds },
        ),
    )
    // replaceAll publishes the child and parent removals as one snapshot; sync callers run this in applyRemote.
    database.replaceAll(after, expectedSnapshot = before)
}

private fun toDbType(type: ItemType): DbItemType = when (type) {
    ItemType.Manga -> DbItemType.Manga
    ItemType.Anime -> DbItemType.Anime
    ItemType.Novel -> DbItemType.Novel
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/SmartUpdateRules.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/SmartUpdateRules.kt) · implementation · 21 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
10: internal fun DbSmartUpdateRules.permits(manga: DbManga, chapters: List<DbChapter>, now: Long): Boolean {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/SmartUpdateRules.kt) · SHA-256 `34ade3942dd95fc262ba36fa383bd745099ce3a6c9deb2bfd63622f2a6063828`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSmartUpdateRules
import eu.friedcutlet.yokan.database.DbStatus
import eu.friedcutlet.yokan.domain.effectiveChapterUpdateDays

/** Pure admission rule shared by manual library refreshes and all scheduler entry points. */
internal fun DbSmartUpdateRules.permits(manga: DbManga, chapters: List<DbChapter>, now: Long): Boolean {
    if (skipCompleted && manga.status == DbStatus.Completed) return false
    if (onlyCaughtUp && chapters.any { !it.isRead }) return false
    if (onlyStarted && chapters.isNotEmpty() && chapters.none { chapter ->
        chapter.isRead || (chapter.lastPageRead.toDoubleOrNull()?.let { it.isFinite() && it > 0 } == true)
    }) return false
    if (!respectExpectedReleasePeriod) return true
    val days = effectiveChapterUpdateDays(manga.smartUpdateDays,
        if (manga.smartUpdateDays == null) chapters.map { it.dateUpload } else emptyList(), now)
    if (days <= 0) return true
    return now - (manga.lastUpdate ?: 0L) >= days.toLong() * 86_400_000L
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/TorrentUtils.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/TorrentUtils.kt) · implementation · 205 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: object TorrentUtils {
12: fun isTorrentLink(url: String): Boolean =
17: fun fileIndex(link: String): Int? =
28: fun normalizeInfoHash(hash: String): String {
65: fun extractInfoHashFromMagnet(magnetUrl: String): String? {
81: fun extractInfoHashFromUrl(url: String): String? {
104: fun extractMagnetDisplayName(magnetUrl: String): String? {
124: fun normalizeHttpUrls(values: Iterable<String>): List<String> {
144: fun extractMagnetFallbacks(magnetUrl: String): Pair<List<String>, List<String>> {
167: fun mergeTorrentFallbacks(base: Iterable<String>, discovered: Iterable<String>): List<String> {
174: data class MagnetInfo(
182: fun parseMagnet(magnetUrl: String): MagnetInfo {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/TorrentUtils.kt) · SHA-256 `c9686204af49c8913686bf625a9cdca6d0b726dc23b2ed936074da9e77c9c48b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import io.ktor.http.Url
import io.ktor.http.decodeURLQueryComponent

object TorrentUtils {
    private const val BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567"
    private val BTIH_REGEX = Regex("""urn:btih:([a-zA-Z0-9]+)""", RegexOption.IGNORE_CASE)
    private val BTMH_REGEX = Regex("""urn:btmh:(?:1220)?([a-zA-Z0-9]+)""", RegexOption.IGNORE_CASE)

    /** A magnet URI or a `.torrent` file path/URL (Animetail's torrent-video test). */
    fun isTorrentLink(url: String): Boolean =
        url.startsWith("magnet:", ignoreCase = true) ||
            url.substringBefore('#').substringBefore('?').endsWith(".torrent", ignoreCase = true)

    /** Animetail's `index=` file selector inside a magnet/torrent link (TorrServer file ids start at 1). */
    fun fileIndex(link: String): Int? =
        link.substringAfter('?', "").split('&').firstOrNull { it.startsWith("index=") }?.substringAfter('=')?.toIntOrNull()

    /**
     * Normalizes a torrent infohash:
     * - 40 hex characters: lowercased hex.
     * - 32 base32 characters (RFC 4648 / BitTorrent standard): decoded into 20 bytes and returned
     *   as 40 lowercase hex characters.
     * - 64 hex characters (BitTorrent v2 multihash/SHA256): lowercased hex.
     * - Other strings: trimmed and left untouched.
     */
    fun normalizeInfoHash(hash: String): String {
        val clean = hash.trim()
        if (clean.length == 40) {
            return clean.lowercase()
        }
        if (clean.length == 32) {
            val lower = clean.lowercase()
            var buffer = 0
            var bitsLeft = 0
            val bytes = ByteArray(20)
            var byteCount = 0
            for (i in lower.indices) {
                val value = BASE32_ALPHABET.indexOf(lower[i])
                if (value < 0) return clean
                buffer = (buffer shl 5) or value
                bitsLeft += 5
                if (bitsLeft >= 8) {
                    bitsLeft -= 8
                    if (byteCount < 20) {
                        bytes[byteCount++] = ((buffer ushr bitsLeft) and 0xFF).toByte()
                    }
                }
            }
            if (byteCount == 20) {
                return bytes.toHexString()
            }
        }
        if (clean.length == 64 && clean.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }) {
            return clean.lowercase()
        }
        return clean
    }

    /**
     * Extracts and normalizes the infohash from a magnet URI:
     * First checks for BitTorrent v1 (urn:btih:...), then BitTorrent v2 (urn:btmh:...).
     */
    fun extractInfoHashFromMagnet(magnetUrl: String): String? {
        val btihMatch = BTIH_REGEX.find(magnetUrl)
        if (btihMatch != null) {
            return normalizeInfoHash(btihMatch.groupValues[1])
        }
        val btmhMatch = BTMH_REGEX.find(magnetUrl)
        if (btmhMatch != null) {
            return normalizeInfoHash(btmhMatch.groupValues[1])
        }
        return null
    }

    /**
     * Extracts and normalizes an infohash from a stream/playlist URL or magnet link:
     * Checks `infohash` and `ih` query parameters, falling back to magnet URI extraction.
     */
    fun extractInfoHashFromUrl(url: String): String? {
        if (url.isBlank()) return null
        val query = url.substringAfter('?', "")
        if (query.isNotEmpty()) {
            for (param in query.split('&')) {
                val key = param.substringBefore('=')
                if (key.equals("infohash", ignoreCase = true) || key.equals("ih", ignoreCase = true)) {
                    val raw = param.substringAfter('=', "")
                    val decoded = runCatching {
                        raw.decodeURLQueryComponent(plusIsSpace = true)
                    }.getOrDefault(raw)
                    val normalized = normalizeInfoHash(decoded)
                    if (normalized.isNotBlank()) return normalized
                }
            }
        }
        return extractInfoHashFromMagnet(url)
    }

    /**
     * Extracts the display name (`dn`) parameter from a magnet URI, decoding percent escapes
     * and plus spaces.
     */
    fun extractMagnetDisplayName(magnetUrl: String): String? {
        if (!magnetUrl.startsWith("magnet:", ignoreCase = true)) return null
        val query = magnetUrl.substringAfter('?', "")
        if (query.isEmpty()) return null
        for (param in query.split('&')) {
            if (param.startsWith("dn=", ignoreCase = true)) {
                val raw = param.substring(3)
                return runCatching {
                    raw.decodeURLQueryComponent(plusIsSpace = true)
                }.getOrDefault(raw.replace('+', ' '))
            }
        }
        return null
    }

    /**
     * Normalizes a collection of HTTP/HTTPS URLs:
     * Trims, removes empty/invalid items, ensures HTTP or HTTPS scheme, and deduplicates while
     * preserving order.
     */
    fun normalizeHttpUrls(values: Iterable<String>): List<String> {
        val normalized = mutableListOf<String>()
        val seen = mutableSetOf<String>()
        for (value in values) {
            val trimmed = value.trim()
            if (trimmed.isEmpty()) continue
            if (!trimmed.startsWith("http://", ignoreCase = true) && !trimmed.startsWith("https://", ignoreCase = true)) {
                continue
            }
            val parsed = runCatching { Url(trimmed).toString() }.getOrNull() ?: trimmed
            if (seen.add(parsed)) {
                normalized.add(parsed)
            }
        }
        return normalized
    }

    /**
     * Extracts fallback download sources (`xs`, `as`) and webseeds (`ws`) from a magnet URI.
     */
    fun extractMagnetFallbacks(magnetUrl: String): Pair<List<String>, List<String>> {
        if (!magnetUrl.startsWith("magnet:", ignoreCase = true)) {
            return Pair(emptyList(), emptyList())
        }
        val query = magnetUrl.substringAfter('?', "")
        if (query.isEmpty()) return Pair(emptyList(), emptyList())
        val sources = mutableListOf<String>()
        val webseeds = mutableListOf<String>()
        for (param in query.split('&')) {
            val key = param.substringBefore('=').lowercase()
            val raw = param.substringAfter('=', "")
            val decoded = runCatching { raw.decodeURLQueryComponent(plusIsSpace = true) }.getOrDefault(raw)
            when (key) {
                "xs", "as" -> sources.add(decoded)
                "ws" -> webseeds.add(decoded)
            }
        }
        return Pair(normalizeHttpUrls(sources), normalizeHttpUrls(webseeds))
    }

    /**
     * Merges base and discovered fallback URLs.
     */
    fun mergeTorrentFallbacks(base: Iterable<String>, discovered: Iterable<String>): List<String> {
        return normalizeHttpUrls(base + discovered)
    }

    /**
     * Complete parsed magnet metadata.
     */
    data class MagnetInfo(
        val infoHash: String?,
        val displayName: String?,
        val sources: List<String>,
        val webseeds: List<String>,
        val trackers: List<String>,
    )

    fun parseMagnet(magnetUrl: String): MagnetInfo {
        val infoHash = extractInfoHashFromMagnet(magnetUrl)
        val displayName = extractMagnetDisplayName(magnetUrl)
        val (sources, webseeds) = extractMagnetFallbacks(magnetUrl)
        val trackers = mutableListOf<String>()
        val query = magnetUrl.substringAfter('?', "")
        if (query.isNotEmpty()) {
            for (param in query.split('&')) {
                if (param.startsWith("tr=", ignoreCase = true)) {
                    val raw = param.substring(3)
                    val decoded = runCatching { raw.decodeURLQueryComponent(plusIsSpace = true) }.getOrDefault(raw)
                    if (decoded.isNotBlank()) trackers.add(decoded)
                }
            }
        }
        return MagnetInfo(
            infoHash = infoHash,
            displayName = displayName,
            sources = sources,
            webseeds = webseeds,
            trackers = trackers.distinct(),
        )
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/LibrarySearch.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/LibrarySearch.kt) · implementation · 239 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
13: internal class LibrarySearchQuery(
20: fun matches(manga: Manga): Boolean = predicate(SearchEntry(manga, index, scheduleIndex, now))
23: private typealias SearchPredicate = (SearchEntry) -> Boolean
25: private class SearchEntry(val manga: Manga, index: LibraryIndex, private val scheduleIndex: LibraryIndex, private val now: Long) {
46: private fun generalSearch(value: String): SearchPredicate = { entry ->
52: private fun legacySearch(query: String): SearchPredicate {
57: private fun compileSearch(query: String): SearchPredicate {
83: private enum class SearchTokenKind { Value, And, Or, Not, Open, Close }
84: private data class SearchToken(val kind: SearchTokenKind, val text: String = "", val quoted: Boolean = false, val literal: Boolean = false)
85: private class SearchSyntaxException : Exception()
88: private fun tokenizeSearch(text: String): List<SearchToken> {
142: private class SearchParser(private val tokens: List<SearchToken>) {
144: private fun peek() = tokens.getOrNull(position)?.kind
145: fun parse(): SearchPredicate {
150: private fun or(depth: Int): SearchPredicate {
155: private fun and(depth: Int): SearchPredicate {
163: private fun term(depth: Int): SearchPredicate {
182: private data class SearchField(val name: String, val comparator: String, val value: String)
183: private fun fieldParts(text: String): SearchField? {
190: private fun compileTerm(text: String): SearchPredicate {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/LibrarySearch.kt) · SHA-256 `e8197c51799177a45763ee2653eeb0949bdb676897bc5cbb5be559be41e6e42d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui

import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.domain.effectiveChapterUpdateDays
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn

/** Compiled once per query, with no database access or parsing in the per-title predicate. */
internal class LibrarySearchQuery(
    query: String,
    private val index: LibraryIndex = LibraryIndex.Empty,
    private val now: Long = nowMillis(),
    private val scheduleIndex: LibraryIndex = index,
) {
    private val predicate: SearchPredicate = compileSearch(query)
    fun matches(manga: Manga): Boolean = predicate(SearchEntry(manga, index, scheduleIndex, now))
}

private typealias SearchPredicate = (SearchEntry) -> Boolean

private class SearchEntry(val manga: Manga, index: LibraryIndex, private val scheduleIndex: LibraryIndex, private val now: Long) {
    private val chapters = index.chapters(manga.id)
    val total get() = chapters.size.toLong()
    private var cachedRead: Long? = null
    val read get() = cachedRead ?: chapters.count { it.isRead }.toLong().also { cachedRead = it }
    val unread get() = total - read
    private var cachedInterval: Long? = null
    val interval get() = cachedInterval ?: effectiveChapterUpdateDays(manga.smartUpdateDays,
        if (manga.smartUpdateDays == null) scheduleIndex.chapters(manga.id).map(Chapter::dateUpload) else emptyList(), now)
        .toLong().also { cachedInterval = it }
    val nextUpdate: Long? get() = manga.lastUpdateMillis.takeIf { it > 0 }?.let {
        val delay = interval * SearchDayMillis
        if (it > Long.MAX_VALUE - delay) Long.MAX_VALUE else it + delay
    }
}

private const val SearchDayMillis = 86_400_000L
private const val MaxSearchLength = 4096
private const val MaxSearchTokens = 256
private const val MaxSearchDepth = 24

private fun generalSearch(value: String): SearchPredicate = { entry ->
    val manga = entry.manga
    manga.name.contains(value, true) || manga.alternativeTitles.any { it.contains(value, true) } ||
        manga.source.contains(value, true) || manga.genres.any { it.contains(value, true) }
}

private fun legacySearch(query: String): SearchPredicate {
    val values = query.split(',').map(String::trim).filter(String::isNotEmpty).map(::generalSearch)
    return { entry -> values.isEmpty() || values.any { it(entry) } }
}

private fun compileSearch(query: String): SearchPredicate {
    val text = query.trim()
    if (text.length > MaxSearchLength) return generalSearch(text)
    if (text.isEmpty()) return { true }
    // Preserve existing exact, multiword genre links, including tags containing commas.
    if (text.startsWith("genre:", true) && text.none { it in "\"'()&|" } &&
        text.substringAfter(':').none { it in ":<=>" } &&
        !Regex("\\s(?:(?:AND|OR|NOT)(?:\\s|$)|-\\S)").containsMatchIn(text)
    ) {
        val genre = text.substringAfter(':').trim()
        return { entry -> entry.manga.genres.any { it.trim().equals(genre, true) } }
    }
    return try {
        val tokens = tokenizeSearch(text)
        if (tokens.none { (it.kind != SearchTokenKind.Value && it.kind != SearchTokenKind.Or) ||
                (it.kind == SearchTokenKind.Value && (fieldParts(it.text) != null || it.quoted)) } &&
            "||" !in text
        ) {
            legacySearch(text)
        } else SearchParser(tokens).parse()
    } catch (_: SearchSyntaxException) {
        // Never apply only the valid prefix of a malformed expression.
        generalSearch(text)
    }
}

private enum class SearchTokenKind { Value, And, Or, Not, Open, Close }
private data class SearchToken(val kind: SearchTokenKind, val text: String = "", val quoted: Boolean = false, val literal: Boolean = false)
private class SearchSyntaxException : Exception()

/** Bounded linear scanner; quoted field values may contain operators and escaped quotes. */
private fun tokenizeSearch(text: String): List<SearchToken> {
    val tokens = mutableListOf<SearchToken>()
    var position = 0
    while (position < text.length) {
        val char = text[position]
        if (char.isWhitespace()) { position++; continue }
        if (tokens.size >= MaxSearchTokens) throw SearchSyntaxException()
        val kind = when {
            char == '(' -> SearchTokenKind.Open
            char == ')' -> SearchTokenKind.Close
            char == ',' -> SearchTokenKind.Or
            char == '-' && position + 1 < text.length && !text[position + 1].isWhitespace() -> SearchTokenKind.Not
            text.startsWith("&&", position) -> SearchTokenKind.And
            text.startsWith("||", position) -> SearchTokenKind.Or
            else -> null
        }
        if (kind != null) {
            tokens += SearchToken(kind)
            position += if (char == '&' || char == '|') 2 else 1
            continue
        }
        val value = StringBuilder()
        val literal = char == '"' || char == '\''
        var quoted = false
        while (position < text.length) {
            val current = text[position]
            if (current.isWhitespace() || current in "()," || text.startsWith("&&", position) || text.startsWith("||", position)) break
            if ((current == '"' || current == '\'') && (value.isEmpty() || value.last() in ":<=>")) {
                quoted = true
                val quote = current
                position++
                var closed = false
                while (position < text.length) {
                    val next = text[position++]
                    if (next == quote) { closed = true; break }
                    if (next == '\\' && position < text.length && (text[position] == quote || text[position] == '\\')) {
                        value.append(text[position++])
                    } else value.append(next)
                }
                if (!closed) throw SearchSyntaxException()
            } else { value.append(current); position++ }
        }
        val word = value.toString()
        val wordKind = if (quoted) SearchTokenKind.Value else when (word) {
            "AND" -> SearchTokenKind.And
            "OR" -> SearchTokenKind.Or
            "NOT" -> SearchTokenKind.Not
            else -> SearchTokenKind.Value
        }
        tokens += SearchToken(wordKind, word, quoted, literal)
    }
    return tokens
}

private class SearchParser(private val tokens: List<SearchToken>) {
    private var position = 0
    private fun peek() = tokens.getOrNull(position)?.kind
    fun parse(): SearchPredicate {
        val result = or(0)
        if (position != tokens.size) throw SearchSyntaxException()
        return result
    }
    private fun or(depth: Int): SearchPredicate {
        val children = mutableListOf(and(depth))
        while (peek() == SearchTokenKind.Or) { position++; children += and(depth) }
        return if (children.size == 1) children.first() else { entry -> children.any { it(entry) } }
    }
    private fun and(depth: Int): SearchPredicate {
        val children = mutableListOf(term(depth))
        while (peek() != null && peek() != SearchTokenKind.Or && peek() != SearchTokenKind.Close) {
            if (peek() == SearchTokenKind.And) position++
            children += term(depth)
        }
        return if (children.size == 1) children.first() else { entry -> children.all { it(entry) } }
    }
    private fun term(depth: Int): SearchPredicate {
        var negate = false
        while (peek() == SearchTokenKind.Not) { negate = !negate; position++ }
        val token = tokens.getOrNull(position++) ?: throw SearchSyntaxException()
        val child = when (token.kind) {
            SearchTokenKind.Open -> {
                if (depth >= MaxSearchDepth) throw SearchSyntaxException()
                val result = or(depth + 1)
                if (peek() != SearchTokenKind.Close) throw SearchSyntaxException()
                position++
                result
            }
            SearchTokenKind.Value -> if (token.literal) generalSearch(token.text) else compileTerm(token.text)
            else -> throw SearchSyntaxException()
        }
        return if (negate) { entry -> !child(entry) } else child
    }
}

private data class SearchField(val name: String, val comparator: String, val value: String)
private fun fieldParts(text: String): SearchField? {
    val position = text.indexOfFirst { it in ":<=>" }
    if (position <= 0 || text.take(position).any { !it.isLetterOrDigit() && it != '_' }) return null
    val end = if (text[position] != ':' && text.getOrNull(position + 1) == '=') position + 2 else position + 1
    return SearchField(text.take(position).lowercase(), text.substring(position, end), text.substring(end))
}

private fun compileTerm(text: String): SearchPredicate {
    val field = fieldParts(text) ?: return generalSearch(text)
    val value = field.value
    if (value.isEmpty()) throw SearchSyntaxException()
    if (field.comparator == ":") {
        return when (field.name) {
            "title" -> { entry -> entry.manga.name.contains(value, true) || entry.manga.alternativeTitles.any { it.contains(value, true) } }
            "author" -> { entry -> entry.manga.author?.contains(value, true) == true }
            "artist" -> { entry -> entry.manga.artist?.contains(value, true) == true }
            "description", "desc" -> { entry -> entry.manga.description.contains(value, true) }
            "genre", "tag" -> { entry -> entry.manga.genres.any { it.trim().equals(value, true) } }
            "source", "src" -> { entry -> entry.manga.source.contains(value, true) }
            "notes", "note" -> { entry -> entry.manga.privateNote.contains(value, true) }
            "language", "lang" -> { entry -> entry.manga.lang.equals(value, true) }
            "source_id", "sourceid", "src_id", "srcid" -> {
                val id = value.toLongOrNull() ?: throw SearchSyntaxException();
                { entry -> entry.manga.sourceId == id }
            }
            "status" -> { entry -> entry.manga.status.name.equals(value, true) || entry.manga.status.label.equals(value, true) }
            "type" -> { entry -> entry.manga.itemType.name.equals(value, true) }
            else -> generalSearch(text)
        }
    }
    val actual: (SearchEntry) -> Long? = when (field.name) {
        "id" -> { entry -> entry.manga.id }
        "total" -> { entry -> entry.total }
        "read" -> { entry -> entry.read }
        "unread" -> { entry -> entry.unread }
        "fetchinterval", "fi" -> { entry -> entry.interval }
        "added" -> { entry -> entry.manga.dateAddedMillis.takeIf { it > 0 }?.div(SearchDayMillis) }
        "nextupdate", "nu" -> { entry -> entry.nextUpdate?.div(SearchDayMillis) }
        else -> return generalSearch(text)
    }
    val dateField = field.name in setOf("added", "nextupdate", "nu")
    val expected = if (dateField) runCatching {
        LocalDate.parse(value).atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds() / SearchDayMillis
    }.getOrNull() else value.toLongOrNull()
    if (expected == null) throw SearchSyntaxException()
    return { entry ->
        val found = actual(entry)
        found != null && when (field.comparator) {
            ">" -> found > expected
            ">=" -> found >= expected
            "<" -> found < expected
            "<=" -> found <= expected
            "=" -> found == expected
            else -> false
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/BulkCategoriesDialog.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/BulkCategoriesDialog.kt) · implementation · 110 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
38: internal fun BulkCategoriesDialog(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/BulkCategoriesDialog.kt) · SHA-256 `98be970ac6c1cbe1d11edea6698d4575f417e8fc9b36226888e2f80344c58c12`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Checkbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.manga
import yokan.composeapp.generated.resources.ok
import yokan.composeapp.generated.resources.set_categories
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import eu.friedcutlet.yokan.ui.components.hoverHighlight

/** Sets the categories of [selectedTitles]; starts from the categories they all share. */
@Composable
internal fun BulkCategoriesDialog(
    categories: List<Category>,
    selectedTitles: List<Manga>,
    onConfirm: (categoryIds: List<Long>) -> Unit,
    onDismiss: () -> Unit,
) {
    val initial = remember(selectedTitles) {
        val sets = selectedTitles.map { it.categories.toSet() }
        if (sets.isEmpty()) emptySet() else sets.reduce { acc, set -> acc intersect set }
    }
    var working by remember { mutableStateOf(initial) }
    androidx.compose.material3.AlertDialog(
        onDismissRequest = onDismiss,
        modifier = Modifier.compactDialogWidth(),
        shape = MaterialTheme.shapes.extraLarge,
        title = {
            Text(
                stringResource(Res.string.set_categories),
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
            )
        },
        text = {
            if (categories.isEmpty()) {
                Text("You don't have any categories yet", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
            } else {
                Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
                    categories.forEach { category ->
                        val checked = category.id in working
                        androidx.compose.material3.Surface(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(MaterialTheme.shapes.large)
                                .hoverHighlight(onClick = {
                                    working = if (checked) working - category.id else working + category.id
                                }),
                            shape = MaterialTheme.shapes.large,
                            color = if (checked) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f)
                            else androidx.compose.ui.graphics.Color.Transparent,
                        ) {
                            Row(
                                modifier = Modifier.padding(horizontal = 4.dp, vertical = 6.dp),
                                verticalAlignment = Alignment.CenterVertically,
                            ) {
                                androidx.compose.material3.Checkbox(checked = checked, onCheckedChange = {
                                    working = if (it) working + category.id else working - category.id
                                })
                                Spacer(Modifier.width(8.dp))
                                Text(
                                    category.name,
                                    modifier = Modifier.weight(1f),
                                    style = MaterialTheme.typography.bodyLarge,
                                    fontWeight = if (checked) FontWeight.Medium else FontWeight.Normal,
                                )
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            androidx.compose.material3.TextButton(onClick = {
                onConfirm(working.toList())
                onDismiss()
            }) { Text(stringResource(Res.string.ok)) }
        },
        dismissButton = {
            androidx.compose.material3.TextButton(onClick = onDismiss) {
                Text(stringResource(Res.string.action_cancel))
            }
        },
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/DisplayTypeSelector.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/DisplayTypeSelector.kt) · implementation · 55 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
20: internal fun DisplayTypeSelector(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/DisplayTypeSelector.kt) · SHA-256 `2858498ec9524215c876d06bedd93caa655721b7526314636c70fb9eac12e016`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import eu.friedcutlet.yokan.domain.DisplayType

@Composable
internal fun DisplayTypeSelector(
    selected: DisplayType,
    onSelected: (DisplayType) -> Unit,
    modifier: Modifier = Modifier,
) {
    val buttonShape = RoundedCornerShape(10.dp)
    FlowRow(modifier = modifier) {
        DisplayType.entries.forEach { displayType ->
            val selectedOption = selected == displayType
            Surface(
                modifier = Modifier
                    .padding(end = 5.dp)
                    .clip(buttonShape)
                    .clickable { onSelected(displayType) },
                shape = buttonShape,
                color = if (selectedOption) {
                    MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)
                } else {
                    Color.Transparent
                },
                border = if (selectedOption) {
                    null
                } else {
                    BorderStroke(0.8.dp, MaterialTheme.colorScheme.onSurface)
                },
            ) {
                Text(
                    text = displayType.label,
                    modifier = Modifier.padding(horizontal = 15.dp, vertical = 10.dp),
                    color = MaterialTheme.colorScheme.onSurface,
                    fontSize = 14.sp,
                )
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryContract.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryContract.kt) · implementation · 51 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
8: data class LibraryTrackerChoice(val id: Int, val name: String? = null)
11: data class LibraryState(
34: sealed interface LibraryEvent {
35: data object Refresh : LibraryEvent
36: data object RefreshAirings : LibraryEvent
37: data class Search(val query: String) : LibraryEvent
38: data class SelectCategory(val categoryId: Long?) : LibraryEvent
40: data class UpdateSettings(val transform: (DbSettings) -> DbSettings) : LibraryEvent
41: data class BeginSelection(val mangaId: Long) : LibraryEvent
42: data class ToggleSelection(val mangaId: Long) : LibraryEvent
43: data object ClearSelection : LibraryEvent
44: data object SelectAll : LibraryEvent
45: data object InvertSelection : LibraryEvent
46: data class MarkSelectedRead(val isRead: Boolean) : LibraryEvent
47: data class SetSelectedCategories(val categoryIds: List<Long>) : LibraryEvent
48: data class RemoveSelected(val fromLibrary: Boolean, val downloads: Boolean) : LibraryEvent
49: data object RescanLocalLibrary : LibraryEvent
50: data class ImportTorrent(val pathOrMagnet: String) : LibraryEvent
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryContract.kt) · SHA-256 `2eb57145ebf09fb01b32d590374652a703206308fa2dc4adad17b759c6c64599`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.library.LibraryAiringRefreshResult

data class LibraryTrackerChoice(val id: Int, val name: String? = null)

/** One item type's library screen. */
data class LibraryState(
    val itemType: ItemType,
    val query: LibraryQuery,
    val display: LibraryDisplay,
    /** `null` until the first pass over the library finished. */
    val content: LibraryContent? = null,
    val badges: Map<Long, LibraryBadgeSummary> = emptyMap(),
    /** The shown category; `null` shows every category. */
    val selectedCategoryId: Long? = null,
    val selectedIds: Set<Long> = emptySet(),
    val refreshing: Boolean = false,
    val lastRefreshSummary: String? = null,
    val trackerProviders: List<LibraryTrackerChoice> = emptyList(),
    val refreshingAirings: Boolean = false,
    val airingRefreshResult: LibraryAiringRefreshResult? = null,
    val airingRefreshFailed: Boolean = false,
) {
    val selectionMode: Boolean get() = selectedIds.isNotEmpty()

    /** The filtered entries of the shown category. */
    val currentItems: List<Manga> get() = content?.items(selectedCategoryId).orEmpty()
}

sealed interface LibraryEvent {
    data object Refresh : LibraryEvent
    data object RefreshAirings : LibraryEvent
    data class Search(val query: String) : LibraryEvent
    data class SelectCategory(val categoryId: Long?) : LibraryEvent
    /** Filter, sort and display changes, written through the settings store. */
    data class UpdateSettings(val transform: (DbSettings) -> DbSettings) : LibraryEvent
    data class BeginSelection(val mangaId: Long) : LibraryEvent
    data class ToggleSelection(val mangaId: Long) : LibraryEvent
    data object ClearSelection : LibraryEvent
    data object SelectAll : LibraryEvent
    data object InvertSelection : LibraryEvent
    data class MarkSelectedRead(val isRead: Boolean) : LibraryEvent
    data class SetSelectedCategories(val categoryIds: List<Long>) : LibraryEvent
    data class RemoveSelected(val fromLibrary: Boolean, val downloads: Boolean) : LibraryEvent
    data object RescanLocalLibrary : LibraryEvent
    data class ImportTorrent(val pathOrMagnet: String) : LibraryEvent
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryFilters.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryFilters.kt) · implementation · 330 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
27: enum class LibraryFilterKind(val label: String) {
37: data class LibraryFilterTypes(
47: fun value(kind: LibraryFilterKind): Int = when (kind) {
58: data class LibraryBadgeSummary(
68: internal fun buildLibraryBadgeSummaries(
90: data class LibraryQuery(
102: internal fun DbSettings.libraryQuery(type: ItemType) = LibraryQuery(
115: data class LibraryCategoryTab(val id: Long, val name: String, val count: Int, val label: LibraryTabLabel = LibraryTabLabel.Name)
117: enum class LibraryTabLabel { Name, All, Untracked, Untagged, UnknownSource }
123: class LibraryContent(
137: fun items(categoryId: Long?): List<Manga> =
139: fun containsCategory(categoryId: Long): Boolean = categoryId in byCategory
142: internal fun libraryContent(
189: internal class LibraryReleaseSelector {
197: fun select(library: List<Manga>, source: LibraryIndex, query: LibraryQuery): LibraryIndex {
216: private fun selectLibraryReleases(library: List<Manga>, index: LibraryIndex, query: LibraryQuery): LibraryIndex {
228: private fun sortLibrary(items: List<Manga>, sort: DbSortLibraryManga, index: LibraryIndex, randomSeed: Long, sourceIndex: LibraryIndex): List<Manga> {
265: private fun <T : Comparable<T>> sortKnownLibraryValues(
285: private fun matchesLibraryFilters(
317: private class LibraryProviderFilter(filters: Map<Int, Int>) {
320: fun matches(providers: List<LibraryTrack>): Boolean {
326: private fun filterMatches(type: Int, value: Boolean): Boolean = when (type) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryFilters.kt) · SHA-256 `e7dccaeb3a2d5c4486b41fdfe9c550eb26654047061cdf18208c7556dfdae66a`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.data.LibraryTrack
import kotlin.random.Random
import eu.friedcutlet.yokan.services.tracking.normalizedTrackerScore
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.database.DbLibraryGrouping
import eu.friedcutlet.yokan.database.DbCategoryLibraryPreferences
import eu.friedcutlet.yokan.database.DbChapterReleasePreference
import eu.friedcutlet.yokan.database.DbFilterScanlator
import eu.friedcutlet.yokan.database.chapterReleasePreference
import eu.friedcutlet.yokan.domain.selectChapterReleases
import eu.friedcutlet.yokan.services.library.scanlatorFilter
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSortLibraryManga
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Status
import eu.friedcutlet.yokan.ui.LibrarySearchQuery

const val UncategorizedCategoryId = -1L
internal const val AllLibraryTabId = Long.MIN_VALUE

enum class LibraryFilterKind(val label: String) {
    Downloaded("Downloaded"),
    Unread("Unread"),
    Started("Started"),
    Bookmarked("Bookmarked"),
    Completed("Completed"),
    Tracking("Tracking"),
    CustomInterval("Custom update interval"),
}

data class LibraryFilterTypes(
    val downloaded: Int,
    val unread: Int,
    val started: Int,
    val bookmarked: Int,
    val completed: Int,
    val tracking: Int,
    val customInterval: Int = 0,
    val providerTracking: Map<Int, Int> = emptyMap(),
) {
    fun value(kind: LibraryFilterKind): Int = when (kind) {
        LibraryFilterKind.Downloaded -> downloaded
        LibraryFilterKind.Unread -> unread
        LibraryFilterKind.Started -> started
        LibraryFilterKind.Bookmarked -> bookmarked
        LibraryFilterKind.Completed -> completed
        LibraryFilterKind.Tracking -> tracking
        LibraryFilterKind.CustomInterval -> customInterval
    }
}

data class LibraryBadgeSummary(
    val unreadCount: Int = 0,
    val downloadedCount: Int = 0,
    val totalCount: Int = 0,
    val readCount: Int = 0,
) {
    val progress: Float
        get() = if (totalCount > 0) (readCount.toFloat() / totalCount.toFloat()).coerceIn(0f, 1f) else 0f
}

internal fun buildLibraryBadgeSummaries(
    chaptersByManga: Map<Long, List<Chapter>>,
    completedDownloadCountsByChapterId: Map<Long, Int>,
    mangaTitles: Map<Long, String> = emptyMap(),
    releaseSettings: DbSettings? = null,
): Map<Long, LibraryBadgeSummary> = chaptersByManga.mapValues { (mangaId, all) ->
    val chapters = if (releaseSettings == null) all else selectChapterReleases(mangaTitles[mangaId].orEmpty(), all,
        releaseSettings.chapterReleasePreference(mangaId).toPolicy(), releaseSettings.scanlatorFilter(mangaId),
        completedDownloadCountsByChapterId.keys, offlineOnly = releaseSettings.downloadedOnlyMode)
    val read = chapters.count { it.isRead }
    LibraryBadgeSummary(
        unreadCount = chapters.count { !it.isRead },
        downloadedCount = chapters.asSequence()
            .map { it.id }
            .distinct()
            .sumOf { completedDownloadCountsByChapterId[it] ?: 0 },
        totalCount = chapters.size,
        readCount = read,
    )
}

/** The settings that decide which library entries show and in which order. */
data class LibraryQuery(
    val search: String,
    val filters: LibraryFilterTypes,
    val sort: DbSortLibraryManga,
    val downloadedOnly: Boolean,
    val releasePreferences: List<DbChapterReleasePreference> = emptyList(),
    val hiddenScanlators: List<DbFilterScanlator> = emptyList(),
    val grouping: DbLibraryGrouping = DbLibraryGrouping.Categories,
    val categoryPreferences: Map<Long, DbCategoryLibraryPreferences> = emptyMap(),
    val randomSeed: Long = 0,
)

internal fun DbSettings.libraryQuery(type: ItemType) = LibraryQuery(
    search = librarySearch(type),
    filters = libraryFilters(type),
    sort = librarySort(type),
    downloadedOnly = downloadedOnlyMode,
    releasePreferences = chapterReleasePreferences,
    hiddenScanlators = filterScanlatorList.orEmpty(),
    grouping = features.library.grouping(type.toDb()),
    categoryPreferences = features.library.categories(type.toDb()),
    randomSeed = features.library.randomSeeds[type.toDb()] ?: 0,
)

/** A category tab; [name] is empty for [UncategorizedCategoryId], which the screen labels. */
data class LibraryCategoryTab(val id: Long, val name: String, val count: Int, val label: LibraryTabLabel = LibraryTabLabel.Name)

enum class LibraryTabLabel { Name, All, Untracked, Untagged, UnknownSource }

/**
 * One item type's library after filters, search and sort, split per category. A plain class:
 * equality is identity, so publishing a rebuilt one never deep-compares the lists.
 */
class LibraryContent(
    /** Every library entry of the type, in database order. */
    val library: List<Manga>,
    /** Every category of the type, hidden ones included. */
    val categories: List<Category>,
    private val filtered: List<Manga>,
    private val byCategory: Map<Long, List<Manga>>,
    /** Uncategorized (when any entry has no category) followed by the visible categories. */
    val tabs: List<LibraryCategoryTab>,
    /** Entries whose title contains the search, ignoring filters and categories. */
    val searchMatches: List<Manga>,
    val grouping: DbLibraryGrouping = DbLibraryGrouping.Categories,
) {
    /** Filtered entries of [categoryId]; `null` means all categories. */
    fun items(categoryId: Long?): List<Manga> =
        if (categoryId == null) filtered else byCategory[categoryId].orEmpty()
    fun containsCategory(categoryId: Long): Boolean = categoryId in byCategory
}

internal fun libraryContent(
    library: List<Manga>,
    categories: List<Category>,
    index: LibraryIndex,
    query: LibraryQuery,
    effectiveIndex: LibraryIndex = selectLibraryReleases(library, index, query),
): LibraryContent {
    val search = LibrarySearchQuery(query.search, effectiveIndex, scheduleIndex = index)
    val matching = if (query.search.isBlank()) library else library.filter(search::matches)
    val downloadedChapterIds = effectiveIndex.downloadedChapterIds
    val providers = LibraryProviderFilter(query.filters.providerTracking)
    val filtered = sortLibrary(
        items = matching.filter { matchesLibraryFilters(it, query, effectiveIndex, downloadedChapterIds, providers) },
        sort = query.sort,
        index = effectiveIndex, randomSeed = query.randomSeed, sourceIndex = index,
    )
    val manual = query.grouping == DbLibraryGrouping.Categories
    val byCategory = if (manual) {
        val memberships = categories.associate { it.id to mutableListOf<Manga>() }.toMutableMap()
        memberships[UncategorizedCategoryId] = mutableListOf()
        filtered.forEach { manga ->
            if (manga.categories.isEmpty()) memberships.getValue(UncategorizedCategoryId).add(manga)
            else manga.categories.distinct().forEach { memberships[it]?.add(manga) }
        }
        memberships.mapValues { (id, members) ->
            val scoped = if (id == UncategorizedCategoryId) null else query.categoryPreferences[id]?.sort
            if (scoped == null || scoped == query.sort) members else sortLibrary(members, scoped, effectiveIndex, query.randomSeed, index)
        }
    } else emptyMap()
    val tabs = if (manual) buildList {
        if (library.any { it.categories.isEmpty() }) {
            add(LibraryCategoryTab(UncategorizedCategoryId, "", byCategory.getValue(UncategorizedCategoryId).size))
        }
        categories.filterNot { it.hidden }.forEach { category ->
            add(LibraryCategoryTab(category.id, category.name, byCategory.getValue(category.id).size))
        }
    } else emptyList()
    val searchMatches = if (query.search.isBlank()) {
        emptyList()
    } else {
        matching
    }
    val groups = if (manual) null else automaticLibraryGroups(library, filtered, categories, effectiveIndex, query.grouping)
    return LibraryContent(library, categories, filtered, groups?.members ?: byCategory, groups?.tabs ?: tabs, searchMatches, query.grouping)
}

/** Only release-policy or library changes invalidate chapter selection, never search or sort. */
internal class LibraryReleaseSelector {
    private var titles: List<Manga>? = null
    private var index: LibraryIndex? = null
    private var preferences: List<DbChapterReleasePreference>? = null
    private var hidden: List<DbFilterScanlator>? = null
    private var offline = false
    private var selected = LibraryIndex.Empty

    fun select(library: List<Manga>, source: LibraryIndex, query: LibraryQuery): LibraryIndex {
        if (library !== titles || source.chaptersByManga !== index?.chaptersByManga ||
            source.downloadedChapterIds != index?.downloadedChapterIds || preferences != query.releasePreferences ||
            hidden != query.hiddenScanlators || offline != query.downloadedOnly
        ) {
            selected = selectLibraryReleases(library, source, query)
            titles = library
            preferences = query.releasePreferences
            hidden = query.hiddenScanlators
            offline = query.downloadedOnly
        } else if (source !== index) {
            selected = LibraryIndex(selected.chaptersByManga, source.completedDownloadCountsByChapterId,
                source.trackedMangaIds, source.tracksByManga)
        }
        index = source
        return selected
    }
}

private fun selectLibraryReleases(library: List<Manga>, index: LibraryIndex, query: LibraryQuery): LibraryIndex {
    val releaseSettings = DbSettings(chapterReleasePreferences = query.releasePreferences, filterScanlatorList = query.hiddenScanlators)
    return LibraryIndex(
        chaptersByManga = library.associate { manga -> manga.id to selectChapterReleases(manga.name, index.chapters(manga.id),
            releaseSettings.chapterReleasePreference(manga.id).toPolicy(), releaseSettings.scanlatorFilter(manga.id),
            index.downloadedChapterIds, offlineOnly = query.downloadedOnly) },
        completedDownloadCountsByChapterId = index.completedDownloadCountsByChapterId,
        trackedMangaIds = index.trackedMangaIds,
        tracksByManga = index.tracksByManga,
    )
}

private fun sortLibrary(items: List<Manga>, sort: DbSortLibraryManga, index: LibraryIndex, randomSeed: Long, sourceIndex: LibraryIndex): List<Manga> {
    val names = items.associate { it.id to it.name.lowercase() }
    when (sort.index) {
        7 -> return sortKnownLibraryValues(items, sort, names) { Random(randomSeed xor it.id).nextLong() }
        8 -> return sortKnownLibraryValues(items, sort, names) { manga ->
            index.tracksByManga[manga.id].orEmpty().distinctBy { it.providerId }.mapNotNull {
                normalizedTrackerScore(it.providerId, it.score, it.scoreMaximum)
            }.average().takeUnless { it.isNaN() }
        }
        9 -> return sortKnownLibraryValues(items, sort, names) { manga ->
            sourceIndex.chapters(manga.id).maxOfOrNull { it.fetchedAt }?.takeIf { it > 0 }
        }
        10 -> {
            val counts = items.associate { it.id to index.chapters(it.id).count { chapter -> !chapter.isRead } }
            val first = if (sort.reverse) compareByDescending<Manga> { counts[it.id] ?: 0 } else compareBy<Manga> { counts[it.id] ?: 0 }
            return sortKnownLibraryValues(items, sort, names, beforeValues = first) { manga -> manga.nextEpisodeAiringAt.takeIf { it > 0 } }
        }
    }
    val unread = if (sort.index == 3) items.associate { manga ->
        manga.id to index.chapters(manga.id).count { !it.isRead }
    } else emptyMap()
    val comparator = when (sort.index) {
        1 -> compareBy<Manga> { it.lastReadMillis }.thenBy { names[it.id].orEmpty() }
        2 -> compareBy<Manga> { it.lastUpdateMillis }.thenBy { names[it.id].orEmpty() }
        3 -> compareBy<Manga> { unread[it.id] ?: 0 }
            .thenBy { names[it.id].orEmpty() }
        4 -> compareBy<Manga> { index.chapters(it.id).size }.thenBy { names[it.id].orEmpty() }
        5 -> compareBy<Manga> { index.chapters(it.id).lastOrNull()?.dateUpload.orEmpty() }
            .thenBy { names[it.id].orEmpty() }
        6 -> compareBy<Manga> { it.dateAddedMillis }.thenBy { names[it.id].orEmpty() }
        else -> compareBy<Manga> { names[it.id].orEmpty() }
    }
    val sorted = items.sortedWith(comparator)
    return if (sort.reverse) sorted.asReversed() else sorted
}

/** Missing data stays last in either direction; values and names are computed once, outside comparisons. */
private fun <T : Comparable<T>> sortKnownLibraryValues(
    items: List<Manga>, sort: DbSortLibraryManga, names: Map<Long, String>, beforeValues: Comparator<Manga>? = null, value: (Manga) -> T?,
): List<Manga> {
    val values = items.associate { it.id to value(it) }
    return items.sortedWith { first, second ->
        val before = beforeValues?.compare(first, second) ?: 0
        if (before != 0) return@sortedWith before
        val a = values[first.id]
        val b = values[second.id]
        val comparison = when {
            a == null -> if (b == null) 0 else 1
            b == null -> -1
            sort.reverse -> b.compareTo(a)
            else -> a.compareTo(b)
        }
        if (comparison != 0) comparison else names[first.id].orEmpty().compareTo(names[second.id].orEmpty())
            .takeIf { it != 0 } ?: first.id.compareTo(second.id)
    }
}

private fun matchesLibraryFilters(
    manga: Manga,
    query: LibraryQuery,
    index: LibraryIndex,
    downloadedChapterIds: Set<Long>,
    providers: LibraryProviderFilter,
): Boolean {
    val filters = query.filters
    val chapters = index.chapters(manga.id)
    val hasDownloaded = chapters.any { it.id in downloadedChapterIds }
    val hasUnread = chapters.any { !it.isRead }
    val allRead = chapters.all { it.isRead }

    if (filters.downloaded == 1 || query.downloadedOnly) {
        if (!hasDownloaded) return false
    } else if (filters.downloaded == 2 && hasDownloaded) {
        return false
    }

    if (filters.unread == 1 || filters.started == 1) {
        if (!hasUnread) return false
    } else if (filters.unread == 2 || filters.started == 2) {
        if (!allRead) return false
    }

    return filterMatches(filters.bookmarked, chapters.any { it.isBookmarked }) &&
        filterMatches(filters.completed, manga.status == Status.Completed) &&
        filterMatches(filters.tracking, manga.id in index.trackedMangaIds) &&
        filterMatches(filters.customInterval, manga.smartUpdateDays != null) &&
        providers.matches(index.tracksByManga[manga.id].orEmpty())
}

private class LibraryProviderFilter(filters: Map<Int, Int>) {
    private val included = filters.filterValues { it == 1 }.keys
    private val excluded = filters.filterValues { it == 2 }.keys
    fun matches(providers: List<LibraryTrack>): Boolean {
        if (included.isEmpty() && excluded.isEmpty()) return true
        return providers.none { it.providerId in excluded } && (included.isEmpty() || providers.any { it.providerId in included })
    }
}

private fun filterMatches(type: Int, value: Boolean): Boolean = when (type) {
    1 -> value
    2 -> !value
    else -> true
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGrid.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGrid.kt) · implementation · 575 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
77: internal fun LibraryBody(
153: private fun LibraryCard(
217: private fun LibraryCoverTile(
407: private fun LibraryListRow(
550: private fun LibraryCover(manga: Manga, modifier: Modifier = Modifier) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGrid.kt) · SHA-256 `79c2bd410d4141473e9f26dd849eb799d422244292c1e83fa657960d78bda6b8`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.items as lazyListItems
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDownward
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.isSecondaryPressed
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import eu.friedcutlet.yokan.domain.DisplayType
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import kotlin.math.ceil
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.empty_library
import yokan.composeapp.generated.resources.manga
import eu.friedcutlet.yokan.ui.components.CoverImage
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import androidx.compose.material.icons.filled.CollectionsBookmark
import eu.friedcutlet.yokan.ui.components.EmptyState

// ─────────────────────────────────────────────────────────────────────────────
// Grid body

@Composable
internal fun LibraryBody(
    items: List<Manga>,
    display: LibraryDisplay,
    badges: Map<Long, LibraryBadgeSummary>,
    selectedIds: Set<Long>,
    onClick: (Manga) -> Unit,
    onLongClick: (Manga) -> Unit,
    onContinue: (Manga) -> Unit,
    modifier: Modifier = Modifier,
) {
    if (items.isEmpty()) {
        EmptyState(
            icon = Icons.Filled.CollectionsBookmark,
            title = stringResource(Res.string.empty_library),
            modifier = modifier,
        )
        return
    }

    val displayType = display.displayType
    if (displayType == DisplayType.List) {
        val listState = rememberLazyListState()
        ScrollbarBox(state = listState, modifier = modifier) {
            LazyColumn(
                state = listState,
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(top = 13.dp),
            ) {
                lazyListItems(items, key = { it.id }) { manga ->
                    LibraryListRow(
                        manga = manga,
                        display = display,
                        badgeSummary = badges[manga.id] ?: LibraryBadgeSummary(),
                        selected = manga.id in selectedIds,
                        onClick = onClick,
                        onLongClick = onLongClick,
                        onContinue = onContinue,
                    )
                }
            }
        }
    } else {
        val configuredGridSize = display.gridSize
        val gridState = rememberLazyGridState()
        BoxWithConstraints(modifier = modifier) {
            val columnCount = when {
                configuredGridSize > 0 -> configuredGridSize
                maxWidth < 600.dp -> 3
                else -> ceil(maxWidth.value / 220f).toInt().coerceAtLeast(1)
            }
            ScrollbarBox(state = gridState, modifier = Modifier.fillMaxSize()) {
                LazyVerticalGrid(
                    state = gridState,
                    modifier = Modifier.fillMaxSize(),
                    columns = GridCells.Fixed(columnCount),
                    contentPadding = PaddingValues(top = 13.dp),
                ) {
                    items(items, key = { it.id }) { manga ->
                        LibraryCard(
                            manga = manga,
                            display = display,
                            badgeSummary = badges[manga.id] ?: LibraryBadgeSummary(),
                            selected = manga.id in selectedIds,
                            onClick = onClick,
                            onLongClick = onLongClick,
                            onContinue = onContinue,
                        )
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun LibraryCard(
    manga: Manga,
    display: LibraryDisplay,
    badgeSummary: LibraryBadgeSummary,
    selected: Boolean,
    onClick: (Manga) -> Unit,
    onLongClick: (Manga) -> Unit,
    onContinue: (Manga) -> Unit,
) {
    val comfortable = display.displayType == DisplayType.ComfortableGrid
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .aspectRatio(if (comfortable) 0.642f else 0.69f)
            .padding(2.dp),
    ) {
        if (comfortable) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(5.dp),
            ) {
                LibraryCoverTile(
                    manga = manga,
                    display = display,
                    badgeSummary = badgeSummary,
                    selected = selected,
                    showTitleOverlay = false,
                    onClick = onClick,
                    onLongClick = onLongClick,
                    onContinue = onContinue,
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f),
                )
                Text(
                    text = manga.name,
                    modifier = Modifier.padding(start = 5.dp, bottom = 5.dp),
                    fontSize = 12.sp,
                    fontWeight = FontWeight.SemiBold,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
            }
        } else {
            LibraryCoverTile(
                manga = manga,
                display = display,
                badgeSummary = badgeSummary,
                selected = selected,
                showTitleOverlay = display.displayType != DisplayType.CoverOnlyGrid,
                onClick = onClick,
                onLongClick = onLongClick,
                onContinue = onContinue,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(5.dp),
            )
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun LibraryCoverTile(
    manga: Manga,
    display: LibraryDisplay,
    badgeSummary: LibraryBadgeSummary,
    selected: Boolean,
    showTitleOverlay: Boolean,
    onClick: (Manga) -> Unit,
    onLongClick: (Manga) -> Unit,
    onContinue: (Manga) -> Unit,
    modifier: Modifier,
) {
    val unreadCount = badgeSummary.unreadCount
    val downloadedCount = badgeSummary.downloadedCount
    val showDownloadCount = display.downloadBadges
    val showLanguage = display.language
    val showSource = display.source
    val showLocal = display.localBadge && manga.isLocalArchive
    val showContinue = display.continueButton

    val interactionSource = remember { MutableInteractionSource() }
    val isFocused by interactionSource.collectIsFocusedAsState()
    val focusScale by animateFloatAsState(
        targetValue = if (isFocused) 1.06f else 1.0f,
        animationSpec = tween(durationMillis = 130, easing = EaseOut),
    )

    Box(
        modifier = modifier
            .graphicsLayer {
                scaleX = focusScale
                scaleY = focusScale
            }
            .border(
                width = if (isFocused) 3.dp else 0.dp,
                color = if (isFocused) MaterialTheme.colorScheme.primary else Color.Transparent,
                shape = RoundedCornerShape(8.dp),
            )
            .clip(RoundedCornerShape(if (isFocused) 8.dp else 5.dp))
            .hoverHighlight(onClick = null)
            .pointerInput(manga.id) {
                awaitPointerEventScope {
                    while (true) {
                        val event = awaitPointerEvent()
                        if (event.type == PointerEventType.Press && event.buttons.isSecondaryPressed) {
                            event.changes.forEach { it.consume() }
                            onLongClick(manga)
                        }
                    }
                }
            }
            .combinedClickable(
                interactionSource = interactionSource,
                indication = null,
                onClick = { onClick(manga) },
                onLongClick = { onLongClick(manga) },
            ),
    ) {
        LibraryCover(manga, modifier = Modifier.fillMaxSize())
        if (badgeSummary.progress > 0f && badgeSummary.progress < 1f) {
            LinearProgressIndicator(
                progress = { badgeSummary.progress },
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .fillMaxWidth()
                    .height(3.dp),
                color = MaterialTheme.colorScheme.primary,
                trackColor = Color.Black.copy(alpha = 0.35f),
            )
        }
        if (selected) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.72f)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    imageVector = Icons.Filled.Done,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.onPrimaryContainer,
                )
            }
        }
        if (showTitleOverlay) {
            Box(
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .fillMaxWidth()
                    .height(70.dp)
                    .background(
                        Brush.verticalGradient(
                            colors = listOf(Color.Transparent, Color.Black.copy(alpha = 0.6f)),
                        ),
                    ),
                contentAlignment = Alignment.BottomStart,
            ) {
                Text(
                    text = manga.name,
                    modifier = Modifier.padding(start = 5.dp, end = 5.dp, bottom = 5.dp),
                    color = Color.White,
                    fontSize = 13.sp,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis,
                )
            }
        }
        Row(
            modifier = Modifier
                .align(Alignment.TopStart)
                .padding(5.dp)
                .clip(RoundedCornerShape(3.dp))
                .background(MaterialTheme.colorScheme.primaryContainer)
                .padding(horizontal = 5.dp, vertical = 2.dp),
            horizontalArrangement = Arrangement.spacedBy(3.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            if (showLocal) {
                Text("Local", color = MaterialTheme.colorScheme.onPrimaryContainer, fontSize = 11.sp)
            }
            if (showDownloadCount) {
                Icon(
                    imageVector = Icons.Filled.ArrowDownward,
                    contentDescription = null,
                    modifier = Modifier.size(13.dp),
                    tint = MaterialTheme.colorScheme.onPrimaryContainer,
                )
                Text(
                    text = downloadedCount.toString(),
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                    fontSize = 11.sp,
                )
            }
            Text(
                text = unreadCount.toString(),
                color = MaterialTheme.colorScheme.onPrimaryContainer,
                fontSize = 12.sp,
            )
        }
        if (showLanguage && manga.lang.isNotBlank()) {
            Text(
                text = manga.lang.uppercase(),
                modifier = Modifier
                    .align(Alignment.TopEnd)
                    .padding(5.dp)
                    .clip(RoundedCornerShape(topStart = 3.dp, bottomStart = 3.dp))
                    .background(MaterialTheme.colorScheme.surface)
                    .padding(horizontal = 5.dp, vertical = 2.dp),
                fontSize = 11.sp,
            )
        }
        if (showSource && manga.source.isNotBlank()) {
            Text(
                text = manga.source,
                modifier = Modifier
                    .align(Alignment.BottomStart)
                    .padding(5.dp)
                    .widthIn(max = 96.dp)
                    .clip(RoundedCornerShape(topEnd = 3.dp))
                    .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.9f))
                    .padding(horizontal = 4.dp, vertical = 2.dp),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                fontSize = 10.sp,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
        }
        if (showContinue) {
            Box(
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(9.dp)
                    .size(33.dp)
                    .clip(RoundedCornerShape(5.dp))
                    .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.9f))
                    .clickable { onContinue(manga) },
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    imageVector = Icons.Filled.PlayArrow,
                    contentDescription = "Continue",
                    modifier = Modifier.size(19.dp),
                    tint = MaterialTheme.colorScheme.onPrimary,
                )
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun LibraryListRow(
    manga: Manga,
    display: LibraryDisplay,
    badgeSummary: LibraryBadgeSummary,
    selected: Boolean,
    onClick: (Manga) -> Unit,
    onLongClick: (Manga) -> Unit,
    onContinue: (Manga) -> Unit,
) {
    val unreadCount = badgeSummary.unreadCount
    val downloadedCount = badgeSummary.downloadedCount
    val showDownloadCount = display.downloadBadges
    val showLanguage = display.language
    val showSource = display.source
    val showLocal = display.localBadge && manga.isLocalArchive
    val showContinue = display.continueButton

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(5.dp))
            .background(
                if (selected) {
                    MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.72f)
                } else {
                    Color.Transparent
                },
            )
            .hoverHighlight(onClick = null)
            .pointerInput(manga.id) {
                awaitPointerEventScope {
                    while (true) {
                        val event = awaitPointerEvent()
                        if (event.type == PointerEventType.Press && event.buttons.isSecondaryPressed) {
                            event.changes.forEach { it.consume() }
                            onLongClick(manga)
                        }
                    }
                }
            }
            .combinedClickable(
                onClick = { onClick(manga) },
                onLongClick = { onLongClick(manga) },
            )
            .padding(horizontal = 8.dp, vertical = 3.dp)
            .height(45.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Box(modifier = Modifier.size(width = 40.dp, height = 45.dp)) {
            LibraryCover(
                manga = manga,
                modifier = Modifier.fillMaxSize(),
            )
            if (selected) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.72f)),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(
                        imageVector = Icons.Filled.Done,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.onPrimaryContainer,
                    )
                }
            }
        }
        Text(
            text = manga.name,
            modifier = Modifier
                .weight(1f)
                .padding(horizontal = 10.dp),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
        Row(
            modifier = Modifier
                .padding(5.dp)
                .height(22.dp)
                .clip(RoundedCornerShape(3.dp))
                .background(MaterialTheme.colorScheme.primaryContainer)
                .padding(horizontal = 3.dp),
            horizontalArrangement = Arrangement.spacedBy(3.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            if (showLocal) {
                Text("Local", color = MaterialTheme.colorScheme.onPrimaryContainer, fontSize = 11.sp)
            }
            if (showDownloadCount) {
                Icon(
                    imageVector = Icons.Filled.ArrowDownward,
                    contentDescription = null,
                    modifier = Modifier.size(13.dp),
                    tint = MaterialTheme.colorScheme.onPrimaryContainer,
                )
                Text(
                    text = downloadedCount.toString(),
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                    fontSize = 11.sp,
                )
            }
            Text(
                text = unreadCount.toString(),
                color = MaterialTheme.colorScheme.onPrimaryContainer,
                fontSize = 12.sp,
            )
            if (showLanguage && manga.lang.isNotBlank()) {
                Text(
                    text = manga.lang.uppercase(),
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                    fontSize = 11.sp,
                )
            }
            if (showSource && manga.source.isNotBlank()) {
                Text(
                    text = manga.source,
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                    fontSize = 11.sp,
                )
            }
        }
        if (showContinue) {
            Box(
                modifier = Modifier
                    .size(33.dp)
                    .clip(RoundedCornerShape(5.dp))
                    .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.9f))
                    .clickable { onContinue(manga) },
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    imageVector = Icons.Filled.PlayArrow,
                    contentDescription = "Continue",
                    modifier = Modifier.size(19.dp),
                    tint = MaterialTheme.colorScheme.onPrimary,
                )
            }
        }
    }
}

@Composable
private fun LibraryCover(manga: Manga, modifier: Modifier = Modifier) {
    val tint = when (manga.itemType) {
        ItemType.Manga -> MaterialTheme.colorScheme.primary
        ItemType.Anime -> MaterialTheme.colorScheme.secondary
        ItemType.Novel -> MaterialTheme.colorScheme.tertiary
    }
    val coverModel: Any? = manga.customCoverImage
        ?: manga.customCoverFromTracker?.takeIf { it.isNotBlank() }
        ?: manga.imageUrl?.takeIf { it.isNotBlank() }
    Box(
        modifier = modifier
            .clip(RoundedCornerShape(5.dp))
            .background(tint.copy(alpha = 0.18f)),
        contentAlignment = Alignment.Center,
    ) {
        CoverImage(
            model = coverModel,
            contentDescription = "${manga.name} cover",
            contentScale = ContentScale.Crop,
            modifier = Modifier.fillMaxSize(),
            fallbackInitials = manga.name.split(" ")
                .take(2)
                .joinToString("") { it.firstOrNull()?.uppercase() ?: "" },
        )
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGrouping.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGrouping.kt) · implementation · 56 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
10: internal class LibraryGroups(val members: Map<Long, List<Manga>>, val tabs: List<LibraryCategoryTab>)
11: private data class GroupDescriptor(val key: String, val name: String, val label: LibraryTabLabel = LibraryTabLabel.Name)
14: internal fun automaticLibraryGroups(
47: internal fun libraryGroupIds(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGrouping.kt) · SHA-256 `c8d7654c785f57365a23a733e930aa08fc31868ed97ac24ea74ee9ec535dc9ff`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.database.DbLibraryGrouping
import eu.friedcutlet.yokan.database.sync.SyncIds
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.Manga

internal class LibraryGroups(val members: Map<Long, List<Manga>>, val tabs: List<LibraryCategoryTab>)
private data class GroupDescriptor(val key: String, val name: String, val label: LibraryTabLabel = LibraryTabLabel.Name)

/** One membership pass, then one pass over sorted matches; never a whole-library scan per tag. */
internal fun automaticLibraryGroups(
    library: List<Manga>, filtered: List<Manga>, categories: List<Category>, index: LibraryIndex, grouping: DbLibraryGrouping,
): LibraryGroups {
    if (grouping == DbLibraryGrouping.Ungrouped || grouping == DbLibraryGrouping.Categories) return LibraryGroups(emptyMap(), emptyList())
    val descriptors = linkedMapOf<String, GroupDescriptor>()
    val memberships = library.associate { manga ->
        val groups = when (grouping) {
            DbLibraryGrouping.Source -> listOf(GroupDescriptor(
                manga.sourceId?.let { "id:$it" } ?: "legacy:${manga.source.lowercase()}:${manga.lang.lowercase()}",
                if (manga.source.isBlank()) "" else manga.source + manga.lang.takeIf(String::isNotBlank)?.let { " ($it)" }.orEmpty(),
                if (manga.source.isBlank()) LibraryTabLabel.UnknownSource else LibraryTabLabel.Name,
            ))
            DbLibraryGrouping.Status -> listOf(GroupDescriptor(manga.status.name, manga.status.label))
            DbLibraryGrouping.TrackerStatus -> index.tracksByManga[manga.id].orEmpty().map {
                GroupDescriptor(it.status.name, it.status.toDomain().label)
            }.distinctBy { it.key }.ifEmpty { listOf(GroupDescriptor("untracked", "", LibraryTabLabel.Untracked)) }
            DbLibraryGrouping.Tags -> manga.genres.map(String::trim).filter(String::isNotBlank).distinctBy { it.lowercase() }
                .map { GroupDescriptor(it.lowercase(), it) }
                .ifEmpty { listOf(GroupDescriptor("\u0000untagged", "", LibraryTabLabel.Untagged)) }
        }
        groups.forEach { descriptors.getOrPut(it.key) { it } }
        manga.id to groups.map { it.key }
    }
    val ids = libraryGroupIds(descriptors.keys, grouping, categories.mapTo(mutableSetOf()) { it.id })
    val members = descriptors.keys.associateWith { mutableListOf<Manga>() }
    filtered.forEach { manga -> memberships[manga.id].orEmpty().forEach { key -> members.getValue(key).add(manga) } }
    val tabs = descriptors.values.sortedWith(compareBy<GroupDescriptor> { it.name.lowercase() }.thenBy { it.key }).map {
        LibraryCategoryTab(ids.getValue(it.key), it.name, members.getValue(it.key).size, it.label)
    }
    return LibraryGroups(members.mapKeys { ids.getValue(it.key) }, tabs)
}

/** Negative IDs keep automatic tabs separate from persisted categories; collisions are resolved. */
internal fun libraryGroupIds(
    keys: Set<String>, grouping: DbLibraryGrouping, reserved: Set<Long>, hash: (String) -> Long = SyncIds::stable,
): Map<String, Long> {
    val used = reserved.toMutableSet().apply { add(0L); add(UncategorizedCategoryId); add(AllLibraryTabId) }
    return keys.sorted().associateWith { key ->
        var candidate = -hash("library-group|${grouping.name}|$key").coerceIn(2, Long.MAX_VALUE)
        while (!used.add(candidate)) candidate = if (candidate == Long.MIN_VALUE) -2L else candidate - 1L
        candidate
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryPreferences.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryPreferences.kt) · implementation · 271 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
16: data class LibraryDisplay(
29: internal fun LibraryDisplay.forCategory(preferences: DbCategoryLibraryPreferences?): LibraryDisplay =
36: internal fun LibraryDisplay.categoryPreferences() = DbCategoryLibraryDisplay(
40: internal fun DbSettings.withLibraryGrouping(type: ItemType, grouping: DbLibraryGrouping): DbSettings =
43: internal fun DbSettings.withCategoryLibraryPreferences(type: ItemType, id: Long, preferences: DbCategoryLibraryPreferences?): DbSettings =
46: internal fun DbSettings.withCategoryLibraryDisplay(type: ItemType, id: Long, transform: (DbSettings) -> DbSettings): DbSettings {
56: internal fun DbSettings.withCategoryLibrarySortSelected(type: ItemType, id: Long, index: Int): DbSettings {
64: fun DbSettings.libraryDisplay(type: ItemType): LibraryDisplay = when (type) {
101: fun DbSettings.withLibraryDisplay(
140: fun DbSettings.withLibraryDisplayType(type: ItemType, displayType: DisplayType): DbSettings {
149: fun DbSettings.withLibraryGridSize(type: ItemType, size: Int): DbSettings {
158: fun DbSettings.librarySearch(type: ItemType): String = when (type) {
164: fun DbSettings.withLibrarySearch(type: ItemType, query: String): DbSettings = when (type) {
170: fun DbSettings.libraryFilters(type: ItemType): LibraryFilterTypes = when (type) {
201: private fun DbSettings.withLibraryCustomIntervalFilter(type: ItemType, value: Int): DbSettings = copy(features = features.copy(
205: internal fun DbSettings.withLibraryProviderTrackingCycled(type: ItemType, providerId: Int): DbSettings {
214: internal fun DbSettings.withLibraryRandomSeed(type: ItemType, seed: Long): DbSettings = copy(features = features.copy(
219: fun DbSettings.withLibraryFilterCycled(type: ItemType, kind: LibraryFilterKind): DbSettings {
252: fun DbSettings.librarySort(type: ItemType): DbSortLibraryManga = when (type) {
259: fun DbSettings.withLibrarySortSelected(type: ItemType, index: Int): DbSettings {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryPreferences.kt) · SHA-256 `62ecf4094d8a999cfcf8ba1301a961958e6a9e43fc9924cec9fbb4f936eba75b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSortLibraryManga
import eu.friedcutlet.yokan.database.DbCategoryLibraryDisplay
import eu.friedcutlet.yokan.database.DbCategoryLibraryPreferences
import eu.friedcutlet.yokan.database.DbLibraryGrouping
import eu.friedcutlet.yokan.database.DbLibraryExtraFilters
import kotlin.random.Random
import eu.friedcutlet.yokan.domain.DisplayType
import eu.friedcutlet.yokan.domain.ItemType

/** How one item type's library is laid out and which badges its entries show. */
data class LibraryDisplay(
    val displayType: DisplayType,
    /** Columns per row; 0 derives them from the width. */
    val gridSize: Int,
    val downloadBadges: Boolean,
    val language: Boolean,
    val source: Boolean,
    val localBadge: Boolean,
    val continueButton: Boolean,
    val categoryTabs: Boolean,
    val itemCounts: Boolean,
)

internal fun LibraryDisplay.forCategory(preferences: DbCategoryLibraryPreferences?): LibraryDisplay =
    preferences?.display?.let { stored -> copy(
        displayType = stored.displayType.toDomain(), gridSize = stored.gridSize.coerceIn(0, 7),
        downloadBadges = stored.downloadBadges, language = stored.language, source = stored.source,
        localBadge = stored.localBadge, continueButton = stored.continueButton,
    ) } ?: this

internal fun LibraryDisplay.categoryPreferences() = DbCategoryLibraryDisplay(
    displayType.toDb(), gridSize.coerceIn(0, 7), downloadBadges, language, source, localBadge, continueButton,
)

internal fun DbSettings.withLibraryGrouping(type: ItemType, grouping: DbLibraryGrouping): DbSettings =
    copy(features = features.copy(library = features.library.withGrouping(type.toDb(), grouping)))

internal fun DbSettings.withCategoryLibraryPreferences(type: ItemType, id: Long, preferences: DbCategoryLibraryPreferences?): DbSettings =
    copy(features = features.copy(library = features.library.withCategory(type.toDb(), id, preferences)))

internal fun DbSettings.withCategoryLibraryDisplay(type: ItemType, id: Long, transform: (DbSettings) -> DbSettings): DbSettings {
    val current = features.library.categories(type.toDb())[id] ?: DbCategoryLibraryPreferences()
    // Apply existing display controls to the effective category display, then store only card options.
    val effective = libraryDisplay(type).forCategory(current)
    val seed = withLibraryDisplayType(type, effective.displayType).withLibraryGridSize(type, effective.gridSize)
        .withLibraryDisplay(type, effective.downloadBadges, effective.language, effective.source,
            effective.localBadge, effective.continueButton)
    return withCategoryLibraryPreferences(type, id, current.copy(display = transform(seed).libraryDisplay(type).categoryPreferences()))
}

internal fun DbSettings.withCategoryLibrarySortSelected(type: ItemType, id: Long, index: Int): DbSettings {
    val current = features.library.categories(type.toDb())[id] ?: DbCategoryLibraryPreferences()
    val before = current.sort ?: librarySort(type)
    return withCategoryLibraryPreferences(type, id, current.copy(sort = before.copy(
        index = index, reverse = if (before.index == index) !before.reverse else before.reverse,
    )))
}

fun DbSettings.libraryDisplay(type: ItemType): LibraryDisplay = when (type) {
    ItemType.Manga -> LibraryDisplay(
        displayType = displayType.toDomain(),
        gridSize = (mangaGridSize ?: 0).coerceIn(0, 7),
        downloadBadges = libraryDownloadedChapters,
        language = libraryShowLanguage,
        source = libraryShowSource,
        localBadge = libraryLocalSource == true,
        continueButton = libraryShowContinueReadingButton,
        categoryTabs = libraryShowCategoryTabs,
        itemCounts = libraryShowNumbersOfItems,
    )
    ItemType.Anime -> LibraryDisplay(
        displayType = animeDisplayType.toDomain(),
        gridSize = (animeGridSize ?: 0).coerceIn(0, 7),
        downloadBadges = animeLibraryDownloadedChapters,
        language = animeLibraryShowLanguage,
        source = animeLibraryShowSource,
        localBadge = animeLibraryLocalSource == true,
        continueButton = animeLibraryShowContinueReadingButton,
        categoryTabs = animeLibraryShowCategoryTabs,
        itemCounts = animeLibraryShowNumbersOfItems,
    )
    ItemType.Novel -> LibraryDisplay(
        displayType = novelDisplayType.toDomain(),
        gridSize = (novelGridSize ?: 0).coerceIn(0, 7),
        downloadBadges = novelLibraryDownloadedChapters,
        language = novelLibraryShowLanguage,
        source = novelLibraryShowSource,
        localBadge = novelLibraryLocalSource == true,
        continueButton = novelLibraryShowContinueReadingButton,
        categoryTabs = novelLibraryShowCategoryTabs,
        itemCounts = novelLibraryShowNumbersOfItems,
    )
}

/** Sets the given display flags for [type]; `null` keeps the stored value. */
fun DbSettings.withLibraryDisplay(
    type: ItemType,
    downloadBadges: Boolean? = null,
    language: Boolean? = null,
    source: Boolean? = null,
    localBadge: Boolean? = null,
    continueButton: Boolean? = null,
    categoryTabs: Boolean? = null,
    itemCounts: Boolean? = null,
): DbSettings = when (type) {
    ItemType.Manga -> copy(
        libraryDownloadedChapters = downloadBadges ?: libraryDownloadedChapters,
        libraryShowLanguage = language ?: libraryShowLanguage,
        libraryShowSource = source ?: libraryShowSource,
        libraryLocalSource = localBadge ?: libraryLocalSource,
        libraryShowContinueReadingButton = continueButton ?: libraryShowContinueReadingButton,
        libraryShowCategoryTabs = categoryTabs ?: libraryShowCategoryTabs,
        libraryShowNumbersOfItems = itemCounts ?: libraryShowNumbersOfItems,
    )
    ItemType.Anime -> copy(
        animeLibraryDownloadedChapters = downloadBadges ?: animeLibraryDownloadedChapters,
        animeLibraryShowLanguage = language ?: animeLibraryShowLanguage,
        animeLibraryShowSource = source ?: animeLibraryShowSource,
        animeLibraryLocalSource = localBadge ?: animeLibraryLocalSource,
        animeLibraryShowContinueReadingButton = continueButton ?: animeLibraryShowContinueReadingButton,
        animeLibraryShowCategoryTabs = categoryTabs ?: animeLibraryShowCategoryTabs,
        animeLibraryShowNumbersOfItems = itemCounts ?: animeLibraryShowNumbersOfItems,
    )
    ItemType.Novel -> copy(
        novelLibraryDownloadedChapters = downloadBadges ?: novelLibraryDownloadedChapters,
        novelLibraryShowLanguage = language ?: novelLibraryShowLanguage,
        novelLibraryShowSource = source ?: novelLibraryShowSource,
        novelLibraryLocalSource = localBadge ?: novelLibraryLocalSource,
        novelLibraryShowContinueReadingButton = continueButton ?: novelLibraryShowContinueReadingButton,
        novelLibraryShowCategoryTabs = categoryTabs ?: novelLibraryShowCategoryTabs,
        novelLibraryShowNumbersOfItems = itemCounts ?: novelLibraryShowNumbersOfItems,
    )
}

fun DbSettings.withLibraryDisplayType(type: ItemType, displayType: DisplayType): DbSettings {
    val value = displayType.toDb()
    return when (type) {
        ItemType.Manga -> copy(displayType = value)
        ItemType.Anime -> copy(animeDisplayType = value)
        ItemType.Novel -> copy(novelDisplayType = value)
    }
}

fun DbSettings.withLibraryGridSize(type: ItemType, size: Int): DbSettings {
    val normalized = size.coerceIn(0, 7)
    return when (type) {
        ItemType.Manga -> copy(mangaGridSize = normalized)
        ItemType.Anime -> copy(animeGridSize = normalized)
        ItemType.Novel -> copy(novelGridSize = normalized)
    }
}

fun DbSettings.librarySearch(type: ItemType): String = when (type) {
    ItemType.Manga -> librarySearchQuery
    ItemType.Anime -> animeLibrarySearchQuery
    ItemType.Novel -> novelLibrarySearchQuery
}

fun DbSettings.withLibrarySearch(type: ItemType, query: String): DbSettings = when (type) {
    ItemType.Manga -> copy(librarySearchQuery = query)
    ItemType.Anime -> copy(animeLibrarySearchQuery = query)
    ItemType.Novel -> copy(novelLibrarySearchQuery = query)
}

fun DbSettings.libraryFilters(type: ItemType): LibraryFilterTypes = when (type) {
    ItemType.Manga -> LibraryFilterTypes(
        downloaded = libraryFilterMangasDownloadType,
        unread = libraryFilterMangasUnreadType,
        started = libraryFilterMangasStartedType,
        bookmarked = libraryFilterMangasBookMarkedType,
        completed = libraryFilterMangasCompletedType,
        tracking = libraryFilterMangasTrackingType,
    )
    ItemType.Anime -> LibraryFilterTypes(
        downloaded = libraryFilterAnimeDownloadType,
        unread = libraryFilterAnimeUnreadType,
        started = libraryFilterAnimeStartedType,
        bookmarked = libraryFilterAnimeBookMarkedType,
        completed = libraryFilterAnimeCompletedType,
        tracking = libraryFilterAnimeTrackingType,
    )
    ItemType.Novel -> LibraryFilterTypes(
        downloaded = libraryFilterNovelDownloadType,
        unread = libraryFilterNovelUnreadType,
        started = libraryFilterNovelStartedType,
        bookmarked = libraryFilterNovelBookMarkedType,
        completed = libraryFilterNovelCompletedType,
        tracking = libraryFilterNovelTrackingType,
    )
}.let { base ->
    val extra = features.library.filters(type.toDb())
    base.copy(customInterval = extra.customInterval.takeIf { it in 0..2 } ?: 0,
        providerTracking = extra.providerTracking.filter { (id, value) -> id > 0 && value in 1..2 })
}

private fun DbSettings.withLibraryCustomIntervalFilter(type: ItemType, value: Int): DbSettings = copy(features = features.copy(
    library = features.library.withFilters(type.toDb(), features.library.filters(type.toDb()).copy(customInterval = value)),
))

internal fun DbSettings.withLibraryProviderTrackingCycled(type: ItemType, providerId: Int): DbSettings {
    if (providerId <= 0) return this
    val before = features.library.filters(type.toDb())
    val next = ((before.providerTracking[providerId] ?: 0).coerceIn(0, 2) + 1) % 3
    return copy(features = features.copy(library = features.library.withFilters(type.toDb(), before.copy(
        providerTracking = if (next == 0) before.providerTracking - providerId else before.providerTracking + (providerId to next),
    ))))
}

internal fun DbSettings.withLibraryRandomSeed(type: ItemType, seed: Long): DbSettings = copy(features = features.copy(
    library = features.library.copy(randomSeeds = features.library.randomSeeds + (type.toDb() to seed)),
))

/** Advances [kind] for [type] through off → include → exclude. */
fun DbSettings.withLibraryFilterCycled(type: ItemType, kind: LibraryFilterKind): DbSettings {
    val next = (libraryFilters(type).value(kind) + 1) % 3
    return when (type) {
        ItemType.Manga -> when (kind) {
            LibraryFilterKind.Downloaded -> copy(libraryFilterMangasDownloadType = next)
            LibraryFilterKind.Unread -> copy(libraryFilterMangasUnreadType = next)
            LibraryFilterKind.Started -> copy(libraryFilterMangasStartedType = next)
            LibraryFilterKind.Bookmarked -> copy(libraryFilterMangasBookMarkedType = next)
            LibraryFilterKind.Completed -> copy(libraryFilterMangasCompletedType = next)
            LibraryFilterKind.Tracking -> copy(libraryFilterMangasTrackingType = next)
            LibraryFilterKind.CustomInterval -> withLibraryCustomIntervalFilter(type, next)
        }
        ItemType.Anime -> when (kind) {
            LibraryFilterKind.Downloaded -> copy(libraryFilterAnimeDownloadType = next)
            LibraryFilterKind.Unread -> copy(libraryFilterAnimeUnreadType = next)
            LibraryFilterKind.Started -> copy(libraryFilterAnimeStartedType = next)
            LibraryFilterKind.Bookmarked -> copy(libraryFilterAnimeBookMarkedType = next)
            LibraryFilterKind.Completed -> copy(libraryFilterAnimeCompletedType = next)
            LibraryFilterKind.Tracking -> copy(libraryFilterAnimeTrackingType = next)
            LibraryFilterKind.CustomInterval -> withLibraryCustomIntervalFilter(type, next)
        }
        ItemType.Novel -> when (kind) {
            LibraryFilterKind.Downloaded -> copy(libraryFilterNovelDownloadType = next)
            LibraryFilterKind.Unread -> copy(libraryFilterNovelUnreadType = next)
            LibraryFilterKind.Started -> copy(libraryFilterNovelStartedType = next)
            LibraryFilterKind.Bookmarked -> copy(libraryFilterNovelBookMarkedType = next)
            LibraryFilterKind.Completed -> copy(libraryFilterNovelCompletedType = next)
            LibraryFilterKind.Tracking -> copy(libraryFilterNovelTrackingType = next)
            LibraryFilterKind.CustomInterval -> withLibraryCustomIntervalFilter(type, next)
        }
    }
}

fun DbSettings.librarySort(type: ItemType): DbSortLibraryManga = when (type) {
    ItemType.Manga -> sortLibraryManga
    ItemType.Anime -> sortLibraryAnime
    ItemType.Novel -> sortLibraryNovel
} ?: DbSortLibraryManga()

/** Selects sort [index] for [type]; selecting the current one flips its direction. */
fun DbSettings.withLibrarySortSelected(type: ItemType, index: Int): DbSettings {
    val current = librarySort(type)
    val next = current.copy(
        index = index,
        reverse = if (current.index == index) !current.reverse else current.reverse,
    )
    val updated = when (type) {
        ItemType.Manga -> copy(sortLibraryManga = next)
        ItemType.Anime -> copy(sortLibraryAnime = next)
        ItemType.Novel -> copy(sortLibraryNovel = next)
    }
    return if (index == 7 && current.index != 7) updated.withLibraryRandomSeed(type, Random.nextLong()) else updated
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryRoute.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryRoute.kt) · implementation · 46 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
14: internal fun rememberLibraryViewModel(itemType: ItemType, nav: Navigator): LibraryViewModel =
31: internal fun LibraryRoute(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryRoute.kt) · SHA-256 `d6502791ab5c5f8f69b4baba8a67282cae378b1ccecbacc86f5c92ef8e9f5daa`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route

/** The [itemType] library's ViewModel, shared through the root store by the screen and the root gestures. */
@Composable
internal fun rememberLibraryViewModel(itemType: ItemType, nav: Navigator): LibraryViewModel =
    viewModel(viewModelStoreOwner = nav.rootViewModelStoreOwner, key = "library-$itemType") {
        LibraryViewModel(
            itemType = itemType,
            repository = YokanRuntime.repository,
            settings = YokanRuntime.settings,
            libraryIndex = YokanRuntime.libraryIndex,
            libraryUpdates = YokanRuntime.libraryUpdates,
            localLibrary = YokanRuntime.localLibrary,
            chapterDownloads = YokanRuntime.chapterDownloads,
            libraryRequests = nav.libraryRequest,
            airings = YokanRuntime.services.libraryAirings,
            trackerProviders = YokanRuntime.services.trackers.map { LibraryTrackerChoice(it.syncId, it.name) },
        )
    }

@Composable
internal fun LibraryRoute(
    itemType: ItemType,
    compact: Boolean,
    nav: Navigator,
) {
    val viewModel = rememberLibraryViewModel(itemType, nav)
    val state by viewModel.state.collectAsStateWithLifecycle()

    LibraryScreen(
        state = state,
        compact = compact,
        onEvent = viewModel::onEvent,
        onOpenDetail = { manga -> nav.navigate(Route.Detail(manga.id)) },
        onContinue = { manga -> nav.navigate(Route.Reader(manga.id, viewModel.continueChapterId(manga))) },
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryScreen.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryScreen.kt) · implementation · 773 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
118: fun LibraryScreen(
135: fun itemsFor(categoryId: Long?): List<Manga> = when {
289: private sealed interface LibraryDialog {
290: data object Filters : LibraryDialog
291: data object ImportLocal : LibraryDialog
292: data object AddTorrent : LibraryDialog
293: data object Categories : LibraryDialog
294: data object Delete : LibraryDialog
302: private fun LibraryDefaultAppBar(
445: private fun RefreshSummaryBanner(refreshSummary: String?) {
463: private fun LibraryCategoryPager(
535: private fun LibraryGroupTab(tab: LibraryCategoryTab, selected: Boolean, showCounts: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier) {
560: private fun ImportLocalDialog(
609: private fun AddTorrentDialog(
675: private fun DeleteLibraryItemsDialog(
771: private fun LibraryFilterTypes.anyActive(): Boolean =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryScreen.kt) · SHA-256 `4054801d042cad24009647ecaece7dae6a10afe6410d94637393e3dba67e535c`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Badge
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SecondaryScrollableTabRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.`or`
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.action_remove
import yokan.composeapp.generated.resources.add_torrent
import yokan.composeapp.generated.resources.anime
import yokan.composeapp.generated.resources.bookmarked
import yokan.composeapp.generated.resources.completed
import yokan.composeapp.generated.resources.default0
import yokan.composeapp.generated.resources.downloaded
import yokan.composeapp.generated.resources.downloaded_chapters
import yokan.composeapp.generated.resources.downloaded_episodes
import yokan.composeapp.generated.resources.enter_torrent_hint_text
import yokan.composeapp.generated.resources.filter
import yokan.composeapp.generated.resources.ignore_filters
import yokan.composeapp.generated.resources.import_local_file
import yokan.composeapp.generated.resources.manga
import yokan.composeapp.generated.resources.novel
import yokan.composeapp.generated.resources.open_random_entry
import yokan.composeapp.generated.resources.search
import yokan.composeapp.generated.resources.library_search_help
import yokan.composeapp.generated.resources.library_search_help_body
import yokan.composeapp.generated.resources.ok
import yokan.composeapp.generated.resources.library_group_untracked
import yokan.composeapp.generated.resources.library_group_untagged
import yokan.composeapp.generated.resources.library_group_unknown_source
import yokan.composeapp.generated.resources.library_group_all
import yokan.composeapp.generated.resources.started
import yokan.composeapp.generated.resources.tabs
import yokan.composeapp.generated.resources.torrent_file_option
import yokan.composeapp.generated.resources.torrent_stream
import yokan.composeapp.generated.resources.torrent_url
import yokan.composeapp.generated.resources.unread
import yokan.composeapp.generated.resources.update_library
import eu.friedcutlet.yokan.ui.components.adaptiveContentPadding
import eu.friedcutlet.yokan.ui.components.AppBarSearchField
import eu.friedcutlet.yokan.ui.components.compactDialogWidth

/**
 * Library screen — Material 3 rewrite that mirrors the original Flutter
 * wireframe. Renders [state]; every change goes out through [onEvent].
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LibraryScreen(
    state: LibraryState,
    compact: Boolean,
    onEvent: (LibraryEvent) -> Unit,
    onOpenDetail: (Manga) -> Unit,
    onContinue: (Manga) -> Unit,
) {
    var searching by remember { mutableStateOf(false) }
    var ignoreFiltersOnSearch by remember { mutableStateOf(false) }
    var dialog by remember { mutableStateOf<LibraryDialog?>(null) }
    val dismissDialog = { dialog = null }

    val itemType = state.itemType
    val content = state.content
    val selectionMode = state.selectionMode
    // Ignoring filters lists every title matching the search, whatever the category.
    val searchAll = searching && ignoreFiltersOnSearch && state.query.search.isNotBlank()
    fun itemsFor(categoryId: Long?): List<Manga> = when {
        content == null -> emptyList()
        searchAll -> content.searchMatches
        else -> content.items(categoryId)
    }
    val onCardClick: (Manga) -> Unit = { manga ->
        if (selectionMode) onEvent(LibraryEvent.ToggleSelection(manga.id)) else onOpenDetail(manga)
    }
    val onCardLongClick: (Manga) -> Unit = { manga -> onEvent(LibraryEvent.BeginSelection(manga.id)) }

    Scaffold(
        topBar = {
            if (selectionMode) {
                LibrarySelectionAppBar(
                    selectedCount = state.selectedIds.size,
                    onClear = { onEvent(LibraryEvent.ClearSelection) },
                    onSelectAll = { onEvent(LibraryEvent.SelectAll) },
                    onInvert = { onEvent(LibraryEvent.InvertSelection) },
                )
            } else {
                LibraryDefaultAppBar(
                    itemType = itemType,
                    count = if (content == null) -1 else itemsFor(null).size,
                    showCount = state.display.itemCounts,
                    filtersActive = state.query.filters.anyActive(),
                    searchQuery = state.query.search,
                    onSearchChange = { onEvent(LibraryEvent.Search(it)) },
                    compact = compact,
                    searching = searching,
                    ignoreFilters = ignoreFiltersOnSearch,
                    onToggleSearch = {
                        searching = !searching
                        if (!searching) {
                            onEvent(LibraryEvent.Search(""))
                            ignoreFiltersOnSearch = false
                        }
                    },
                    onToggleIgnoreFilters = { ignoreFiltersOnSearch = !ignoreFiltersOnSearch },
                    onOpenFilters = { dialog = LibraryDialog.Filters },
                    onRefresh = { onEvent(LibraryEvent.Refresh) },
                    refreshing = state.refreshing,
                    onRandomOpen = { state.currentItems.randomOrNull()?.let(onOpenDetail) },
                    onOpenImport = { dialog = LibraryDialog.ImportLocal },
                    onOpenTorrent = { dialog = LibraryDialog.AddTorrent },
                )
            }
        },
        bottomBar = {
            if (selectionMode) {
                LibrarySelectionBottomBar(
                    onCategorize = { dialog = LibraryDialog.Categories },
                    onMarkRead = { isRead -> onEvent(LibraryEvent.MarkSelectedRead(isRead)) },
                    onDelete = { dialog = LibraryDialog.Delete },
                )
            }
        },
    ) { padding ->
        PullToRefreshBox(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(if (compact) PaddingValues(0.dp) else adaptiveContentPadding()),
            isRefreshing = state.refreshing,
            onRefresh = { onEvent(LibraryEvent.Refresh) },
        ) {
            // Nothing to show until the first pass over the library finished.
            if (content != null) {
                Column(modifier = Modifier.fillMaxSize()) {
                    val categoryTabs = if (state.display.categoryTabs && content.tabs.isNotEmpty())
                        listOf(LibraryCategoryTab(AllLibraryTabId, "", content.items(null).size, LibraryTabLabel.All)) + content.tabs else emptyList()
                    val body: @Composable (categoryId: Long?) -> Unit = { categoryId ->
                        LibraryBody(
                            items = itemsFor(categoryId),
                            display = if (state.query.grouping == eu.friedcutlet.yokan.database.DbLibraryGrouping.Categories)
                                state.display.forCategory(state.query.categoryPreferences[categoryId]) else state.display,
                            badges = state.badges,
                            selectedIds = state.selectedIds,
                            onClick = onCardClick,
                            onLongClick = onCardLongClick,
                            onContinue = onContinue,
                            modifier = Modifier.fillMaxSize(),
                        )
                    }
                    if (categoryTabs.isNotEmpty()) {
                        LibraryCategoryPager(
                            tabs = categoryTabs,
                            selectedCategoryId = state.selectedCategoryId ?: AllLibraryTabId,
                            showCounts = state.display.itemCounts,
                            refreshSummary = state.lastRefreshSummary,
                            onSelectCategory = { onEvent(LibraryEvent.SelectCategory(it.takeUnless { id -> id == AllLibraryTabId })) },
                            page = { categoryId -> body(categoryId.takeUnless { it == AllLibraryTabId }) },
                        )
                    } else {
                        RefreshSummaryBanner(state.lastRefreshSummary)
                        body(state.selectedCategoryId)
                    }
                }
            }
        }
    }

    when (dialog) {
        LibraryDialog.Filters -> LibrarySettingsSheet(
            itemType = itemType,
            filters = state.query.filters,
            sort = state.query.sort,
            display = state.display,
            grouping = state.query.grouping,
            selectedCategory = if (state.query.grouping == eu.friedcutlet.yokan.database.DbLibraryGrouping.Categories)
                content?.categories?.firstOrNull { it.id == state.selectedCategoryId } else null,
            categoryPreferences = state.query.categoryPreferences[state.selectedCategoryId],
            trackerProviders = state.trackerProviders,
            refreshingAirings = state.refreshingAirings,
            airingResult = state.airingRefreshResult,
            airingFailed = state.airingRefreshFailed,
            onRefreshAirings = { onEvent(LibraryEvent.RefreshAirings) },
            onUpdateSettings = { onEvent(LibraryEvent.UpdateSettings(it)) },
            onDismiss = dismissDialog,
        )
        LibraryDialog.ImportLocal -> ImportLocalDialog(
            itemType = itemType,
            onDismiss = dismissDialog,
            onImport = {
                onEvent(LibraryEvent.RescanLocalLibrary)
                dialog = null
            },
        )
        LibraryDialog.AddTorrent -> AddTorrentDialog(
            onDismiss = dismissDialog,
            onAdd = { url ->
                onEvent(LibraryEvent.ImportTorrent(url))
                dialog = null
            },
        )
        LibraryDialog.Categories -> BulkCategoriesDialog(
            categories = content?.categories.orEmpty(),
            selectedTitles = content?.library.orEmpty().filter { it.id in state.selectedIds },
            onConfirm = { categoryIds -> onEvent(LibraryEvent.SetSelectedCategories(categoryIds)) },
            onDismiss = dismissDialog,
        )
        LibraryDialog.Delete -> DeleteLibraryItemsDialog(
            selectedCount = state.selectedIds.size,
            itemType = itemType,
            onConfirm = { deleteFromLibrary, deleteDownloads ->
                onEvent(LibraryEvent.RemoveSelected(fromLibrary = deleteFromLibrary, downloads = deleteDownloads))
                dialog = null
            },
            onDismiss = dismissDialog,
        )
        null -> Unit
    }
}

/** The one dialog or sheet [LibraryScreen] shows at a time. */
private sealed interface LibraryDialog {
    data object Filters : LibraryDialog
    data object ImportLocal : LibraryDialog
    data object AddTorrent : LibraryDialog
    data object Categories : LibraryDialog
    data object Delete : LibraryDialog
}

// ─────────────────────────────────────────────────────────────────────────────
// Top app bars

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun LibraryDefaultAppBar(
    itemType: ItemType,
    count: Int,
    showCount: Boolean,
    filtersActive: Boolean,
    searchQuery: String,
    onSearchChange: (String) -> Unit,
    compact: Boolean,
    searching: Boolean,
    ignoreFilters: Boolean,
    onToggleSearch: () -> Unit,
    onToggleIgnoreFilters: () -> Unit,
    onOpenFilters: () -> Unit,
    onRefresh: () -> Unit,
    refreshing: Boolean,
    onRandomOpen: () -> Unit,
    onOpenImport: () -> Unit,
    onOpenTorrent: () -> Unit,
) {
    var menuOpen by remember { mutableStateOf(false) }
    var searchHelpOpen by remember { mutableStateOf(false) }

    TopAppBar(
        title = {
            if (searching) {
                AppBarSearchField(
                    query = searchQuery,
                    placeholder = stringResource(Res.string.search),
                    onQueryChange = onSearchChange,
                    onClose = onToggleSearch,
                )
            } else {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(10.dp),
                ) {
                    Text(
                        text = stringResource(
                            when (itemType) {
                                ItemType.Manga -> Res.string.manga
                                ItemType.Anime -> Res.string.anime
                                ItemType.Novel -> Res.string.novel
                            },
                        ),
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                    if (showCount && count >= 0) {
                        Badge(
                            containerColor = MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = MaterialTheme.colorScheme.onSurface,
                        ) {
                            Text(count.toString(), fontSize = 12.sp)
                        }
                    }
                }
            }
        },
        actions = {
            if (!searching) {
                IconButton(onClick = onToggleSearch) {
                    Icon(Icons.Filled.Search, contentDescription = "Search library")
                }
            }
            if (searching) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { onToggleIgnoreFilters() },
                ) {
                    Text(
                        text = stringResource(Res.string.ignore_filters).let { label ->
                            if (compact) label.replaceFirst(' ', '\n') else label.replace("\n", "")
                        },
                        textAlign = androidx.compose.ui.text.style.TextAlign.Center,
                    )
                    Checkbox(
                        checked = ignoreFilters,
                        onCheckedChange = { onToggleIgnoreFilters() },
                    )
                }
            }
            IconButton(onClick = onOpenFilters) {
                Icon(
                    imageVector = Icons.Filled.FilterList,
                    contentDescription = "Filter library",
                    tint = if (filtersActive) MaterialTheme.colorScheme.primary else LocalContentColor.current,
                )
            }
            Box {
                IconButton(onClick = { menuOpen = true }) {
                    Icon(Icons.Filled.MoreVert, contentDescription = "Library menu")
                }
                DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
                    DropdownMenuItem(
                        text = { Text(stringResource(Res.string.library_search_help)) },
                        onClick = { menuOpen = false; searchHelpOpen = true },
                    )
                    DropdownMenuItem(
                        text = { Text(stringResource(Res.string.update_library)) },
                        enabled = !refreshing,
                        onClick = { menuOpen = false; onRefresh() },
                    )
                    DropdownMenuItem(
                        text = { Text(stringResource(Res.string.open_random_entry)) },
                        onClick = { menuOpen = false; onRandomOpen() },
                    )
                    DropdownMenuItem(
                        text = { Text(stringResource(Res.string.import_local_file)) },
                        onClick = { menuOpen = false; onOpenImport() },
                    )
                    if (itemType == ItemType.Anime) {
                        DropdownMenuItem(
                            text = { Text(stringResource(Res.string.torrent_stream)) },
                            onClick = { menuOpen = false; onOpenTorrent() },
                        )
                    }
                }
            }
        },
    )
    if (searchHelpOpen) {
        androidx.compose.material3.AlertDialog(
            modifier = Modifier.compactDialogWidth(),
            onDismissRequest = { searchHelpOpen = false },
            title = { Text(stringResource(Res.string.library_search_help)) },
            text = {
                Text(
                    stringResource(Res.string.library_search_help_body),
                    modifier = Modifier.verticalScroll(rememberScrollState()),
                )
            },
            confirmButton = {
                androidx.compose.material3.TextButton(onClick = { searchHelpOpen = false }) {
                    Text(stringResource(Res.string.ok))
                }
            },
        )
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Category tabs

@Composable
private fun RefreshSummaryBanner(refreshSummary: String?) {
    refreshSummary?.let { summary ->
        Surface(
            modifier = Modifier.fillMaxWidth(),
            color = MaterialTheme.colorScheme.surfaceVariant,
        ) {
            Text(
                text = summary,
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
private fun LibraryCategoryPager(
    tabs: List<LibraryCategoryTab>,
    selectedCategoryId: Long?,
    showCounts: Boolean,
    refreshSummary: String?,
    onSelectCategory: (Long) -> Unit,
    page: @Composable (categoryId: Long) -> Unit,
) {
    val selectedId = selectedCategoryId ?: tabs.first().id
    val selectedIndex = tabs.indexOfFirst { it.id == selectedId }.takeIf { it >= 0 } ?: 0
    val tabIds = remember(tabs) { tabs.map { it.id } }
    val pagerState = rememberPagerState(initialPage = selectedIndex, pageCount = { tabs.size })
    val selectedPage = pagerState.currentPage.coerceIn(tabs.indices)
    val scope = rememberCoroutineScope()

    LaunchedEffect(tabIds, selectedIndex) {
        if (pagerState.currentPage > tabs.lastIndex) {
            pagerState.scrollToPage(tabs.lastIndex)
        } else if (pagerState.currentPage != selectedIndex) {
            pagerState.scrollToPage(selectedIndex)
        }
    }

    LaunchedEffect(pagerState, tabIds) {
        snapshotFlow { pagerState.settledPage }.collect { settled ->
            val tab = tabs.getOrNull(settled) ?: return@collect
            onSelectCategory(tab.id)
        }
    }

    if (tabs.size > 64) {
        val rowState = rememberLazyListState()
        val indicator = MaterialTheme.colorScheme.primary
        LaunchedEffect(tabIds, selectedPage) {
            val visible = rowState.layoutInfo.visibleItemsInfo
            if (visible.any { it.index == selectedPage }) rowState.animateScrollToItem(selectedPage)
            else rowState.scrollToItem(selectedPage)
        }
        LazyRow(state = rowState, modifier = Modifier.fillMaxWidth()) {
            itemsIndexed(tabs, key = { _, tab -> tab.id }, contentType = { _, _ -> "library-tab" }) { index, tab ->
                LibraryGroupTab(tab, selectedPage == index, showCounts,
                    onClick = { scope.launch { pagerState.animateScrollToPage(index) } },
                    modifier = Modifier.widthIn(min = 90.dp, max = 240.dp).width(IntrinsicSize.Max).drawBehind {
                        if (selectedPage == index) {
                            val thickness = 3.dp.toPx()
                            drawLine(indicator, Offset(0f, size.height - thickness / 2),
                                Offset(size.width, size.height - thickness / 2), thickness)
                        }
                    })
            }
        }
    } else SecondaryScrollableTabRow(
        selectedTabIndex = selectedPage,
        edgePadding = 0.dp,
        modifier = Modifier.fillMaxWidth(),
    ) {
        tabs.forEachIndexed { index, tab ->
            LibraryGroupTab(tab, selectedPage == index, showCounts,
                onClick = { scope.launch { pagerState.animateScrollToPage(index) } })
        }
    }
    RefreshSummaryBanner(refreshSummary)
    HorizontalPager(
        state = pagerState,
        beyondViewportPageCount = 1,
        modifier = Modifier.fillMaxSize(),
    ) { index ->
        page(tabs[index].id)
    }
}

@Composable
private fun LibraryGroupTab(tab: LibraryCategoryTab, selected: Boolean, showCounts: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier) {
    Tab(selected = selected, onClick = onClick, modifier = modifier, text = {
        Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
            Text(text = when {
                tab.id == UncategorizedCategoryId -> stringResource(Res.string.default0)
                tab.label == LibraryTabLabel.All -> stringResource(Res.string.library_group_all)
                tab.label == LibraryTabLabel.Untracked -> stringResource(Res.string.library_group_untracked)
                tab.label == LibraryTabLabel.Untagged -> stringResource(Res.string.library_group_untagged)
                tab.label == LibraryTabLabel.UnknownSource -> stringResource(Res.string.library_group_unknown_source)
                else -> tab.name
            }, maxLines = 1, overflow = TextOverflow.Ellipsis)
            if (showCounts) {
                Box(modifier = Modifier.size(16.dp).clip(CircleShape).background(MaterialTheme.colorScheme.surfaceVariant),
                    contentAlignment = Alignment.Center) {
                    Text(tab.count.toString(), color = MaterialTheme.colorScheme.onSurface, fontSize = 10.sp)
                }
            }
        }
    })
}

// ─────────────────────────────────────────────────────────────────────────────
// Dialogs

@Composable
private fun ImportLocalDialog(
    itemType: ItemType,
    onDismiss: () -> Unit,
    onImport: () -> Unit,
) {
    val description = when (itemType) {
        ItemType.Manga -> "Import files (.zip, .cbz, .cbr, .rar)"
        ItemType.Anime -> "Import files (.mp4, .mkv, .avi, and more)"
        ItemType.Novel -> "Import files (.epub)"
    }
    androidx.compose.material3.AlertDialog(
        onDismissRequest = onDismiss,
        modifier = Modifier.compactDialogWidth(),
        shape = MaterialTheme.shapes.extraLarge,
        title = {
            Text(
                stringResource(Res.string.import_local_file),
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
            )
        },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                Text(description, style = MaterialTheme.typography.bodyMedium)
                Text(
                    "Tap import to rescan the local library directory.",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
        },
        confirmButton = {
            androidx.compose.material3.Button(
                onClick = onImport,
                shape = RoundedCornerShape(50),
                contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 18.dp, vertical = 8.dp),
            ) {
                Text(stringResource(Res.string.import_local_file), style = MaterialTheme.typography.labelLarge)
            }
        },
        dismissButton = {
            androidx.compose.material3.TextButton(onClick = onDismiss) {
                Text(stringResource(Res.string.action_cancel))
            }
        },
    )
}

@Composable
private fun AddTorrentDialog(
    onDismiss: () -> Unit,
    onAdd: (String) -> Unit,
) {
    val scope = rememberCoroutineScope()
    var url by remember { mutableStateOf("") }
    androidx.compose.material3.AlertDialog(
        onDismissRequest = onDismiss,
        modifier = Modifier.compactDialogWidth(),
        shape = MaterialTheme.shapes.extraLarge,
        title = {
            Text(
                stringResource(Res.string.add_torrent),
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
            )
        },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                OutlinedTextField(
                    value = url,
                    onValueChange = { url = it },
                    label = { Text(stringResource(Res.string.torrent_url)) },
                    placeholder = { Text(stringResource(Res.string.enter_torrent_hint_text)) },
                    singleLine = true,
                    shape = MaterialTheme.shapes.large,
                    modifier = Modifier.fillMaxWidth(),
                    keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Done),
                    keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { if (url.isNotBlank()) onAdd(url.trim()) }),
                )
                Text(
                    stringResource(Res.string.or),
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = androidx.compose.ui.text.style.TextAlign.Center,
                    style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
                // Mangayomi's dialog also imports local .torrent files.
                androidx.compose.material3.TextButton(
                    onClick = {
                        scope.launch {
                            eu.friedcutlet.yokan.services.files.pickFile(listOf("torrent"))
                                ?.takeIf(String::isNotBlank)
                                ?.let(onAdd)
                        }
                    },
                ) { Text(stringResource(Res.string.torrent_file_option)) }
            }
        },
        confirmButton = {
            androidx.compose.material3.Button(
                onClick = { if (url.isNotBlank()) onAdd(url.trim()) },
                enabled = url.isNotBlank(),
                shape = RoundedCornerShape(50),
                contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 18.dp, vertical = 8.dp),
            ) { Text(stringResource(Res.string.add_torrent), style = MaterialTheme.typography.labelLarge) }
        },
        dismissButton = {
            androidx.compose.material3.TextButton(onClick = onDismiss) {
                Text(stringResource(Res.string.action_cancel))
            }
        },
    )
}

@Composable
private fun DeleteLibraryItemsDialog(
    selectedCount: Int,
    itemType: ItemType,
    onConfirm: (deleteFromLibrary: Boolean, deleteDownloads: Boolean) -> Unit,
    onDismiss: () -> Unit,
) {
    var deleteFromLibrary by remember { mutableStateOf(true) }
    var deleteDownloads by remember { mutableStateOf(false) }

    androidx.compose.material3.AlertDialog(
        onDismissRequest = onDismiss,
        modifier = Modifier.compactDialogWidth(),
        shape = MaterialTheme.shapes.extraLarge,
        title = {
            Text(
                stringResource(Res.string.action_remove),
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
            )
        },
        text = {
            Column(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(4.dp),
            ) {
                Text(
                    "Remove $selectedCount item(s)?",
                    style = MaterialTheme.typography.bodyMedium,
                )
                Spacer(Modifier.height(4.dp))
                // Trailing padding is inner spacing, so the ripple fills the whole clipped row.
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp)
                        .clip(MaterialTheme.shapes.small)
                        .clickable { deleteFromLibrary = !deleteFromLibrary }
                        .padding(horizontal = 4.dp, vertical = 4.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    Checkbox(
                        checked = deleteFromLibrary,
                        onCheckedChange = { deleteFromLibrary = it },
                    )
                    Text(
                        "From library",
                        style = MaterialTheme.typography.bodyMedium,
                    )
                }
                // Trailing padding is inner spacing, so the ripple fills the whole clipped row.
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp)
                        .clip(MaterialTheme.shapes.small)
                        .clickable { deleteDownloads = !deleteDownloads }
                        .padding(horizontal = 4.dp, vertical = 4.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    Checkbox(
                        checked = deleteDownloads,
                        onCheckedChange = { deleteDownloads = it },
                    )
                    Text(
                        stringResource(
                            if (itemType == ItemType.Anime) Res.string.downloaded_episodes else Res.string.downloaded_chapters
                        ),
                        style = MaterialTheme.typography.bodyMedium,
                    )
                }
            }
        },
        confirmButton = {
            androidx.compose.material3.TextButton(
                onClick = { onConfirm(deleteFromLibrary, deleteDownloads) },
                enabled = deleteFromLibrary || deleteDownloads,
            ) {
                Text(
                    stringResource(Res.string.action_remove),
                    color = if (deleteFromLibrary || deleteDownloads) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f),
                )
            }
        },
        dismissButton = {
            androidx.compose.material3.TextButton(onClick = onDismiss) {
                Text(stringResource(Res.string.action_cancel))
            }
        },
    )
}

// ─────────────────────────────────────────────────────────────────────────────
// Helpers

private fun LibraryFilterTypes.anyActive(): Boolean =
    downloaded != 0 || unread != 0 || started != 0 || bookmarked != 0 || completed != 0 || tracking != 0 ||
        customInterval != 0 || providerTracking.isNotEmpty()
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibrarySelectionBars.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibrarySelectionBars.kt) · implementation · 84 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
32: internal fun LibrarySelectionAppBar(
60: internal fun LibrarySelectionBottomBar(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibrarySelectionBars.kt) · SHA-256 `e6daf6b1d965b85cc5db118ca1a15301d251667bd980a29a9c08be884185c146`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Label
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material.icons.filled.DoneAll
import androidx.compose.material.icons.filled.FlipToBack
import androidx.compose.material.icons.filled.RemoveDone
import androidx.compose.material.icons.filled.SelectAll
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_remove
import yokan.composeapp.generated.resources.ui_close
import yokan.composeapp.generated.resources.ui_mark_read
import yokan.composeapp.generated.resources.ui_mark_unread

@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun LibrarySelectionAppBar(
    selectedCount: Int,
    onClear: () -> Unit,
    onSelectAll: () -> Unit,
    onInvert: () -> Unit,
) {
    TopAppBar(
        title = { Text(selectedCount.toString()) },
        navigationIcon = {
            IconButton(onClick = onClear) {
                Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.ui_close))
            }
        },
        actions = {
            IconButton(onClick = onSelectAll) {
                Icon(Icons.Filled.SelectAll, contentDescription = "Select all")
            }
            IconButton(onClick = onInvert) {
                Icon(Icons.Filled.FlipToBack, contentDescription = "Invert selection")
            }
        },
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f),
        ),
    )
}

@Composable
internal fun LibrarySelectionBottomBar(
    onCategorize: () -> Unit,
    onMarkRead: (Boolean) -> Unit,
    onDelete: () -> Unit,
) {
    BottomAppBar {
        Spacer(Modifier.weight(1f))
        IconButton(onClick = onCategorize) {
            Icon(Icons.AutoMirrored.Outlined.Label, contentDescription = "Categorize")
        }
        Spacer(Modifier.weight(1f))
        IconButton(onClick = { onMarkRead(true) }) {
            Icon(Icons.Filled.DoneAll, contentDescription = stringResource(Res.string.ui_mark_read))
        }
        Spacer(Modifier.weight(1f))
        IconButton(onClick = { onMarkRead(false) }) {
            Icon(Icons.Filled.RemoveDone, contentDescription = stringResource(Res.string.ui_mark_unread))
        }
        Spacer(Modifier.weight(1f))
        IconButton(onClick = onDelete) {
            Icon(Icons.Filled.DeleteOutline, contentDescription = stringResource(Res.string.action_remove))
        }
        Spacer(Modifier.weight(1f))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibrarySettingsSheet.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibrarySettingsSheet.kt) · implementation · 472 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
115: internal fun LibrarySettingsSheet(
209: private fun LibraryGroupingSetting(grouping: DbLibraryGrouping, onSelect: (DbLibraryGrouping) -> Unit) {
228: private fun FilterTab(itemType: ItemType, filters: LibraryFilterTypes, onCycle: (LibraryFilterKind) -> Unit,
277: private fun libraryFilterLabel(kind: LibraryFilterKind, itemType: ItemType): String = when (kind) {
290: private fun SortTab(itemType: ItemType, sort: DbSortLibraryManga, onSelect: (Int) -> Unit, onReshuffle: () -> Unit,
338: private fun librarySortLabel(index: Int, itemType: ItemType): String = when (index) {
353: private fun DisplayTab(
453: private fun LibraryDisplayToggleRow(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibrarySettingsSheet.kt) · SHA-256 `7acb04c01ceebd4699f8522bb1e992e9d02440f5e02797f37ba54d9526a7aeda`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDownward
import androidx.compose.material.icons.filled.ArrowUpward
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TriStateCheckbox
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.database.DbCategoryLibraryPreferences
import eu.friedcutlet.yokan.database.DbLibraryGrouping
import eu.friedcutlet.yokan.services.library.LibraryAiringRefreshResult
import kotlin.random.Random
import eu.friedcutlet.yokan.domain.Manga
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.library_category_override
import yokan.composeapp.generated.resources.library_grouping
import yokan.composeapp.generated.resources.library_group_categories
import yokan.composeapp.generated.resources.library_group_source
import yokan.composeapp.generated.resources.library_group_status
import yokan.composeapp.generated.resources.library_group_tracker_status
import yokan.composeapp.generated.resources.library_group_tags
import yokan.composeapp.generated.resources.library_group_ungrouped
import yokan.composeapp.generated.resources.library_filter_custom_interval
import yokan.composeapp.generated.resources.library_filter_providers
import yokan.composeapp.generated.resources.library_filter_unknown_provider
import yokan.composeapp.generated.resources.library_sort_random
import yokan.composeapp.generated.resources.library_sort_tracker_mean
import yokan.composeapp.generated.resources.library_sort_fetch_date
import yokan.composeapp.generated.resources.library_sort_airing_time
import yokan.composeapp.generated.resources.library_reshuffle
import yokan.composeapp.generated.resources.library_refresh_airings
import yokan.composeapp.generated.resources.library_refresh_airings_busy
import yokan.composeapp.generated.resources.library_refresh_airings_description
import yokan.composeapp.generated.resources.library_refresh_airings_result
import yokan.composeapp.generated.resources.library_refresh_airings_failed
import yokan.composeapp.generated.resources.alphabetically
import yokan.composeapp.generated.resources.badges
import yokan.composeapp.generated.resources.bookmarked
import yokan.composeapp.generated.resources.completed
import yokan.composeapp.generated.resources.date_added
import yokan.composeapp.generated.resources.default0
import yokan.composeapp.generated.resources.display
import yokan.composeapp.generated.resources.display_mode
import yokan.composeapp.generated.resources.downloaded
import yokan.composeapp.generated.resources.downloaded_chapters
import yokan.composeapp.generated.resources.downloaded_episodes
import yokan.composeapp.generated.resources.filter
import yokan.composeapp.generated.resources.grid_size
import yokan.composeapp.generated.resources.language
import yokan.composeapp.generated.resources.last_read
import yokan.composeapp.generated.resources.last_update_check
import yokan.composeapp.generated.resources.last_watched
import yokan.composeapp.generated.resources.latest_chapter
import yokan.composeapp.generated.resources.latest_episode
import yokan.composeapp.generated.resources.local_source
import yokan.composeapp.generated.resources.n_per_row
import yokan.composeapp.generated.resources.show_category_tabs
import yokan.composeapp.generated.resources.show_continue_reading_buttons
import yokan.composeapp.generated.resources.show_continue_watching_buttons
import yokan.composeapp.generated.resources.show_numbers_of_items
import yokan.composeapp.generated.resources.sort
import yokan.composeapp.generated.resources.started
import yokan.composeapp.generated.resources.tabs
import yokan.composeapp.generated.resources.total_chapters
import yokan.composeapp.generated.resources.total_episodes
import yokan.composeapp.generated.resources.tracked
import yokan.composeapp.generated.resources.unread
import yokan.composeapp.generated.resources.unread_count
import yokan.composeapp.generated.resources.unwatched
import yokan.composeapp.generated.resources.unwatched_count
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSortLibraryManga
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
import eu.friedcutlet.yokan.ui.components.hoverHighlight

// ─────────────────────────────────────────────────────────────────────────────
// Settings sheet (Filter / Sort / Display)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun LibrarySettingsSheet(
    itemType: ItemType,
    filters: LibraryFilterTypes,
    sort: DbSortLibraryManga,
    display: LibraryDisplay,
    grouping: DbLibraryGrouping = DbLibraryGrouping.Categories,
    selectedCategory: Category? = null,
    categoryPreferences: DbCategoryLibraryPreferences? = null,
    trackerProviders: List<LibraryTrackerChoice> = emptyList(),
    refreshingAirings: Boolean = false,
    airingResult: LibraryAiringRefreshResult? = null,
    airingFailed: Boolean = false,
    onRefreshAirings: () -> Unit = {},
    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
    onDismiss: () -> Unit,
) {
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    var tabIndex by remember { mutableStateOf(0) }
    val categoryScoped = selectedCategory != null && categoryPreferences != null

    ModalBottomSheet(
        onDismissRequest = onDismiss,
        modifier = Modifier.compactSheetWidth(),
        sheetState = sheetState,
    ) {
        if (selectedCategory != null) {
            LibraryDisplayToggleRow(
                label = stringResource(Res.string.library_category_override, selectedCategory.name),
                checked = categoryScoped,
                onCheckedChange = { enabled -> onUpdateSettings { db ->
                    db.withCategoryLibraryPreferences(itemType, selectedCategory.id, if (enabled)
                        DbCategoryLibraryPreferences(db.librarySort(itemType), db.libraryDisplay(itemType).categoryPreferences()) else null)
                } },
            )
        }
        // Pill-tabs sit inside the sheet padding so they look like a control,
        // not a header bar fused to the top edge.
        eu.friedcutlet.yokan.ui.components.YokanChipTabs(
            options = listOf(
                stringResource(Res.string.filter),
                stringResource(Res.string.sort),
                stringResource(Res.string.display),
            ),
            selectedIndex = tabIndex,
            onSelect = { tabIndex = it },
            modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
        )
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .animateContentSize(
                    animationSpec = tween(
                        durationMillis = 300,
                        easing = CubicBezierEasing(0.35f, 0.91f, 0.33f, 0.97f),
                    ),
                )
                .padding(16.dp)
                .verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            when (tabIndex) {
                0 -> FilterTab(
                    itemType = itemType,
                    filters = filters,
                    onCycle = { kind -> onUpdateSettings { it.withLibraryFilterCycled(itemType, kind) } },
                    providers = trackerProviders,
                    onCycleProvider = { id -> onUpdateSettings { it.withLibraryProviderTrackingCycled(itemType, id) } },
                )
                1 -> SortTab(
                    itemType = itemType,
                    sort = if (categoryScoped) categoryPreferences.sort ?: sort else sort,
                    onSelect = { index -> onUpdateSettings {
                        if (categoryScoped) it.withCategoryLibrarySortSelected(itemType, selectedCategory.id, index)
                        else it.withLibrarySortSelected(itemType, index)
                    } },
                    onReshuffle = { val seed = Random.nextLong(); onUpdateSettings { it.withLibraryRandomSeed(itemType, seed) } },
                    refreshingAirings = refreshingAirings, airingResult = airingResult, airingFailed = airingFailed,
                    onRefreshAirings = onRefreshAirings,
                )
                else -> {
                    LibraryGroupingSetting(grouping) { selected -> onUpdateSettings { it.withLibraryGrouping(itemType, selected) } }
                    DisplayTab(itemType, if (categoryScoped) display.forCategory(categoryPreferences) else display,
                        onUpdateSettings = { transform -> onUpdateSettings { db ->
                            if (categoryScoped) db.withCategoryLibraryDisplay(itemType, selectedCategory.id, transform)
                            else transform(db)
                        } }, categoryScoped = categoryScoped)
                }
            }
            Spacer(Modifier.height(8.dp))
        }
    }
}

@Composable
private fun LibraryGroupingSetting(grouping: DbLibraryGrouping, onSelect: (DbLibraryGrouping) -> Unit) {
    var open by remember { mutableStateOf(false) }
    val title = stringResource(Res.string.library_grouping)
    val labels = DbLibraryGrouping.entries.associateWith { group -> stringResource(when (group) {
        DbLibraryGrouping.Categories -> Res.string.library_group_categories
        DbLibraryGrouping.Source -> Res.string.library_group_source
        DbLibraryGrouping.Status -> Res.string.library_group_status
        DbLibraryGrouping.TrackerStatus -> Res.string.library_group_tracker_status
        DbLibraryGrouping.Tags -> Res.string.library_group_tags
        DbLibraryGrouping.Ungrouped -> Res.string.library_group_ungrouped
    }) }
    eu.friedcutlet.yokan.ui.screens.settings.SettingTile(title, labels.getValue(grouping), onClick = { open = true })
    if (open) eu.friedcutlet.yokan.ui.components.ChoiceDialog(
        title = title, options = DbLibraryGrouping.entries, selected = grouping, label = { labels.getValue(it) },
        onSelect = { onSelect(it); open = false }, onDismiss = { open = false },
    )
}

@Composable
private fun FilterTab(itemType: ItemType, filters: LibraryFilterTypes, onCycle: (LibraryFilterKind) -> Unit,
    providers: List<LibraryTrackerChoice>, onCycleProvider: (Int) -> Unit) {
    Column {
        LibraryFilterKind.entries.forEach { kind ->
            val state = when (filters.value(kind)) {
                1 -> ToggleableState.On
                2 -> ToggleableState.Indeterminate
                else -> ToggleableState.Off
            }
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 8.dp)
                    .clickable { onCycle(kind) },
                verticalAlignment = Alignment.CenterVertically,
            ) {
                TriStateCheckbox(
                    state = state,
                    onClick = { onCycle(kind) },
                )
                Spacer(Modifier.width(8.dp))
                Text(
                    text = libraryFilterLabel(kind, itemType),
                    fontSize = 14.sp,
                )
            }
        }
        val choices = (providers + filters.providerTracking.keys.map { LibraryTrackerChoice(it) }).distinctBy { it.id }
        if (choices.isNotEmpty()) {
            Text(stringResource(Res.string.library_filter_providers), style = MaterialTheme.typography.titleSmall,
                modifier = Modifier.padding(8.dp))
            choices.forEach { provider ->
                val state = when (filters.providerTracking[provider.id]) {
                    1 -> ToggleableState.On
                    2 -> ToggleableState.Indeterminate
                    else -> ToggleableState.Off
                }
                Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp).clickable { onCycleProvider(provider.id) },
                    verticalAlignment = Alignment.CenterVertically) {
                    TriStateCheckbox(state, onClick = { onCycleProvider(provider.id) })
                    Spacer(Modifier.width(8.dp))
                    Text(provider.name ?: stringResource(Res.string.library_filter_unknown_provider, provider.id))
                }
            }
        }
    }
}

@Composable
private fun libraryFilterLabel(kind: LibraryFilterKind, itemType: ItemType): String = when (kind) {
    LibraryFilterKind.Downloaded -> stringResource(Res.string.downloaded)
    LibraryFilterKind.Unread -> stringResource(
        if (itemType == ItemType.Anime) Res.string.unwatched else Res.string.unread,
    )
    LibraryFilterKind.Started -> stringResource(Res.string.started)
    LibraryFilterKind.Bookmarked -> stringResource(Res.string.bookmarked)
    LibraryFilterKind.Completed -> stringResource(Res.string.completed)
    LibraryFilterKind.Tracking -> stringResource(Res.string.tracked)
    LibraryFilterKind.CustomInterval -> stringResource(Res.string.library_filter_custom_interval)
}

@Composable
private fun SortTab(itemType: ItemType, sort: DbSortLibraryManga, onSelect: (Int) -> Unit, onReshuffle: () -> Unit,
    refreshingAirings: Boolean, airingResult: LibraryAiringRefreshResult?, airingFailed: Boolean, onRefreshAirings: () -> Unit) {
    Column {
        for (index in 0..(if (itemType == ItemType.Anime) 10 else 9)) {
            val selected = sort.index == index
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .hoverHighlight(onClick = { onSelect(index) })
                    .padding(horizontal = 8.dp),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Icon(
                    imageVector = if (sort.reverse) {
                        Icons.Filled.ArrowUpward
                    } else {
                        Icons.Filled.ArrowDownward
                    },
                    contentDescription = null,
                    tint = if (selected) MaterialTheme.colorScheme.primary else Color.Transparent,
                )
                Spacer(Modifier.width(16.dp))
                Text(
                    text = librarySortLabel(index, itemType),
                    modifier = Modifier
                        .weight(1f)
                        .padding(vertical = 12.dp),
                    fontSize = 14.sp,
                )
            }
        }
        if (sort.index == 7) androidx.compose.material3.TextButton(onClick = onReshuffle) {
            Text(stringResource(Res.string.library_reshuffle))
        }
        if (itemType == ItemType.Anime && sort.index == 10) {
            Text(stringResource(Res.string.library_refresh_airings_description), style = MaterialTheme.typography.bodySmall)
            androidx.compose.material3.TextButton(onClick = onRefreshAirings, enabled = !refreshingAirings) {
                Text(stringResource(if (refreshingAirings) Res.string.library_refresh_airings_busy else Res.string.library_refresh_airings))
            }
            airingResult?.let { result -> Text(stringResource(Res.string.library_refresh_airings_result,
                result.updated, result.unavailable, result.failed), style = MaterialTheme.typography.bodySmall) }
            if (airingFailed) Text(stringResource(Res.string.library_refresh_airings_failed),
                style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
        }
    }
}

@Composable
private fun librarySortLabel(index: Int, itemType: ItemType): String = when (index) {
    1 -> stringResource(if (itemType == ItemType.Anime) Res.string.last_watched else Res.string.last_read)
    2 -> stringResource(Res.string.last_update_check)
    3 -> stringResource(if (itemType == ItemType.Anime) Res.string.unwatched_count else Res.string.unread_count)
    4 -> stringResource(if (itemType == ItemType.Anime) Res.string.total_episodes else Res.string.total_chapters)
    5 -> stringResource(if (itemType == ItemType.Anime) Res.string.latest_episode else Res.string.latest_chapter)
    6 -> stringResource(Res.string.date_added)
    7 -> stringResource(Res.string.library_sort_random)
    8 -> stringResource(Res.string.library_sort_tracker_mean)
    9 -> stringResource(Res.string.library_sort_fetch_date)
    10 -> stringResource(Res.string.library_sort_airing_time)
    else -> stringResource(Res.string.alphabetically)
}

@Composable
private fun DisplayTab(
    itemType: ItemType,
    display: LibraryDisplay,
    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
    categoryScoped: Boolean = false,
) {
    val gridSize = display.gridSize

    Column(horizontalAlignment = Alignment.Start) {
        Text(
            stringResource(Res.string.display_mode),
            modifier = Modifier.padding(start = 4.dp, end = 4.dp, top = 10.dp),
        )
        DisplayTypeSelector(
            selected = display.displayType,
            onSelected = { displayType -> onUpdateSettings { it.withLibraryDisplayType(itemType, displayType) } },
            modifier = Modifier.padding(horizontal = 4.dp, vertical = 5.dp),
        )
        Row(
            modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 10.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Column(
                modifier = Modifier.padding(horizontal = 20.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Text(stringResource(Res.string.grid_size))
                Text(
                    if (gridSize == 0) {
                        stringResource(Res.string.default0)
                    } else {
                        stringResource(Res.string.n_per_row, gridSize.toString())
                    },
                )
            }
            Slider(
                value = gridSize.toFloat(),
                onValueChange = { size -> onUpdateSettings { it.withLibraryGridSize(itemType, size.toInt()) } },
                valueRange = 0f..7f,
                steps = 6,
                modifier = Modifier.weight(1f),
            )
        }
        Text(
            stringResource(Res.string.badges),
            modifier = Modifier.padding(start = 4.dp, end = 4.dp, top = 10.dp),
        )
        LibraryDisplayToggleRow(
            label = stringResource(
                if (itemType == ItemType.Anime) Res.string.downloaded_episodes else Res.string.downloaded_chapters,
            ),
            checked = display.downloadBadges,
            onCheckedChange = { checked -> onUpdateSettings { it.withLibraryDisplay(itemType, downloadBadges = checked) } },
        )
        LibraryDisplayToggleRow(
            label = stringResource(Res.string.language),
            checked = display.language,
            onCheckedChange = { checked -> onUpdateSettings { it.withLibraryDisplay(itemType, language = checked) } },
        )
        LibraryDisplayToggleRow(
            label = "Source",
            checked = display.source,
            onCheckedChange = { checked -> onUpdateSettings { it.withLibraryDisplay(itemType, source = checked) } },
        )
        LibraryDisplayToggleRow(
            label = stringResource(Res.string.local_source),
            checked = display.localBadge,
            onCheckedChange = { checked -> onUpdateSettings { it.withLibraryDisplay(itemType, localBadge = checked) } },
        )
        LibraryDisplayToggleRow(
            label = stringResource(
                if (itemType == ItemType.Anime) {
                    Res.string.show_continue_watching_buttons
                } else {
                    Res.string.show_continue_reading_buttons
                },
            ),
            checked = display.continueButton,
            onCheckedChange = { checked -> onUpdateSettings { it.withLibraryDisplay(itemType, continueButton = checked) } },
        )
        if (!categoryScoped) {
            Text(
                stringResource(Res.string.tabs),
                modifier = Modifier.padding(start = 4.dp, end = 4.dp, top = 10.dp),
            )
            LibraryDisplayToggleRow(
                label = stringResource(Res.string.show_category_tabs),
                checked = display.categoryTabs,
                onCheckedChange = { checked -> onUpdateSettings { it.withLibraryDisplay(itemType, categoryTabs = checked) } },
            )
            LibraryDisplayToggleRow(
                label = stringResource(Res.string.show_numbers_of_items),
                checked = display.itemCounts,
                onCheckedChange = { checked -> onUpdateSettings { it.withLibraryDisplay(itemType, itemCounts = checked) } },
            )
        }
    }
}

@Composable
private fun LibraryDisplayToggleRow(
    label: String,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 8.dp)
            .clickable { onCheckedChange(!checked) },
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Checkbox(
            checked = checked,
            onCheckedChange = onCheckedChange,
        )
        Spacer(Modifier.width(8.dp))
        Text(label, fontSize = 14.sp)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryUpdateScope.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryUpdateScope.kt) · implementation · 20 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
8: internal fun libraryUpdateTitleIds(content: LibraryContent?, selectedId: Long?, mode: DbGroupUpdateMode, index: LibraryIndex): Set<Long>? {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryUpdateScope.kt) · SHA-256 `08f7ae4a9e1078e6bd2aba5c18ba6bc37a494d0cb752641cd8c4f6160a79cefb`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.database.DbGroupUpdateMode
import eu.friedcutlet.yokan.database.DbLibraryGrouping

/** null means global; an empty set means no titles. Search/row filters never shrink group scope. */
internal fun libraryUpdateTitleIds(content: LibraryContent?, selectedId: Long?, mode: DbGroupUpdateMode, index: LibraryIndex): Set<Long>? {
    if (mode == DbGroupUpdateMode.Global) return null
    if (content == null) return emptySet()
    if (mode == DbGroupUpdateMode.CurrentExceptUngrouped && content.grouping == DbLibraryGrouping.Ungrouped) return null
    if (selectedId == null) return null
    if (!content.containsCategory(selectedId)) return emptySet()
    val titles = if (content.grouping == DbLibraryGrouping.Categories) {
        content.library.filter { if (selectedId == UncategorizedCategoryId) it.categories.isEmpty() else selectedId in it.categories }
    } else {
        automaticLibraryGroups(content.library, content.library, content.categories, index, content.grouping).members[selectedId].orEmpty()
    }
    return titles.mapTo(mutableSetOf()) { it.id }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryViewModel.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryViewModel.kt) · implementation · 255 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.

Declaration checklist (source line numbers):
```text
48: class LibraryViewModel(
120: fun onEvent(event: LibraryEvent) {
156: fun shiftCategory(delta: Int): Boolean {
166: fun continueChapterId(manga: Manga): Long? {
172: private fun applyRequest(request: LibraryRequest) {
185: private fun defaultCategoryId(): Long? = if (settings.db.value.features.library.grouping(itemType.toDb()) == DbLibraryGrouping.Categories)
189: private fun writeSelection(write: suspend (Set<Long>) -> Unit) {
196: private fun search(query: String) {
207: private fun refresh() {
222: private fun refreshAirings() {
237: private fun LibraryState.withToggled(mangaId: Long): LibraryState =
241: private fun LibraryState.withContent(content: LibraryContent): LibraryState {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryViewModel.kt) · SHA-256 `fb5dcb26dc66e9d76748792d0a90f1eb4acd52df4b63bd18ca919827f6795f45`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observeSnapshot
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.data.toDomainMangas
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.download.ChapterDownloads
import eu.friedcutlet.yokan.services.library.LibraryUpdateController
import eu.friedcutlet.yokan.services.library.LibraryAiringService
import kotlinx.coroutines.CancellationException
import eu.friedcutlet.yokan.services.library.LocalLibraryController
import eu.friedcutlet.yokan.ui.navigation.LibraryRequest
import eu.friedcutlet.yokan.services.library.sortedChapters
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbLibraryGrouping
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * One item type's library: filtered and sorted entries per category, badges, the category and
 * selection cursor, and the library update. Lives in the root ViewModel store for the whole app.
 */
class LibraryViewModel(
    private val itemType: ItemType,
    private val repository: YokanRepository,
    private val settings: SettingsStore,
    private val libraryIndex: LibraryIndexStore,
    private val libraryUpdates: LibraryUpdateController,
    private val localLibrary: LocalLibraryController,
    private val chapterDownloads: ChapterDownloads,
    libraryRequests: Flow<LibraryRequest?>,
    private val airings: LibraryAiringService? = null,
    trackerProviders: List<LibraryTrackerChoice> = emptyList(),
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
    private val _state = MutableStateFlow(
        LibraryState(
            itemType = itemType,
            query = settings.db.value.libraryQuery(itemType),
            display = settings.db.value.libraryDisplay(itemType),
            selectedCategoryId = defaultCategoryId(),
            trackerProviders = trackerProviders,
        ),
    )
    val state: StateFlow<LibraryState> = _state.asStateFlow()

    private var searchJob: Job? = null
    private var pendingSearch: String? = null

    init {
        val entries = repository.observeSnapshot({ it.mangas to it.settings.titleMetadata }, workDispatcher) { snapshot ->
            snapshot.mangas.filter { it.itemType == itemType.toDb() && it.favorite && it.parentId == null }.toDomainMangas(snapshot.settings)
        }
            .stateIn(viewModelScope, SharingStarted.Eagerly, null)
            .filterNotNull()
        // Empty is the placeholder before the first build; filtering against it would flash wrong results.
        val index = libraryIndex.index.filter { it !== LibraryIndex.Empty }
        viewModelScope.launch {
            settings.db.collect { db ->
                _state.update { it.copy(query = db.libraryQuery(itemType).let { query -> pendingSearch?.let { query.copy(search = it) } ?: query }, display = db.libraryDisplay(itemType)) }
            }
        }
        viewModelScope.launch {
            val releases = LibraryReleaseSelector()
            combine(
                entries,
                repository.observeSnapshot({ it.categories }, workDispatcher) { snapshot ->
                    snapshot.categories.filter { it.forItemType == itemType.toDb() }
                        .sortedBy { it.position ?: 0 }.map { it.toDomain() }
                },
                index,
                settings.db.map { it.libraryQuery(itemType) }.distinctUntilChanged(),
            ) { titles, categories, built, query -> libraryContent(titles, categories, built, query, releases.select(titles, built, query)) }
                .flowOn(workDispatcher)
                .collect { content -> _state.update { it.withContent(content) } }
        }
        viewModelScope.launch {
            combine(entries, index, settings.db.map { db ->
                DbSettings(chapterReleasePreferences = db.chapterReleasePreferences,
                    filterScanlatorList = db.filterScanlatorList, downloadedOnlyMode = db.downloadedOnlyMode)
            }.distinctUntilChanged()) { titles, built, db ->
                buildLibraryBadgeSummaries(
                    chaptersByManga = titles.associate { it.id to built.chapters(it.id) },
                    completedDownloadCountsByChapterId = built.completedDownloadCountsByChapterId,
                    mangaTitles = titles.associate { it.id to it.name },
                    releaseSettings = db,
                )
            }.flowOn(workDispatcher).collect { badges -> _state.update { it.copy(badges = badges) } }
        }
        viewModelScope.launch {
            libraryRequests.filterNotNull().filter { it.itemType == itemType }.collect { applyRequest(it) }
        }
    }

    fun onEvent(event: LibraryEvent) {
        when (event) {
            LibraryEvent.Refresh -> refresh()
            LibraryEvent.RefreshAirings -> refreshAirings()
            is LibraryEvent.Search -> search(event.query)
            is LibraryEvent.SelectCategory -> _state.update { it.copy(selectedCategoryId = event.categoryId) }
            is LibraryEvent.UpdateSettings -> settings.updateDb(event.transform)
            is LibraryEvent.BeginSelection -> _state.update {
                if (it.selectionMode) it.withToggled(event.mangaId) else it.copy(selectedIds = setOf(event.mangaId))
            }
            is LibraryEvent.ToggleSelection -> _state.update { it.withToggled(event.mangaId) }
            LibraryEvent.ClearSelection -> _state.update { it.copy(selectedIds = emptySet()) }
            LibraryEvent.SelectAll -> _state.update { state ->
                state.copy(selectedIds = state.currentItems.mapTo(HashSet()) { it.id })
            }
            LibraryEvent.InvertSelection -> _state.update { state ->
                val visible = state.currentItems.mapTo(HashSet()) { it.id }
                state.copy(selectedIds = (state.selectedIds - visible) + (visible - state.selectedIds))
            }
            is LibraryEvent.MarkSelectedRead -> writeSelection { ids -> repository.setLibraryEntriesRead(ids, event.isRead) }
            is LibraryEvent.SetSelectedCategories -> writeSelection { ids ->
                ids.forEach { repository.setMangaCategories(it, event.categoryIds) }
            }
            is LibraryEvent.RemoveSelected -> writeSelection { ids ->
                val removable = if (event.downloads) chapterDownloads.deleteForMangaAwait(ids) else ids
                if (event.fromLibrary) repository.removeLibraryEntries(removable)
            }
            LibraryEvent.RescanLocalLibrary -> viewModelScope.launch { localLibrary.rescan() }
            is LibraryEvent.ImportTorrent -> viewModelScope.launch { localLibrary.importTorrent(event.pathOrMagnet) }
        }
    }

    /**
     * Moves one visible category forward or back, wrapping at the ends. False when there are fewer
     * than two visible categories, so the caller can switch item types instead.
     */
    fun shiftCategory(delta: Int): Boolean {
        val visible = listOf(null) + _state.value.content?.tabs.orEmpty().map { it.id }
        if (visible.size < 2) return false
        val current = visible.indexOf(_state.value.selectedCategoryId).takeIf { it >= 0 } ?: 0
        val next = ((current + delta) % visible.size + visible.size) % visible.size
        _state.update { it.copy(selectedCategoryId = visible[next]) }
        return true
    }

    /** The chapter "continue" opens: the first unread one in the title's sort order, else the first. */
    fun continueChapterId(manga: Manga): Long? {
        val chapters = sortedChapters(manga, libraryIndex.index.value.chapters(manga.id), settings.db.value)
        return (chapters.firstOrNull { !it.isRead } ?: chapters.firstOrNull())?.id
    }

    /** A query shows every category; otherwise the library opens on its default category. */
    private fun applyRequest(request: LibraryRequest) {
        val query = request.query
        if (query != null) { searchJob?.cancel(); pendingSearch = null }
        if (query != null) settings.updateDb { it.withLibrarySearch(itemType, query) }
        _state.update {
            it.copy(
                selectedCategoryId = if (query != null) null else defaultCategoryId(),
                selectedIds = emptySet(),
            )
        }
    }

    /** The first visible category, so the library opens on one category rather than all of them. */
    private fun defaultCategoryId(): Long? = if (settings.db.value.features.library.grouping(itemType.toDb()) == DbLibraryGrouping.Categories)
        repository.categories(itemType).firstOrNull { !it.hidden }?.id else null

    /** Clears the selection, then runs [write] with its ids off the main thread. */
    private fun writeSelection(write: suspend (Set<Long>) -> Unit) {
        val ids = _state.value.selectedIds
        _state.update { it.copy(selectedIds = emptySet()) }
        if (ids.isEmpty()) return
        viewModelScope.launch { withContext(workDispatcher) { write(ids) } }
    }

    private fun search(query: String) {
        searchJob?.cancel()
        pendingSearch = query
        _state.update { it.copy(query = it.query.copy(search = query)) }
        searchJob = viewModelScope.launch {
            delay(250)
            pendingSearch = null
            settings.updateDb { it.withLibrarySearch(itemType, query) }
        }
    }

    private fun refresh() {
        if (_state.value.refreshing) return
        val current = _state.value
        val titleIds = libraryUpdateTitleIds(current.content, current.selectedCategoryId,
            settings.db.value.features.library.updateGroupMode(itemType.toDb()), libraryIndex.index.value)
        _state.update { it.copy(refreshing = true, lastRefreshSummary = null) }
        viewModelScope.launch {
            try {
                val result = libraryUpdates.run(itemType, titleIds)
                val summary = "Checked ${result.checked}, updated ${result.updated}, failed ${result.failed}"
                _state.update { it.copy(lastRefreshSummary = summary) }
            } finally { _state.update { it.copy(refreshing = false) } }
        }
    }

    private fun refreshAirings() {
        if (itemType != ItemType.Anime || _state.value.refreshingAirings) return
        val service = airings ?: return
        _state.update { it.copy(refreshingAirings = true, airingRefreshResult = null, airingRefreshFailed = false) }
        viewModelScope.launch {
            try {
                val result = withContext(workDispatcher) { service.refresh() }
                _state.update { it.copy(airingRefreshResult = result) }
            } catch (cancel: CancellationException) { throw cancel }
            catch (_: Exception) { _state.update { it.copy(airingRefreshFailed = true) } }
            finally { _state.update { it.copy(refreshingAirings = false) } }
        }
    }
}

private fun LibraryState.withToggled(mangaId: Long): LibraryState =
    copy(selectedIds = if (mangaId in selectedIds) selectedIds - mangaId else selectedIds + mangaId)

/** Publishes [content]; a deleted category falls back to all categories and removed titles leave the selection. */
private fun LibraryState.withContent(content: LibraryContent): LibraryState {
    val groupingChanged = (this.content?.grouping ?: DbLibraryGrouping.Categories) != content.grouping
    val categoryGone = selectedCategoryId != null && !content.containsCategory(selectedCategoryId)
    val libraryIds: Set<Long> = if (selectedIds.isEmpty()) emptySet() else content.library.mapTo(HashSet()) { it.id }
    val keptIds = if (selectedIds.all(libraryIds::contains)) selectedIds else selectedIds.filterTo(HashSet(), libraryIds::contains)
    return copy(
        content = content,
        selectedCategoryId = when {
            groupingChanged -> content.tabs.firstOrNull()?.id
            categoryGone -> null
            else -> selectedCategoryId
        },
        selectedIds = keptIds,
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/BackupDialogs.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/BackupDialogs.kt) · implementation · 149 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
31: internal fun BackupPasswordDialog(
97: internal fun RollbackConfirmDialog(
115: internal fun RestoreBackupWarningDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) {
128: internal fun RestorePasswordDialog(onSubmit: (String) -> Unit, onDismiss: () -> Unit) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/BackupDialogs.kt) · SHA-256 `6b64fa96902bd7c97b3300009a5a4b1f4a3f8fbd92785fc01e3411a577279534`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.settings.data

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.services.backup.MAX_BACKUP_PASSWORD_BYTES
import eu.friedcutlet.yokan.services.backup.SafetySnapshot
import eu.friedcutlet.yokan.services.backup.isValidBackupPassword
import eu.friedcutlet.yokan.ui.components.ConfirmDialog
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.action_open
import yokan.composeapp.generated.resources.ok

/** Asks for a backup encryption password twice; [onConfirm] only receives a password the backup envelope accepts. */
@Composable
internal fun BackupPasswordDialog(
    onConfirm: (String) -> Unit,
    onDismiss: () -> Unit,
    title: String = "Set backup password",
    confirmLabel: String = stringResource(Res.string.ok),
) {
    var password by remember { mutableStateOf("") }
    var confirmation by remember { mutableStateOf("") }
    var error by remember { mutableStateOf<String?>(null) }
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(title) },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                Text(
                    "Enter a password (1–$MAX_BACKUP_PASSWORD_BYTES UTF-8 bytes) to encrypt backup archives using AES-256-GCM. You will need this password to restore your backups.",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
                OutlinedTextField(
                    value = password,
                    onValueChange = {
                        password = it
                        error = null
                    },
                    label = { Text("Password") },
                    visualTransformation = PasswordVisualTransformation(),
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                )
                OutlinedTextField(
                    value = confirmation,
                    onValueChange = {
                        confirmation = it
                        error = null
                    },
                    label = { Text("Confirm password") },
                    visualTransformation = PasswordVisualTransformation(),
                    singleLine = true,
                    isError = error != null,
                    supportingText = error?.let { message -> { Text(message) } },
                    modifier = Modifier.fillMaxWidth(),
                )
            }
        },
        confirmButton = {
            TextButton(
                onClick = {
                    error = when {
                        password != confirmation -> "Passwords do not match"
                        !isValidBackupPassword(password) -> "Password must be 1–$MAX_BACKUP_PASSWORD_BYTES UTF-8 bytes"
                        else -> null
                    }
                    if (error == null) onConfirm(password)
                },
                enabled = password.isNotEmpty() && confirmation.isNotEmpty(),
            ) { Text(confirmLabel) }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) }
        },
    )
}

/** Confirms rolling the database back to [snapshot], taken at [dateLabel]. */
@Composable
internal fun RollbackConfirmDialog(
    snapshot: SafetySnapshot,
    dateLabel: String,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit,
) {
    ConfirmDialog(
        title = "Roll back last change",
        message = "Roll back to safety snapshot from $dateLabel (${snapshot.description})? This will undo the changes and return your database to its state prior to that operation.",
        confirmLabel = "Roll back",
        danger = true,
        onConfirm = onConfirm,
        onDismiss = onDismiss,
    )
}

/** Explains what a restore does before the file picker opens. */
@Composable
internal fun RestoreBackupWarningDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) {
    ConfirmDialog(
        title = "Restore backup",
        message = "Choose a backup file to restore. You will be able to review its contents and choose between Merge (keeping existing titles) or Replace (overwriting library). A safety backup will be created automatically beforehand so this change can be rolled back.",
        confirmLabel = "Choose file",
        danger = false,
        onConfirm = onConfirm,
        onDismiss = onDismiss,
    )
}

/** Asks for the password of an encrypted backup being opened; every open starts with an empty draft. */
@Composable
internal fun RestorePasswordDialog(onSubmit: (String) -> Unit, onDismiss: () -> Unit) {
    var password by remember { mutableStateOf("") }
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Backup password") },
        text = {
            OutlinedTextField(
                value = password,
                onValueChange = { password = it },
                label = { Text("Password") },
                visualTransformation = PasswordVisualTransformation(),
                singleLine = true,
            )
        },
        confirmButton = {
            TextButton(onClick = { onSubmit(password) }) { Text(stringResource(Res.string.action_open)) }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) }
        },
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/BackupOptions.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/BackupOptions.kt) · implementation · 49 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: internal fun buildBackupOptionsFromIds(
32: internal data class BackupOption(val id: Int, val label: String)
48: internal fun toggleOption(options: List<Int>, option: Int): List<Int> =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/BackupOptions.kt) · SHA-256 `c2de56e23e7380818750b7ba1ed4fbd281862e9042c6ac24dfe41878446879e7`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.settings.data

import eu.friedcutlet.yokan.services.backup.BackupFormat
import eu.friedcutlet.yokan.services.backup.BackupOptions

internal fun buildBackupOptionsFromIds(
    ids: List<Int>,
    compressionLevel: Int,
    format: BackupFormat = BackupFormat.Yokan,
): BackupOptions {
    val set = ids.toSet()
    return BackupOptions(
        includeManga = 0 in set,
        includeAnime = 0 in set,
        includeNovel = 0 in set,
        includeCategories = 1 in set,
        includeChapters = 2 in set,
        includeTracks = 3 in set,
        includeHistory = 4 in set,
        includeUpdates = 5 in set,
        includeSettings = 6 in set,
        includeSensitiveSettings = 8 in set,
        includeSources = 7 in set,
        includeCustomButtons = 10 in set,
        compressionLevel = compressionLevel,
        format = format,
    )
}

internal val DefaultBackupOptions = listOf(0, 1, 2, 3, 4, 5, 6, 7, 10)

internal data class BackupOption(val id: Int, val label: String)

internal val BackupOptionTiles = listOf(
    BackupOption(0, "Library entries"),
    BackupOption(1, "Categories"),
    BackupOption(2, "Chapters and episodes"),
    BackupOption(3, "Tracking"),
    BackupOption(4, "History"),
    BackupOption(5, "Updates"),
    BackupOption(6, "App settings"),
    BackupOption(10, "Custom buttons"),
    BackupOption(7, "Source settings"),
    BackupOption(8, "Sensitive settings"),
    BackupOption(9, "Extensions"),
)

internal fun toggleOption(options: List<Int>, option: Int): List<Int> =
    if (option in options) options.filterNot { it == option } else (options + option).sorted()
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/CreateBackupScreen.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/CreateBackupScreen.kt) · implementation · 196 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
34: internal fun CreateBackupRoute(
58: private fun CreateBackupScreen(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/CreateBackupScreen.kt) · SHA-256 `83476db4b275de0ce0f87f49f5e09e23a338aa3a8c78e68f79e1118fae1abccc`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.settings.data

import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.backup.BackupFormat
import eu.friedcutlet.yokan.ui.components.YokanChipTabs
import eu.friedcutlet.yokan.ui.screens.settings.ButtonRow
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.profiles.LocalProfileControls
import eu.friedcutlet.yokan.ui.screens.settings.profiles.ProfileBackupScreen
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.backup_native_private_notes
import yokan.composeapp.generated.resources.backup_external_notes_omitted
import yokan.composeapp.generated.resources.backup_tachiyomi_omitted
import eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider as HorizontalDivider

@Composable
internal fun CreateBackupRoute(
    title: String,
    settings: DbSettings,
    onUpdate: ((DbSettings) -> DbSettings) -> Unit,
    onBack: () -> Unit,
) {
    val controls = LocalProfileControls.current
    if (controls.state.registry.hasAdditionalProfiles) {
        ProfileBackupScreen(export = true, onBack = onBack)
        return
    }
    val model = viewModel { CreateBackupViewModel(YokanRuntime.services.backup, YokanRuntime.localFiles) }
    val state by model.state.collectAsStateWithLifecycle()
    CreateBackupScreen(
        title = title,
        settings = settings,
        state = state,
        onUpdate = onUpdate,
        onBack = onBack,
        onExport = model::export,
    )
}

@Composable
private fun CreateBackupScreen(
    title: String,
    settings: DbSettings,
    state: CreateBackupState,
    onUpdate: ((DbSettings) -> DbSettings) -> Unit,
    onBack: () -> Unit,
    onExport: (autoBackupLocation: String?, ids: List<Int>, compressionLevel: Int, format: BackupFormat, password: String?) -> Unit,
) {
    val options = settings.backupListOptions ?: DefaultBackupOptions
    val compressionLevel = settings.backupCompressionLevel ?: 6
    val running = state.running
    var format by remember { mutableStateOf(BackupFormat.Yokan) }
    var encrypt by remember { mutableStateOf(settings.backupEncryptionEnabled) }
    var passwordDialog by remember { mutableStateOf(false) }
    // Group backup options into Library / Settings / Extensions per the wireframe.
    val libraryIds = setOf(0, 1, 2, 3, 4, 5)
    val settingsIds = setOf(6, 10, 7, 8)
    val extensionsIds = setOf(9)
    SettingsScaffold(title, onBack) {
        item { SettingsSection("Format") }
        item {
            val formats = BackupFormat.entries
            YokanChipTabs(
                options = listOf("Yokan (.json.gz)", "Mangayomi (.backup)", "Mihon/Aniyomi (.tachibk)"),
                selectedIndex = formats.indexOf(format),
                onSelect = { idx ->
                    format = formats[idx]
                    if (formats[idx] != BackupFormat.Yokan) encrypt = false
                },
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
            )
        }
        item {
            SwitchTile(
                title = "Encrypt backup",
                subtitle = if (format != BackupFormat.Yokan) {
                    "Unavailable for Mangayomi and Mihon/Aniyomi exports"
                } else "Password-protect backup files using AES-256-GCM encryption",
                value = encrypt,
                onValueChange = { encrypt = it },
                enabled = format == BackupFormat.Yokan,
            )
        }
        item {
            InfoRow(
                when (format) {
                    BackupFormat.Yokan -> stringResource(Res.string.backup_native_private_notes)
                    BackupFormat.Mangayomi -> stringResource(Res.string.backup_external_notes_omitted)
                    BackupFormat.Tachiyomi -> stringResource(Res.string.backup_tachiyomi_omitted)
                },
            )
        }
        item { SettingsSection("Library") }
        BackupOptionTiles.filter { it.id in libraryIds }.forEach { option ->
            item(key = "backup-option:${option.id}") {
                SwitchTile(
                    option.label,
                    null,
                    option.id in options,
                    { onUpdate { it.copy(backupListOptions = toggleOption(options, option.id)) } },
                )
            }
        }
        item { SettingsSection("Settings") }
        BackupOptionTiles.filter { it.id in settingsIds }.forEach { option ->
            item(key = "backup-option:${option.id}") {
                SwitchTile(
                    option.label,
                    null,
                    option.id in options,
                    { onUpdate { it.copy(backupListOptions = toggleOption(options, option.id)) } },
                )
            }
        }
        item { SettingsSection("Extensions") }
        BackupOptionTiles.filter { it.id in extensionsIds }.forEach { option ->
            item(key = "backup-option:${option.id}") {
                SwitchTile(
                    option.label,
                    null,
                    option.id in options,
                    { onUpdate { it.copy(backupListOptions = toggleOption(options, option.id)) } },
                )
            }
        }
        item { HorizontalDivider() }
        item {
            ButtonRow(if (running) "Creating backup…" else "Create") {
                if (running) return@ButtonRow
                if (encrypt && format == BackupFormat.Yokan) {
                    val savedPassword = settings.backupEncryptionPassword
                    if (savedPassword.isNullOrBlank()) {
                        passwordDialog = true
                        return@ButtonRow
                    }
                    onExport(settings.autoBackupLocation, options, compressionLevel, format, savedPassword)
                    return@ButtonRow
                }
                onExport(settings.autoBackupLocation, options, compressionLevel, format, null)
            }
        }
        if (passwordDialog) {
            item {
                BackupPasswordDialog(
                    onConfirm = { chosenPassword ->
                        passwordDialog = false
                        if (settings.backupEncryptionEnabled && settings.backupEncryptionPassword == null) {
                            onUpdate { it.copy(backupEncryptionPassword = chosenPassword) }
                        }
                        onExport(settings.autoBackupLocation, options, compressionLevel, format, chosenPassword)
                    },
                    onDismiss = { passwordDialog = false },
                    title = "Encrypt backup",
                    confirmLabel = "Encrypt and export",
                )
            }
        }
        state.status?.let { result ->
            item {
                Text(
                    text = "Wrote ${formatBytes(result.bytesWritten)} (${result.itemCount} items) to ${result.path ?: result.fileName}",
                    modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    style = MaterialTheme.typography.bodySmall,
                )
            }
        }
        state.error?.let { message ->
            item {
                Text(
                    text = message,
                    modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
                    color = MaterialTheme.colorScheme.error,
                    style = MaterialTheme.typography.bodySmall,
                )
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/CreateBackupViewModel.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/CreateBackupViewModel.kt) · implementation · 62 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.

Declaration checklist (source line numbers):
```text
17: internal data class CreateBackupState(
24: internal class CreateBackupViewModel(
32: fun export(autoBackupLocation: String?, ids: List<Int>, compressionLevel: Int, format: BackupFormat, password: String?) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/CreateBackupViewModel.kt) · SHA-256 `6d3137157e8b953cda17e2edaee2068c7ba94f402e20297121db4d8c4faf4ad9`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.settings.data

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.services.backup.BackupFormat
import eu.friedcutlet.yokan.services.backup.BackupResult
import eu.friedcutlet.yokan.services.backup.BackupService
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.files.exportFile
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

internal data class CreateBackupState(
    val status: BackupResult? = null,
    val error: String? = null,
    val running: Boolean = false,
)

/** Exports a backup and hands it to the platform save UI. */
internal class CreateBackupViewModel(
    private val backup: BackupService,
    private val files: LocalFileService,
) : ViewModel() {
    private val _state = MutableStateFlow(CreateBackupState())
    val state: StateFlow<CreateBackupState> = _state.asStateFlow()

    /** Encrypts the export when [password] is set; a cancelled save leaves [CreateBackupState.status] null. */
    fun export(autoBackupLocation: String?, ids: List<Int>, compressionLevel: Int, format: BackupFormat, password: String?) {
        _state.update { it.copy(running = true, error = null) }
        viewModelScope.launch {
            catchingNonCancellation {
                val options = buildBackupOptionsFromIds(ids, compressionLevel, format)
                val export = if (password == null) {
                    backup.exportBackup(options)
                } else {
                    backup.exportEncryptedBackup(options, password)
                }
                val path = exportFile(
                    bytes = export.bytes,
                    suggestedName = export.fileName,
                    mimeType = export.contentType,
                    initial = autoBackupLocation
                        ?.takeIf { it.isNotBlank() }
                        ?: files.backupRoot,
                )
                path?.let {
                    BackupResult(
                        fileName = export.fileName,
                        bytesWritten = export.bytes.size.toLong(),
                        itemCount = export.itemCount,
                        path = it,
                    )
                }
            }.onSuccess { result -> _state.update { it.copy(status = result, running = false) } }
                .onFailure { error -> _state.update { it.copy(error = error.message ?: "Backup failed", running = false) } }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/DataAndStorageScreen.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/DataAndStorageScreen.kt) · implementation · 393 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
61: internal fun DataAndStorageRoute(
112: private fun DataAndStorageScreen(
373: internal fun formatBytes(bytes: Long): String {
386: private fun backupFrequencyLabel(value: Int): String = when (value) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/DataAndStorageScreen.kt) · SHA-256 `ae4ee2f332fa53449d93251894a0f009705ea8c35df9c612dce6db5e5a16855a`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.settings.data

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Restore
import androidx.compose.material.icons.filled.Storage
import androidx.compose.material3.Button
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil3.SingletonImageLoader
import coil3.compose.LocalPlatformContext
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.files.pickFile
import eu.friedcutlet.yokan.services.files.pickFolder
import eu.friedcutlet.yokan.services.backup.RestoreMode
import eu.friedcutlet.yokan.services.backup.SafetySnapshot
import eu.friedcutlet.yokan.ui.components.ChoiceDialog
import eu.friedcutlet.yokan.ui.formatTimestamp
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.navigation.PendingBackupFile
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.CreateBackup
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.profiles.LocalProfileControls
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.backup_frequency
import yokan.composeapp.generated.resources.compression_level
import yokan.composeapp.generated.resources.download_location
import yokan.composeapp.generated.resources.tile_clear_cache_on_launch

@Composable
internal fun DataAndStorageRoute(
    title: String,
    settings: DbSettings,
    onUpdate: ((DbSettings) -> DbSettings) -> Unit,
    onBack: () -> Unit,
    onOpen: (SettingsPage) -> Unit,
) {
    val profiles = LocalProfileControls.current
    val imageLoader = SingletonImageLoader.get(LocalPlatformContext.current)
    val model = viewModel {
        DataAndStorageViewModel(
            YokanRuntime.services.backup,
            YokanRuntime.localFiles,
            YokanRuntime.notifications,
            YokanRuntime.repository,
            imageLoader,
        )
    }
    val state by model.state.collectAsStateWithLifecycle()
    LaunchedEffect(settings.downloadLocation, settings.autoBackupLocation, settings.namedLocalFolders, settings.localFolders) {
        model.refreshStorage(settings)
    }
    // A backup opened from the OS lands here; the restore preview's Apply button is the confirmation.
    val pendingBackup by PendingBackupFile.value.collectAsStateWithLifecycle()
    LaunchedEffect(pendingBackup) { PendingBackupFile.take()?.let(model::openBackupFile) }
    DataAndStorageScreen(
        title = title,
        settings = settings,
        state = state,
        downloadRoot = model.downloadRoot,
        backupRoot = model.backupRoot,
        onUpdate = onUpdate,
        onBack = onBack,
        onOpen = onOpen,
        onSelectFrequency = { value ->
            if (value > 0) model.requestNotificationPermission()
            onUpdate { it.copy(backupFrequency = value) }
        },
        onRollback = model::rollback,
        onClearRestoreCandidate = model::clearRestoreCandidate,
        onOpenBackupFile = model::openBackupFile,
        onTargetedRestore = if (profiles.state.registry.hasAdditionalProfiles) ({ onOpen(SettingsPage.RestoreBackup) }) else null,
        onSubmitPassword = model::submitPassword,
        onDismissPassword = model::dismissPassword,
        onSelectRestoreMode = model::selectRestoreMode,
        onApplyRestore = model::applyRestore,
        onClearCache = { model.clearCache(settings) },
    )
}

@Composable
private fun DataAndStorageScreen(
    title: String,
    settings: DbSettings,
    state: DataAndStorageState,
    downloadRoot: String,
    backupRoot: String,
    onUpdate: ((DbSettings) -> DbSettings) -> Unit,
    onBack: () -> Unit,
    onOpen: (SettingsPage) -> Unit,
    onSelectFrequency: (Int) -> Unit,
    onRollback: (SafetySnapshot) -> Unit,
    onClearRestoreCandidate: () -> Unit,
    onOpenBackupFile: (String) -> Unit,
    onTargetedRestore: (() -> Unit)? = null,
    onSubmitPassword: (String) -> Unit,
    onDismissPassword: () -> Unit,
    onSelectRestoreMode: (RestoreMode) -> Unit,
    onApplyRestore: () -> Unit,
    onClearCache: () -> Unit,
) {
    val compression = settings.backupCompressionLevel ?: 6
    // Only drives the platform pickers; service work runs in the view model.
    val scope = rememberCoroutineScope()
    var frequencyDialog by remember { mutableStateOf(false) }
    var restoreWarningOpen by remember { mutableStateOf(false) }
    var encryptionPasswordDialogOpen by remember { mutableStateOf(false) }
    var rollbackSnapshotToConfirm by remember { mutableStateOf<SafetySnapshot?>(null) }
    val cacheLabel = state.storage?.cache?.let { formatBytes(it) } ?: "—"

    if (frequencyDialog) {
        val choices = listOf(0, 1, 2, 3, 4, 5)
        ChoiceDialog(
            title = stringResource(Res.string.backup_frequency),
            options = choices,
            selected = settings.backupFrequency ?: 0,
            label = ::backupFrequencyLabel,
            onSelect = onSelectFrequency,
            onDismiss = { frequencyDialog = false },
        )
    }

    rollbackSnapshotToConfirm?.let { snapshot ->
        RollbackConfirmDialog(
            snapshot = snapshot,
            dateLabel = formatTimestamp(settings, snapshot.createdAt),
            onConfirm = {
                rollbackSnapshotToConfirm = null
                onRollback(snapshot)
            },
            onDismiss = { rollbackSnapshotToConfirm = null },
        )
    }

    if (restoreWarningOpen) {
        RestoreBackupWarningDialog(
            onConfirm = {
                restoreWarningOpen = false
                onClearRestoreCandidate()
                scope.launch {
                    if (onTargetedRestore != null) { onTargetedRestore(); return@launch }
                    pickFile(
                        extensions = listOf("tachibk", "proto", "json", "gz", "backup", "yokanbak"),
                        initial = settings.autoBackupLocation,
                    )?.let(onOpenBackupFile)
                }
            },
            onDismiss = { restoreWarningOpen = false },
        )
    }

    if (state.restorePasswordOpen) {
        RestorePasswordDialog(onSubmit = onSubmitPassword, onDismiss = onDismissPassword)
    }

    if (encryptionPasswordDialogOpen) {
        BackupPasswordDialog(
            onConfirm = { password ->
                onUpdate { it.copy(backupEncryptionEnabled = true, backupEncryptionPassword = password) }
                encryptionPasswordDialogOpen = false
            },
            onDismiss = { encryptionPasswordDialogOpen = false },
        )
    }

    SettingsScaffold(title, onBack) {
        item {
            SettingTile(
                stringResource(Res.string.download_location),
                settings.downloadLocation.ifBlank { downloadRoot },
                onClick = {
                    scope.launch {
                        pickFolder(settings.downloadLocation)?.let { picked ->
                            onUpdate { it.copy(downloadLocation = picked) }
                        }
                    }
                },
            )
        }
        item { InfoRow("Choose where downloaded chapters and episodes are stored. Custom paths interact with auto-cleanup and per-source folders.") }
        item { SettingsSection("Backup and restore") }
        if (state.safetySnapshots.isNotEmpty()) {
            val snapshot = state.safetySnapshots.first()
            val dateLabel = formatTimestamp(settings, snapshot.createdAt)
            item {
                SettingTile(
                    title = "Roll back last change",
                    subtitle = "$dateLabel • ${snapshot.description}",
                    onClick = { rollbackSnapshotToConfirm = snapshot },
                )
            }
        }
        item {
            Row(
                modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                OutlinedButton(
                    modifier = Modifier.weight(1f),
                    onClick = { onOpen(CreateBackup) },
                ) {
                    Icon(Icons.Filled.Storage, contentDescription = null)
                    Spacer(Modifier.width(6.dp))
                    Text("Create backup")
                }
                OutlinedButton(
                    modifier = Modifier.weight(1f),
                    onClick = { restoreWarningOpen = true },
                ) {
                    Icon(Icons.Filled.Restore, contentDescription = null)
                    Spacer(Modifier.width(6.dp))
                    Text("Restore backup")
                }
            }
        }
        state.restoreStatus?.let { message ->
            item { Text(message, modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp), color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall) }
        }
        state.restoreError?.let { message ->
            item { Text(message, modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp), color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
        }
        state.restorePreview?.let { preview ->
            item {
                Column(
                    Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                    Text("Restore preview", fontWeight = FontWeight.Medium)
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                    ) {
                        FilterChip(
                            selected = state.restoreMode == RestoreMode.Merge,
                            onClick = { onSelectRestoreMode(RestoreMode.Merge) },
                            label = { Text("Merge (Keep existing)") },
                        )
                        FilterChip(
                            selected = state.restoreMode == RestoreMode.Replace,
                            onClick = { onSelectRestoreMode(RestoreMode.Replace) },
                            label = { Text("Replace (Overwrite)") },
                        )
                    }
                    if (state.restoreMode == RestoreMode.Merge) {
                        Text(
                            "New series: ${preview.newSeriesCount} • Updated series: ${preview.updatedSeriesCount} • New chapters: ${preview.newChapterCount}",
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            style = MaterialTheme.typography.bodySmall,
                        )
                    } else {
                        Text(
                            "Manga ${preview.mangaCount} • Anime ${preview.animeCount} • Novel ${preview.novelCount} • Categories ${preview.categoryCount} • Chapters ${preview.chapterCount} (all existing will be replaced)",
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            style = MaterialTheme.typography.bodySmall,
                        )
                    }
                    if (preview.conflictingCategories.isNotEmpty()) {
                        Text(
                            "Shared categories: ${preview.conflictingCategories.joinToString()}",
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            style = MaterialTheme.typography.bodySmall,
                        )
                    }
                    if (preview.unmatchedSourceNames.isNotEmpty()) {
                        Text(
                            "Missing sources: ${preview.unmatchedSourceNames.joinToString()}",
                            color = MaterialTheme.colorScheme.error,
                            style = MaterialTheme.typography.bodySmall,
                        )
                    }
                    preview.warnings.forEach { warning ->
                        Text(warning, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
                    }
                    if (state.restorePlan != null) {
                        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                            Button(onClick = onApplyRestore) { Text("Apply restore") }
                            OutlinedButton(onClick = onClearRestoreCandidate) { Text(stringResource(Res.string.action_cancel)) }
                        }
                    }
                }
            }
        }
        item {
            SettingTile(
                stringResource(Res.string.backup_frequency),
                backupFrequencyLabel(settings.backupFrequency ?: 0),
                onClick = { frequencyDialog = true },
            )
        }
        item {
            SwitchTile(
                title = "Encrypt backups",
                subtitle = "Password-protect backup files using AES encryption",
                value = settings.backupEncryptionEnabled,
                onValueChange = { enabled ->
                    if (!enabled) {
                        onUpdate { it.copy(backupEncryptionEnabled = false, backupEncryptionPassword = null) }
                    } else {
                        encryptionPasswordDialogOpen = true
                    }
                },
            )
        }
        item {
            Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
                Text(stringResource(Res.string.compression_level), fontWeight = FontWeight.Medium)
                Text("Higher = smaller files, slower writes", color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall)
                Slider(
                    value = compression.toFloat(),
                    onValueChange = { value -> onUpdate { it.copy(backupCompressionLevel = value.toInt().coerceIn(0, 9)) } },
                    valueRange = 0f..9f,
                    steps = 8,
                )
                Text(compression.toString(), color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall)
            }
        }
        item {
            SettingTile(
                title = "Backup location",
                subtitle = settings.autoBackupLocation ?: backupRoot,
                onClick = {
                    scope.launch {
                        pickFolder(settings.autoBackupLocation)?.let { picked ->
                            onUpdate { it.copy(autoBackupLocation = picked) }
                        }
                    }
                },
            )
        }
        item { InfoRow("Keep backups in a safe place — restoring overwrites your current library, history, and progress.") }
        item { SettingsSection("Storage") }
        item {
            SettingTile(
                title = "Clear chapter and episode cache",
                subtitle = "$cacheLabel cached",
                onClick = onClearCache,
            )
        }
        item { SwitchTile(stringResource(Res.string.tile_clear_cache_on_launch), null, settings.clearChapterCacheOnAppLaunch, { value -> onUpdate { it.copy(clearChapterCacheOnAppLaunch = value) } }) }
    }
}

internal fun formatBytes(bytes: Long): String {
    if (bytes <= 0L) return "0 B"
    val units = listOf("B", "KB", "MB", "GB", "TB")
    var value = bytes.toDouble()
    var unit = 0
    while (value >= 1024 && unit < units.size - 1) {
        value /= 1024
        unit += 1
    }
    val tenths = kotlin.math.round(value * 10).toLong()
    return if (unit == 0) "${bytes} B" else "${tenths / 10}.${tenths % 10} ${units[unit]}"
}

private fun backupFrequencyLabel(value: Int): String = when (value) {
    1 -> "Every 6 hours"
    2 -> "Every 12 hours"
    3 -> "Daily"
    4 -> "Every 2 days"
    5 -> "Weekly"
    else -> "Off"
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/DataAndStorageViewModel.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/DataAndStorageViewModel.kt) · implementation · 210 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.

Declaration checklist (source line numbers):
```text
30: internal data class StorageUsage(
37: internal data class DataAndStorageState(
49: internal class DataAndStorageViewModel(
74: fun requestNotificationPermission() = notifications.requestPermission()
77: fun refreshStorage(settings: DbSettings) {
89: fun clearCache(settings: DbSettings) {
100: fun rollback(snapshot: SafetySnapshot) {
112: fun clearRestoreCandidate() {
118: fun openBackupFile(path: String) {
148: fun submitPassword(password: String) {
175: fun dismissPassword() {
180: fun selectRestoreMode(mode: RestoreMode) = _state.update { it.copy(restoreMode = mode) }
182: fun applyRestore() {
203: private suspend fun computeStorageUsage(settings: DbSettings): StorageUsage = withContext(workDispatcher) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/DataAndStorageViewModel.kt) · SHA-256 `b2198b98c3b7e48d4b5758831b89868a92f0fd88d6e1782e1ddedc85907aef24`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.settings.data

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import coil3.ImageLoader
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.configuredLocalFolders
import eu.friedcutlet.yokan.services.backup.BackupOpenError
import eu.friedcutlet.yokan.services.backup.BackupOpenResult
import eu.friedcutlet.yokan.services.backup.BackupPlan
import eu.friedcutlet.yokan.services.backup.BackupService
import eu.friedcutlet.yokan.services.backup.RestoreMode
import eu.friedcutlet.yokan.services.backup.RestorePreview
import eu.friedcutlet.yokan.services.backup.SafetySnapshot
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.ui.image.clearCaches
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

internal data class StorageUsage(
    val downloads: Long,
    val cache: Long,
    val backups: Long,
    val localFolders: Long,
)

internal data class DataAndStorageState(
    val storage: StorageUsage? = null,
    val safetySnapshots: List<SafetySnapshot> = emptyList(),
    val restoreStatus: String? = null,
    val restoreError: String? = null,
    val restorePreview: RestorePreview? = null,
    val restorePlan: BackupPlan? = null,
    val restoreMode: RestoreMode = RestoreMode.Merge,
    val restorePasswordOpen: Boolean = false,
)

/** Backup restore/rollback and storage usage for the Data and storage page. */
internal class DataAndStorageViewModel(
    private val backup: BackupService,
    private val files: LocalFileService,
    private val notifications: NotificationService,
    private val repository: YokanRepository,
    private val imageLoader: ImageLoader,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
    private val _state = MutableStateFlow(DataAndStorageState())
    val state: StateFlow<DataAndStorageState> = _state.asStateFlow()

    val downloadRoot: String get() = files.downloadRoot
    val backupRoot: String get() = files.backupRoot

    // Bytes of an encrypted backup awaiting its password.
    private var restoreBytes: ByteArray? = null
    private var storageJob: Job? = null

    init {
        viewModelScope.launch {
            val snapshots = catchingNonCancellation { backup.listSafetySnapshots() }.getOrDefault(emptyList())
            _state.update { it.copy(safetySnapshots = snapshots) }
        }
    }

    fun requestNotificationPermission() = notifications.requestPermission()

    /** Recomputes usage for the storage-relevant [settings]; a newer call supersedes a running one. */
    fun refreshStorage(settings: DbSettings) {
        storageJob?.cancel()
        storageJob = viewModelScope.launch {
            val usage = computeStorageUsage(settings)
            _state.update { it.copy(storage = usage) }
        }
    }

    /**
     * The chapter cache: page images (through Coil, which keeps its cache directory open) and saved
     * page lists. Other files under cacheRoot (logs, imported models, archive extraction) stay.
     */
    fun clearCache(settings: DbSettings) {
        viewModelScope.launch {
            withContext(workDispatcher) {
                imageLoader.clearCaches()
                repository.clearPageCache()
            }
            val usage = computeStorageUsage(settings)
            _state.update { it.copy(storage = usage) }
        }
    }

    fun rollback(snapshot: SafetySnapshot) {
        viewModelScope.launch {
            catchingNonCancellation { backup.rollbackSafetySnapshot(snapshot) }
                .onSuccess {
                    _state.update { it.copy(restoreStatus = "Rolled back successfully") }
                    val snapshots = backup.listSafetySnapshots()
                    _state.update { it.copy(safetySnapshots = snapshots) }
                }
                .onFailure { error -> _state.update { it.copy(restoreError = error.message ?: "Rollback failed") } }
        }
    }

    fun clearRestoreCandidate() {
        restoreBytes = null
        _state.update { it.copy(restorePlan = null, restorePreview = null) }
    }

    /** Opens the backup at [path], asking for a password when it is encrypted. */
    fun openBackupFile(path: String) {
        _state.update { it.copy(restoreError = null) }
        viewModelScope.launch {
            catchingNonCancellation {
                val bytes = backup.readBackupFile(path)
                restoreBytes = bytes
                when (val opened = backup.openBackup(bytes)) {
                    is BackupOpenResult.Ready -> {
                        restoreBytes = null
                        _state.update {
                            it.copy(
                                restorePlan = opened.plan,
                                restorePreview = opened.plan.preview,
                                restoreMode = RestoreMode.Merge,
                                restoreError = null,
                            )
                        }
                    }
                    is BackupOpenResult.Failure -> when (opened.error) {
                        BackupOpenError.PasswordRequired -> _state.update { it.copy(restorePasswordOpen = true) }
                        BackupOpenError.AuthenticationFailed -> _state.update {
                            it.copy(restorePasswordOpen = true, restoreError = "Incorrect password, try again.")
                        }
                        else -> _state.update { it.copy(restoreError = "Unable to open backup.") }
                    }
                }
            }.onFailure { error -> _state.update { it.copy(restoreError = error.message ?: "Restore failed") } }
        }
    }

    fun submitPassword(password: String) {
        val bytes = restoreBytes ?: return
        viewModelScope.launch {
            _state.update { it.copy(restoreError = null) }
            when (val opened = backup.openBackup(bytes, password)) {
                is BackupOpenResult.Ready -> {
                    restoreBytes = null
                    _state.update {
                        it.copy(
                            restorePlan = opened.plan,
                            restorePreview = opened.plan.preview,
                            restoreError = null,
                            restorePasswordOpen = false,
                        )
                    }
                }
                is BackupOpenResult.Failure -> {
                    val message = if (opened.error == BackupOpenError.AuthenticationFailed) {
                        "Wrong password or damaged backup"
                    } else "Unable to open backup."
                    _state.update { it.copy(restoreError = message, restorePasswordOpen = false) }
                    clearRestoreCandidate()
                }
            }
        }
    }

    fun dismissPassword() {
        _state.update { it.copy(restorePasswordOpen = false) }
        clearRestoreCandidate()
    }

    fun selectRestoreMode(mode: RestoreMode) = _state.update { it.copy(restoreMode = mode) }

    fun applyRestore() {
        val plan = _state.value.restorePlan ?: return
        val mode = _state.value.restoreMode
        viewModelScope.launch {
            catchingNonCancellation { backup.applyBackup(plan, mode) }
                .onSuccess { preview ->
                    restoreBytes = null
                    _state.update {
                        it.copy(
                            restoreStatus = "Restored ${preview.itemCount} items (${if (mode == RestoreMode.Merge) "Merge" else "Replace"})",
                            restorePlan = null,
                            restorePreview = null,
                        )
                    }
                    val snapshots = backup.listSafetySnapshots()
                    _state.update { it.copy(safetySnapshots = snapshots) }
                }
                .onFailure { error -> _state.update { it.copy(restoreError = error.message ?: "Restore failed") } }
        }
    }

    private suspend fun computeStorageUsage(settings: DbSettings): StorageUsage = withContext(workDispatcher) {
        val downloads = files.directorySize(settings.downloadLocation.takeIf { it.isNotBlank() } ?: files.downloadRoot)
        val cache = files.directorySize(files.cacheRoot)
        val backups = files.directorySize(settings.autoBackupLocation ?: files.backupRoot)
        val local = settings.configuredLocalFolders().sumOf { files.directorySize(it.path) }
        StorageUsage(downloads = downloads, cache = cache, backups = backups, localFolders = local)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/ChapterFetchDateTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/ChapterFetchDateTest.kt) · test / fixture · 37 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
8: class ChapterFetchDateTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/ChapterFetchDateTest.kt) · SHA-256 `b6b93fae620a48037c550748aa8d283f7b60aa320fc771215aee0e08ea659c17`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import kotlin.test.*

class ChapterFetchDateTest {
    @Test fun firstDiscoveryPersistsWhileReadProgressAndRefreshDoNotRewriteIt() {
        val db = InMemoryYokanDatabase(emptySnapshot().copy(sources = listOf(DbSource(id = 1, name = "Source", baseUrl = "https://source.test"))))
        val repository = DefaultYokanRepository(db)
        val source = checkNotNull(repository.source(1))
        val detail = RemoteDetail("Title", "/title", chapters = listOf(RemoteChapter("Chapter 1", "/chapter")))
        val title = repository.upsertRemoteDetail(source, detail, favorite = true)
        val chapter = db.chapters(title.id).single()
        assertTrue(chapter.fetchedAt > 0)
        repository.setChaptersRead(setOf(chapter.id), true, lastPageRead = "7")
        repository.upsertRemoteDetail(source, detail.copy(description = "Refreshed"))
        assertEquals(chapter.fetchedAt, db.chapter(chapter.id)?.fetchedAt)
        assertEquals(chapter.fetchedAt, repository.chapters(title.id).single().fetchedAt)
        val reopened = InMemoryYokanDatabase(checkNotNull(decodeDatabaseSnapshot(encodeDatabaseSnapshot(db.snapshot()))))
        assertEquals(chapter.fetchedAt, reopened.chapter(chapter.id)?.fetchedAt)
    }

    @Test fun legacyDatesStayUnknownInsteadOfBeingInferredFromReadingOrUploadTimestamps() {
        val db = InMemoryYokanDatabase(emptySnapshot().copy(
            sources = listOf(DbSource(id = 1, name = "Source", baseUrl = "https://source.test")),
            mangas = listOf(DbManga(id = 2, name = "Title", link = "/title", sourceId = 1, source = "Source")),
            chapters = listOf(DbChapter(id = 3, mangaId = 2, name = "Chapter 1", url = "/chapter", dateUpload = "2026-01-01", updatedAt = 123456)),
        ))
        val repository = DefaultYokanRepository(db)
        repository.upsertRemoteDetail(checkNotNull(repository.source(1)), RemoteDetail("Title", "/title",
            chapters = listOf(RemoteChapter("Chapter 1", "/chapter", "2026-01-01"))))
        assertEquals(0L, db.chapter(3)?.fetchedAt)
        assertEquals(0L, DatabaseJson.decodeFromString(DbChapter.serializer(), "{\"id\":3}").fetchedAt)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/ChapterReleasePersistenceTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/ChapterReleasePersistenceTest.kt) · test / fixture · 38 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
13: class ChapterReleasePersistenceTest {
15: fun ingestionAndAutomaticReadStateKeepVolumeLanguageAndSpecialReleasesDistinct() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/ChapterReleasePersistenceTest.kt) · SHA-256 `5ea9aa526e63ea5d52fc64ae3ace73b4b8668beebd19dff2822d8f0fd231b5ce`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class ChapterReleasePersistenceTest {
    @Test
    fun ingestionAndAutomaticReadStateKeepVolumeLanguageAndSpecialReleasesDistinct() {
        val source = DbSource(id = 42, name = "Source", baseUrl = "https://source.test", lang = "en")
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = emptyList(), chapters = emptyList(), sources = listOf(source)))
        val repository = DefaultYokanRepository(database)
        val releases = listOf(
            RemoteChapter("Vol. 1 Chapter 1", "/v1-a", scanlator = "A"),
            RemoteChapter("Vol. 1 Chapter 1", "/v1-b", scanlator = "B"),
            RemoteChapter("Vol. 2 Chapter 1", "/v2-a", scanlator = "A"),
            RemoteChapter("Vol. 1 Chapter 1 Special", "/special", scanlator = "A"),
            RemoteChapter("Vol. 1 Chapter 1 [fr]", "/fr", scanlator = "A"),
        )
        val detail = RemoteDetail("Fixture", "/title", chapters = releases)
        val manga = repository.upsertRemoteDetail(source.toDomain(), detail, favorite = true)
        assertEquals(5, repository.chapters(manga.id).size)
        val current = repository.chapters(manga.id).first { it.url == "/v1-a" }
        repository.setChaptersRead(setOf(current.id), true, autoReadDuplicates = true)
        assertTrue(repository.chapters(manga.id).first { it.url == "/v1-b" }.isRead)
        repository.chapters(manga.id).filter { it.url !in setOf("/v1-a", "/v1-b") }.forEach { assertFalse(it.isRead) }
        repository.upsertRemoteDetail(source.toDomain(), detail, favorite = true)
        assertEquals(5, repository.chapters(manga.id).size)
        assertTrue(repository.chapters(manga.id).first { it.url == "/v1-a" }.isRead)
        assertFalse(repository.chapters(manga.id).first { it.url == "/v2-a" }.isRead)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/DefaultLibraryCategoryTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/DefaultLibraryCategoryTest.kt) · test / fixture · 102 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
14: class DefaultLibraryCategoryTest {
99: private fun default(id: Long?) = repository.updateDbSettings { db -> db.copy(features = db.features.copy(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/DefaultLibraryCategoryTest.kt) · SHA-256 `eedcded2a1ae3af21a19c35ff927549034f41c082cdca9d36c2abae5fb0dbd80`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.ItemType
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest

class DefaultLibraryCategoryTest {
    private val database = InMemoryYokanDatabase(emptySnapshot().copy(
        mangas = DbItemType.entries.mapIndexed { index, type ->
            DbManga(id = index + 1L, name = type.name, link = "/${type.name}", itemType = type)
        },
    ))
    private val repository = DefaultYokanRepository(database)

    @Test fun eachMediaTypeUsesItsOwnDefaultAndSerializedSettingsSurviveRestart() {
        val categories = ItemType.entries.map { repository.createCategory(it, it.name) }
        categories.forEach { category ->
            repository.updateDbSettings { db -> db.copy(features = db.features.copy(
                library = db.features.library.withDefaultCategory(category.forItemType.toDb(), category.id),
            )) }
        }
        val saved = checkNotNull(decodeDatabaseSnapshot(encodeDatabaseSnapshot(database.snapshot())))
        val restarted = DefaultYokanRepository(InMemoryYokanDatabase(saved))
        categories.forEachIndexed { index, category ->
            restarted.setMangaFavorite(index + 1L, true)
            assertEquals(listOf(category.id), restarted.manga(index + 1L)?.categories)
        }
        assertEquals(listOf(false, false, false), database.mangas().map { it.favorite })
    }

    @Test fun missingDeletedAndOtherMediaDefaultsNeverAssignForeignCategories() {
        val anime = repository.createCategory(ItemType.Anime, "Anime")
        for (invalid in listOf(anime.id, 999_999L, -1L)) {
            default(invalid)
            repository.setMangaFavorite(1, true)
            assertEquals(emptyList(), repository.manga(1)?.categories)
            repository.setMangaFavorite(1, false)
        }
        val manga = repository.createCategory(ItemType.Manga, "Manga")
        default(manga.id)
        repository.updateDbSettings { db -> db.copy(features = db.features.copy(library = db.features.library
            .withCategory(DbItemType.Manga, manga.id, DbCategoryLibraryPreferences(sort = DbSortLibraryManga(index = 4)))
            .withCategory(DbItemType.Anime, anime.id, DbCategoryLibraryPreferences(sort = DbSortLibraryManga(index = 3))))) }
        repository.removeCategory(manga.id)
        assertNull(repository.dbSettings().features.library.defaultCategory(DbItemType.Manga))
        assertEquals(emptyMap(), repository.dbSettings().features.library.categories(DbItemType.Manga))
        assertEquals(DbSortLibraryManga(index = 3), repository.dbSettings().features.library.categories(DbItemType.Anime)[anime.id]?.sort)
        repository.setMangaFavorite(1, true)
        assertEquals(emptyList(), repository.manga(1)?.categories)
    }

    @Test fun existingAssignmentsAndRepeatedFavoriteCallsKeepExplicitChoices() {
        val automatic = repository.createCategory(ItemType.Manga, "Automatic")
        val explicit = repository.createCategory(ItemType.Manga, "Explicit")
        default(automatic.id)
        repository.setMangaCategories(1, listOf(explicit.id))
        repository.setMangaFavorite(1, true)
        assertEquals(listOf(explicit.id), repository.manga(1)?.categories)
        repository.setMangaCategories(1, emptyList())
        repository.setMangaFavorite(1, true)
        assertEquals(emptyList(), repository.manga(1)?.categories)
        repository.setMangaFavorite(1, false)
        repository.setMangaFavorite(1, true)
        assertEquals(listOf(automatic.id), repository.manga(1)?.categories)
    }

    @Test fun uncategorizedAndAskKeepTheirDistinctSettingsWithoutInventingACategory() {
        default(0)
        repository.setMangaFavorite(1, true)
        assertEquals(0L, repository.dbSettings().features.library.defaultCategory(DbItemType.Manga))
        assertEquals(emptyList(), repository.manga(1)?.categories)
        default(null)
        assertNull(repository.dbSettings().features.library.defaultCategory(DbItemType.Manga))
        repository.setMangaFavorite(1, false)
        repository.setMangaFavorite(1, true)
        assertEquals(emptyList(), repository.manga(1)?.categories)
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    @Test fun explicitFavoriteAndCategorySelectionPublishOneAtomicState() = runTest {
        val automatic = repository.createCategory(ItemType.Manga, "Automatic")
        default(automatic.id)
        val observed = mutableListOf<DbManga>()
        backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
            repository.snapshots.collect { snapshot -> observed += snapshot.mangas.single { it.id == 1L } }
        }
        repository.setMangaCategories(1, emptyList(), favorite = true)
        assertEquals(listOf(false to emptyList<Long>(), true to emptyList<Long>()),
            observed.map { it.favorite to it.categories.orEmpty() })
    }

    private fun default(id: Long?) = repository.updateDbSettings { db -> db.copy(features = db.features.copy(
        library = db.features.library.withDefaultCategory(DbItemType.Manga, id),
    )) }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/DefaultYokanRepositoryTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/DefaultYokanRepositoryTest.kt) · test / fixture · 81 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
18: class DefaultYokanRepositoryTest {
20: fun refreshingADetailLeavesUnchangedChaptersUntouched() {
47: fun pageHeadersRoundTripWhetherSharedOrPerPage() {
65: fun savedPageListsNeverKeepCredentials() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/DefaultYokanRepositoryTest.kt) · SHA-256 `8caf3e384098e8c32d1d3875fec1dbc66c721ada9fccfe1635b2c6983a645964`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class DefaultYokanRepositoryTest {
    @Test
    fun refreshingADetailLeavesUnchangedChaptersUntouched() {
        val database = InMemoryYokanDatabase(
            seedDatabaseSnapshot().copy(
                mangas = listOf(DbManga(id = 1, name = "Title", link = "/title", sourceId = 5, itemType = DbItemType.Manga)),
                chapters = listOf(
                    DbChapter(id = 10, mangaId = 1, name = "Chapter 1", url = "/c1", updatedAt = 1),
                    DbChapter(id = 11, mangaId = 1, name = "Chapter 2", url = "/c2", updatedAt = 1),
                ),
            ),
        )
        val source = Source(id = 5, name = "Source", baseUrl = "https://example.com", lang = "en", itemType = ItemType.Manga, typeSource = "single")

        DefaultYokanRepository(database).upsertRemoteDetail(
            source,
            RemoteDetail(
                title = "Title",
                url = "/title",
                chapters = listOf(RemoteChapter("Chapter 1", "/c1"), RemoteChapter("Chapter 2 (renamed)", "/c2")),
            ),
        )

        assertEquals(1L, database.chapter(10)?.updatedAt, "an unchanged chapter is not rewritten")
        assertEquals("Chapter 2 (renamed)", database.chapter(11)?.name)
        assertTrue((database.chapter(11)?.updatedAt ?: 0) > 1, "a changed chapter still gets a fresh sync timestamp")
    }

    @Test
    fun pageHeadersRoundTripWhetherSharedOrPerPage() {
        val repository = DefaultYokanRepository(InMemoryYokanDatabase(seedDatabaseSnapshot()))
        val shared = mapOf("Referer" to "https://example.com/chapter")
        val sharedPages = (1..3).map { DbPageUrl("https://example.com/$it.jpg", headers = shared) }
        val mixedPages = listOf(
            DbPageUrl("https://example.com/a.jpg", headers = shared),
            DbPageUrl("https://example.com/b.jpg"),
            DbPageUrl("https://example.com/c.jpg", headers = mapOf("Referer" to "other")),
        )

        repository.cachePageUrls(chapterId = 1, chapterUrl = "/1", pageUrls = sharedPages)
        repository.cachePageUrls(chapterId = 2, chapterUrl = "/2", pageUrls = mixedPages)

        assertEquals(sharedPages, repository.pageUrls(1))
        assertEquals(mixedPages, repository.pageUrls(2))
    }

    @Test
    fun savedPageListsNeverKeepCredentials() {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val repository = DefaultYokanRepository(database)
        val source = DbSource(id = 5, version = "2.0.0")
        val kept = mapOf("Referer" to "https://example.com/chapter")

        repository.cachePageUrls(1, "/1", listOf(DbPageUrl("https://example.com/1.jpg", headers = kept + ("cookie" to "session=1"))), source, fetchedAt = 42)
        repository.cachePageUrls(2, "/2", listOf(DbPageUrl("https://example.com/2.jpg", headers = kept + ("AUTHORIZATION" to "Bearer t"))), source, fetchedAt = 42)

        assertEquals(kept, repository.pageUrls(1).single().headers)
        assertEquals(kept, repository.pageUrls(2).single().headers)
        val (withCookie, withAuthorization) = database.pageCache(1).single() to database.pageCache(2).single()
        assertEquals(42L, withCookie.fetchedAt, "the cookie jar re-adds cookies, so the list stays servable")
        assertEquals(null, withAuthorization.fetchedAt, "nothing re-adds Authorization: the list must be refetched")
        assertEquals(5L to "2.0.0", withAuthorization.sourceId to withAuthorization.sourceVersion)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/FillerOverrideTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/FillerOverrideTest.kt) · test / fixture · 50 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
15: class FillerOverrideTest {
28: fun effective() = repository.chapters(title.id).sortedBy { it.url }.map { it.isFiller }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/FillerOverrideTest.kt) · SHA-256 `348e28faf99479ce8977d92b9dade5cb543b0cc67bd01407f6c0139ff438cc47`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.backup.BackupJson
import eu.friedcutlet.yokan.services.backup.BackupSnapshot
import eu.friedcutlet.yokan.services.backup.MangayomiBackupCodec
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.test.*

class FillerOverrideTest {
    @Test fun manualMarksSurviveSourceRefreshAndClearingRestoresTheSourceValue() {
        val db = InMemoryYokanDatabase(emptySnapshot().copy(sources = listOf(DbSource(id = 1, name = "Source", baseUrl = "https://source.test"))))
        val repository = DefaultYokanRepository(db)
        val source = checkNotNull(repository.source(1))
        val detail = RemoteDetail("Show", "/show", chapters = listOf(RemoteChapter("Episode 1", "/e1"), RemoteChapter("Episode 2", "/e2")))
        val title = repository.upsertRemoteDetail(source, detail, favorite = true)
        val (first, second) = db.chapters(title.id).sortedBy { it.url }
        db.upsertChapter(second.copy(isFiller = true)) // source/sidecar mark
        repository.setChaptersFillerOverride(setOf(first.id), true)
        repository.setChaptersFillerOverride(setOf(second.id), false)
        repository.upsertRemoteDetail(source, detail.copy(description = "Refreshed"), favorite = true)

        fun effective() = repository.chapters(title.id).sortedBy { it.url }.map { it.isFiller }
        assertEquals(listOf(true, false), effective())
        assertEquals(listOf(false to true, true to false), db.chapters(title.id).sortedBy { it.url }.map { it.isFiller to it.fillerOverride })
        val stamp = checkNotNull(db.chapter(first.id)).updatedAt
        repository.setChaptersFillerOverride(setOf(first.id), true) // unchanged: no write, no sync churn
        assertEquals(stamp, db.chapter(first.id)?.updatedAt)

        repository.setChaptersFillerOverride(setOf(first.id, second.id), null)
        assertEquals(listOf(false, true), effective())
        assertTrue(db.chapters(title.id).all { it.fillerOverride == null })
    }

    @Test fun legacyBackupExportsTheEffectiveMarkWithoutTheOverrideField() {
        val payload = BackupSnapshot(createdAtMillis = 1, chapters = listOf(
            DbChapter(id = 1, mangaId = 1, isFiller = true, fillerOverride = false),
            DbChapter(id = 2, mangaId = 1, fillerOverride = true),
            DbChapter(id = 3, mangaId = 1, isFiller = true),
        ))
        val rows = BackupJson.parseToJsonElement(MangayomiBackupCodec.encode(payload)).jsonObject.getValue("chapters").jsonArray.map { it.jsonObject }
        assertEquals(listOf(false, true, true), rows.map { it.getValue("isFiller").jsonPrimitive.boolean })
        assertTrue(rows.none { "fillerOverride" in it })
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/LibraryIndexTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/LibraryIndexTest.kt) · test / fixture · 123 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
19: class LibraryIndexTest {
20: private fun database() = InMemoryYokanDatabase(
42: fun progressCheckpointsDoNotPublishAnotherLibraryIndex() = runTest {
57: fun trackerStatusChangesPublishWithoutRegroupingChaptersButRefreshOnlyWritesDoNot() = runTest {
73: fun registeredProviderScalesAreCapturedForNewTrackerIds() = runTest {
84: fun indexGroupsChaptersPerTitleAndCountsCompletedDownloads() = runTest {
98: fun completedDownloadRefreshesCountsWithoutRegroupingChapters() = runTest {
112: fun chapterChangeRegroupsThatTitle() = runTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/LibraryIndexTest.kt) · SHA-256 `f95878a79268ccccff8f99596ea1af4ac07d55eb808876085e6cf203a0ee99c8`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
import kotlin.test.assertTrue
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest

@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class LibraryIndexTest {
    private fun database() = InMemoryYokanDatabase(
        seedDatabaseSnapshot().copy(
            mangas = listOf(
                DbManga(id = 1, name = "One", itemType = DbItemType.Manga, favorite = true),
                DbManga(id = 2, name = "Two", itemType = DbItemType.Manga, favorite = true),
            ),
            chapters = listOf(
                DbChapter(id = 10, mangaId = 1, url = "/10", name = "Ch 1"),
                DbChapter(id = 20, mangaId = 2, url = "/20", name = "Ch 1"),
                DbChapter(id = 11, mangaId = 1, url = "/11", name = "Ch 2"),
            ),
            downloads = listOf(
                DbDownload(id = 100, chapterId = 10, isDownload = true),
                DbDownload(id = 101, chapterId = 10, isDownload = true),
                // Queued, not completed: neither counted nor "downloaded".
                DbDownload(id = 102, chapterId = 20, isDownload = false),
            ),
            tracks = listOf(DbTrack(id = 1, mangaId = 2, status = DbTrackStatus.Reading)),
        ),
    )

    @Test
    fun progressCheckpointsDoNotPublishAnotherLibraryIndex() = runTest {
        val database = database()
        val store = LibraryIndexStore(DefaultYokanRepository(database), backgroundScope,
            kotlinx.coroutines.test.UnconfinedTestDispatcher(testScheduler))
        val before = store.index.first { it !== LibraryIndex.Empty }
        repeat(20) { value ->
            database.upsertDownload(DbDownload(id = 102, chapterId = 20, isDownload = false, succeeded = value))
        }
        assertSame(before, store.index.value)
        database.upsertDownload(DbDownload(id = 102, chapterId = 20, isDownload = true))
        assertEquals(1, store.index.value.completedDownloadCountsByChapterId[20])
    }

    @Test
    @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
    fun trackerStatusChangesPublishWithoutRegroupingChaptersButRefreshOnlyWritesDoNot() = runTest {
        val database = database()
        val store = LibraryIndexStore(DefaultYokanRepository(database), backgroundScope,
            kotlinx.coroutines.test.UnconfinedTestDispatcher(testScheduler))
        val before = store.index.first { it !== LibraryIndex.Empty }
        val track = database.tracks().single()
        database.upsertTrack(track.copy(lastChapterRead = 10, updatedAt = 100))
        assertSame(before, store.index.value)
        database.upsertTrack(track.copy(status = DbTrackStatus.Completed, score = 8))
        val after = store.index.value
        assertSame(before.chaptersByManga, after.chaptersByManga)
        assertEquals(DbTrackStatus.Completed, after.tracksByManga[2]?.single()?.status)
        assertEquals(8, after.tracksByManga[2]?.single()?.score)
    }

    @Test
    fun registeredProviderScalesAreCapturedForNewTrackerIds() = runTest {
        val database = database()
        database.upsertTrack(checkNotNull(database.tracks().singleOrNull()).copy(syncId = 99, score = 10))
        val store = LibraryIndexStore(DefaultYokanRepository(database), backgroundScope, trackerScoreRanges = mapOf(99 to (0..20)))
        val index = store.index.first { it !== LibraryIndex.Empty }
        val track = index.tracksByManga.getValue(2).single()
        assertEquals(20, track.scoreMaximum)
        assertEquals(5.0, eu.friedcutlet.yokan.services.tracking.normalizedTrackerScore(track.providerId, track.score, track.scoreMaximum))
    }

    @Test
    fun indexGroupsChaptersPerTitleAndCountsCompletedDownloads() = runTest {
        val store = LibraryIndexStore(DefaultYokanRepository(database()), backgroundScope)

        val index = store.index.first { it !== LibraryIndex.Empty }

        assertEquals(listOf(10L, 11L), index.chapters(1).map { it.id })
        assertEquals(listOf(20L), index.chapters(2).map { it.id })
        assertTrue(index.chapters(3).isEmpty())
        assertEquals(mapOf(10L to 2), index.completedDownloadCountsByChapterId)
        assertEquals(setOf(10L), index.downloadedChapterIds)
        assertEquals(setOf(2L), index.trackedMangaIds)
    }

    @Test
    fun completedDownloadRefreshesCountsWithoutRegroupingChapters() = runTest {
        val database = database()
        val store = LibraryIndexStore(DefaultYokanRepository(database), backgroundScope)
        val before = store.index.first { it !== LibraryIndex.Empty }

        database.upsertDownload(DbDownload(id = 102, chapterId = 20, isDownload = true))
        val after = store.index.first { it !== before }

        assertEquals(mapOf(10L to 2, 20L to 1), after.completedDownloadCountsByChapterId)
        assertEquals(setOf(10L, 20L), after.downloadedChapterIds)
        assertSame(before.chaptersByManga, after.chaptersByManga)
    }

    @Test
    fun chapterChangeRegroupsThatTitle() = runTest {
        val database = database()
        val store = LibraryIndexStore(DefaultYokanRepository(database), backgroundScope)
        val before = store.index.first { it !== LibraryIndex.Empty }

        database.upsertChapter(DbChapter(id = 21, mangaId = 2, url = "/21", name = "Ch 2"))
        val after = store.index.first { it !== before }

        assertEquals(listOf(20L, 21L), after.chapters(2).map { it.id })
        assertEquals(listOf(10L, 11L), after.chapters(1).map { it.id })
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/LocalLibraryCleanupTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/LocalLibraryCleanupTest.kt) · test / fixture · 104 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
16: class LocalLibraryCleanupTest {
18: fun clearLocalLibraryRemovesOnlyLocalArchiveTitlesAndDependents() {
69: fun pruneConflictPreservesConcurrentEditAndReportsNoDeletion() {
82: private class InjectingDatabase(
86: override fun replaceAll(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/LocalLibraryCleanupTest.kt) · SHA-256 `f9f11fb4a8ffeae7ee3ded8a9ae899680de67a109a0347c9c8f9ff76fcb6f642`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbUpdate
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import kotlin.test.Test
import kotlin.test.assertEquals

class LocalLibraryCleanupTest {
    @Test
    fun clearLocalLibraryRemovesOnlyLocalArchiveTitlesAndDependents() {
        val seed = seedDatabaseSnapshot()
        val database = InMemoryYokanDatabase(
            seed.copy(
                mangas = listOf(
                    DbManga(id = LOCAL_MANGA, name = "Local", source = "local", favorite = true),
                    DbManga(id = ARCHIVE_MANGA, name = "Archive", source = "archive", favorite = true),
                    DbManga(id = REMOTE_MANGA, name = "Remote", source = "remote", favorite = true),
                    DbManga(
                        id = TORRENT_MANGA,
                        name = "Torrent",
                        source = "torrent",
                        favorite = true,
                        isLocalArchive = true,
                    ),
                ),
                chapters = listOf(
                    DbChapter(id = LOCAL_CHAPTER, mangaId = LOCAL_MANGA),
                    DbChapter(id = ARCHIVE_CHAPTER, mangaId = ARCHIVE_MANGA),
                    DbChapter(id = REMOTE_CHAPTER, mangaId = REMOTE_MANGA),
                ),
                histories = listOf(
                    DbHistory(id = 1, mangaId = LOCAL_MANGA, chapterId = LOCAL_CHAPTER, itemType = DbItemType.Manga),
                    DbHistory(id = 2, mangaId = ARCHIVE_MANGA, chapterId = ARCHIVE_CHAPTER, itemType = DbItemType.Manga),
                    DbHistory(id = 3, mangaId = REMOTE_MANGA, chapterId = REMOTE_CHAPTER, itemType = DbItemType.Manga),
                ),
                updates = listOf(
                    DbUpdate(id = 1, mangaId = LOCAL_MANGA, chapterId = LOCAL_CHAPTER),
                    DbUpdate(id = 2, mangaId = ARCHIVE_MANGA, chapterId = ARCHIVE_CHAPTER),
                    DbUpdate(id = 3, mangaId = REMOTE_MANGA, chapterId = REMOTE_CHAPTER),
                ),
                downloads = listOf(
                    DbDownload(id = 1, chapterId = LOCAL_CHAPTER),
                    DbDownload(id = 2, chapterId = ARCHIVE_CHAPTER),
                    DbDownload(id = 3, chapterId = REMOTE_CHAPTER),
                ),
                tracks = emptyList(),
            ),
        )

        val removed = DefaultYokanRepository(database).clearLocalLibrary()

        assertEquals(2, removed)
        assertEquals(setOf(REMOTE_MANGA, TORRENT_MANGA), database.mangas().mapTo(mutableSetOf()) { it.id })
        assertEquals(setOf(REMOTE_CHAPTER), database.chapters().mapTo(mutableSetOf()) { it.id })
        assertEquals(setOf(3L), database.histories().mapTo(mutableSetOf()) { it.id })
        assertEquals(setOf(3L), database.updates().mapTo(mutableSetOf()) { it.id })
        assertEquals(setOf(3L), database.downloads().mapTo(mutableSetOf()) { it.id })
    }

    @Test
    fun pruneConflictPreservesConcurrentEditAndReportsNoDeletion() {
        val title = DbManga(id = 930_001L, name = "Stale", favorite = false)
        val backing = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(title)))
        val database = InjectingDatabase(backing) {
            backing.upsertManga(title.copy(name = "Concurrent edit"))
        }

        val removed = DefaultYokanRepository(database).pruneBrowsedTitles()

        assertEquals(0, removed)
        assertEquals("Concurrent edit", backing.mangas().single().name)
    }

    private class InjectingDatabase(
        private val delegate: InMemoryYokanDatabase,
        private val beforeReplacement: () -> Unit,
    ) : YokanDatabase by delegate {
        override fun replaceAll(
            snapshot: YokanDatabaseSnapshot,
            expectedSnapshot: YokanDatabaseSnapshot?,
        ) {
            beforeReplacement()
            delegate.replaceAll(snapshot, expectedSnapshot)
        }
    }

    private companion object {
        const val LOCAL_MANGA = 910_001L
        const val ARCHIVE_MANGA = 910_002L
        const val REMOTE_MANGA = 910_003L
        const val TORRENT_MANGA = 910_004L
        const val LOCAL_CHAPTER = 920_001L
        const val ARCHIVE_CHAPTER = 920_002L
        const val REMOTE_CHAPTER = 920_003L
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/PrivateNotesTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/PrivateNotesTest.kt) · test / fixture · 85 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
24: class PrivateNotesTest {
26: private fun database() = InMemoryYokanDatabase(emptySnapshot().copy(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/PrivateNotesTest.kt) · SHA-256 `9301e1d01cb99cebf860010b2de19753a39b640d6ee36700b6b3bff1a7564b11`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.decodeDatabaseSnapshot
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.database.encodeDatabaseSnapshot
import eu.friedcutlet.yokan.database.sync.SyncPaths
import eu.friedcutlet.yokan.domain.mergePrivateNotes
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.encodeToJsonElement
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertNull

class PrivateNotesTest {
    private val note = "第一行 🌙\nZweite Zeile\n  keep spacing  "
    private fun database() = InMemoryYokanDatabase(emptySnapshot().copy(
        mangas = listOf(DbManga(id = 1, name = "Title", link = "/title", sourceId = 2, source = "Source", favorite = true)),
        sources = listOf(DbSource(id = 2, name = "Source", isAdded = true)),
    ))

    @Test fun refreshUnfavoriteCleanupAndSnapshotRestartRetainTheNote() {
        val db = database()
        val repo = DefaultYokanRepository(db)
        repo.setMangaPrivateNote(1, note)
        repo.upsertRemoteDetail(checkNotNull(repo.source(2)), RemoteDetail(title = "Refreshed", url = "/title"))
        assertEquals(note, repo.manga(1)?.privateNote)
        repo.setMangaFavorite(1, false)
        assertNull(repo.setMangaPrivateNote(1, "cannot edit"))
        repo.pruneBrowsedTitles()
        repo.cleanDatabase()
        val reopened = InMemoryYokanDatabase(checkNotNull(decodeDatabaseSnapshot(encodeDatabaseSnapshot(db.snapshot()))))
        val restarted = DefaultYokanRepository(reopened)
        restarted.setMangaFavorite(1, true)
        assertEquals(note, restarted.manga(1)?.privateNote)
        restarted.setMangaPrivateNote(1, "")
        assertEquals("", restarted.manga(1)?.privateNote)
    }

    @Test fun localEditEmitsStateWithoutChangingSyncContentOrExposingText() {
        val db = database()
        val repo = DefaultYokanRepository(db)
        val before = db.snapshot()
        val beforeDomain = checkNotNull(repo.manga(1))
        repo.setMangaPrivateNote(1, note)
        val after = db.snapshot()
        assertNotEquals(before, after)
        assertNotEquals(beforeDomain, repo.manga(1))
        assertEquals(before.mangas.single().updatedAt, after.mangas.single().updatedAt)
        assertEquals(before.outbox, after.outbox)
        val doc = SyncPaths.doc(SyncPaths.KIND_MANGA, DbManga.serializer(), after.mangas.single())
        assertFalse("privateNote" in doc)
        val local = Json.encodeToJsonElement(after.mangas.single()).jsonObject
        val malicious = JsonObject(doc + ("privateNote" to JsonPrimitive("remote")))
        val pulled = SyncPaths.applyIncoming(SyncPaths.KIND_MANGA, local, malicious, 1)
        assertEquals(note, pulled["privateNote"]?.jsonPrimitive?.content)
        assertFalse(after.mangas.single().toString().contains(note))
        assertFalse(checkNotNull(repo.manga(1)).toString().contains(note))
    }

    @Test fun independentRepositoriesDoNotShareNotesForTheSameTitleId() {
        val a = DefaultYokanRepository(database())
        val b = DefaultYokanRepository(database())
        a.setMangaPrivateNote(1, note)
        assertEquals("", b.manga(1)?.privateNote)
    }

    @Test fun mergeKeepsBothTextsAndIsIdempotentForRepeatedImports() {
        assertEquals(note, mergePrivateNotes(note, ""))
        assertEquals(note, mergePrivateNotes("", note))
        assertEquals(note, mergePrivateNotes(note, note))
        val combined = mergePrivateNotes("Destination", note)
        assertEquals("Destination\n\n---\n\n$note", combined)
        assertEquals(combined, mergePrivateNotes(combined, note))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/ReaderIncognitoPersistenceTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/ReaderIncognitoPersistenceTest.kt) · test / fixture · 115 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
15: class ReaderIncognitoPersistenceTest {
17: fun incognitoProgressLeavesChapterMangaAndHistoryUnchanged() {
34: fun normalProgressStillPersistsChapterAndHistory() {
53: fun readerCompletionMarksMatchingUnreadScanlationsOnlyWhenEnabled() {
74: fun duplicateScanlationsRemainUnreadWhenReaderSettingIsDisabled() {
89: private fun readerDatabase(incognito: Boolean): InMemoryYokanDatabase {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/ReaderIncognitoPersistenceTest.kt) · SHA-256 `8daee7b8c3ef3ab60b22e5e558a39f363d58f6ce06b4ecf0b5b9822e877c0a3c`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.Chapter
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class ReaderIncognitoPersistenceTest {
    @Test
    fun incognitoProgressLeavesChapterMangaAndHistoryUnchanged() {
        val database = readerDatabase(incognito = true)
        val repository = DefaultYokanRepository(database)
        val before = database.snapshot()

        repository.setChaptersRead(
            chapterIds = setOf(CHAPTER_ID),
            isRead = true,
            lastPageRead = "12",
            readingTimeSeconds = 45,
        )

        assertEquals(before, database.snapshot())
        assertEquals(100L, database.manga(MANGA_ID)?.lastRead)
    }

    @Test
    fun normalProgressStillPersistsChapterAndHistory() {
        val database = readerDatabase(incognito = false)
        val repository = DefaultYokanRepository(database)

        repository.setChaptersRead(
            chapterIds = setOf(CHAPTER_ID),
            isRead = true,
            lastPageRead = "12",
            readingTimeSeconds = 45,
        )

        val chapter = database.chapter(CHAPTER_ID)!!
        assertTrue(chapter.isRead)
        assertEquals("12", chapter.lastPageRead)
        assertFalse(database.manga(MANGA_ID)?.lastRead == 100L)
        assertEquals(55, database.histories().single().readingTimeSeconds)
    }

    @Test
    fun readerCompletionMarksMatchingUnreadScanlationsOnlyWhenEnabled() {
        val database = readerDatabase(incognito = false)
        database.upsertChapter(DbChapter(id = 900_003L, mangaId = MANGA_ID, name = "Ch. 1 - Group B"))
        database.upsertChapter(DbChapter(id = 900_004L, mangaId = MANGA_ID, name = "Chapter 2"))
        val repository = DefaultYokanRepository(database)

        repository.setChaptersRead(
            chapterIds = setOf(CHAPTER_ID),
            isRead = true,
            lastPageRead = "1",
            autoReadDuplicates = true,
        )

        assertTrue(database.chapter(CHAPTER_ID)!!.isRead)
        assertTrue(database.chapter(900_003L)!!.isRead)
        assertEquals("1", database.chapter(900_003L)!!.lastPageRead)
        assertFalse(database.chapter(900_004L)!!.isRead)
        assertEquals(CHAPTER_ID, database.histories().single().chapterId)
    }

    @Test
    fun duplicateScanlationsRemainUnreadWhenReaderSettingIsDisabled() {
        val database = readerDatabase(incognito = false)
        database.upsertChapter(DbChapter(id = 900_003L, mangaId = MANGA_ID, name = "Ch. 1 - Group B"))
        val repository = DefaultYokanRepository(database)

        repository.setChaptersRead(
            chapterIds = setOf(CHAPTER_ID),
            isRead = true,
            lastPageRead = "1",
            autoReadDuplicates = false,
        )

        assertFalse(database.chapter(900_003L)!!.isRead)
    }

    private fun readerDatabase(incognito: Boolean): InMemoryYokanDatabase {
        val seed = seedDatabaseSnapshot()
        return InMemoryYokanDatabase(
            seed.copy(
                settings = seed.settings.copy(incognitoMode = incognito),
                mangas = listOf(DbManga(id = MANGA_ID, name = "Reader fixture", lastRead = 100L)),
                chapters = listOf(DbChapter(id = CHAPTER_ID, mangaId = MANGA_ID, name = "Chapter 1")),
                histories = listOf(
                    DbHistory(
                        id = 1L,
                        mangaId = MANGA_ID,
                        chapterId = CHAPTER_ID,
                        itemType = DbItemType.Manga,
                        readingTimeSeconds = 10,
                    ),
                ),
                tracks = emptyList(),
                downloads = emptyList(),
            ),
        )
    }

    private companion object {
        const val MANGA_ID = 900_001L
        const val CHAPTER_ID = 900_002L
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/RepositorySyncTriggersTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/RepositorySyncTriggersTest.kt) · test / fixture · 51 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
11: class RepositorySyncTriggersTest {
25: fun openingEmitsChapterOrEpisodeOpenByItemType() {
33: fun onlyTheUnreadToReadTransitionEmitsReadOrSeen() {
45: fun incognitoEmitsNothing() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/RepositorySyncTriggersTest.kt) · SHA-256 `53eccdee445599aea33d227a1f503b0d4bb3d12d0d15da6c5c7954ed9789b674`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.services.sync.SyncTriggerKind
import kotlin.test.Test
import kotlin.test.assertEquals

class RepositorySyncTriggersTest {
    private val events = mutableListOf<SyncTriggerKind>()
    private val database = InMemoryYokanDatabase().apply {
        upsertManga(DbManga(id = 1, name = "Manga", itemType = DbItemType.Manga))
        upsertManga(DbManga(id = 2, name = "Anime", itemType = DbItemType.Anime))
        upsertManga(DbManga(id = 3, name = "Novel", itemType = DbItemType.Novel))
        upsertChapter(DbChapter(id = 10, mangaId = 1, name = "Chapter 1"))
        upsertChapter(DbChapter(id = 11, mangaId = 1, name = "Chapter 2"))
        upsertChapter(DbChapter(id = 20, mangaId = 2, name = "Episode 1"))
        upsertChapter(DbChapter(id = 30, mangaId = 3, name = "Chapter 1"))
    }
    private val repository = DefaultYokanRepository(database, onSyncTrigger = { events += it })

    @Test
    fun openingEmitsChapterOrEpisodeOpenByItemType() {
        repository.chapterOpened(10)
        repository.chapterOpened(20)
        repository.chapterOpened(30)
        assertEquals(listOf(SyncTriggerKind.ChapterOpen, SyncTriggerKind.EpisodeOpen, SyncTriggerKind.ChapterOpen), events)
    }

    @Test
    fun onlyTheUnreadToReadTransitionEmitsReadOrSeen() {
        repository.setChaptersRead(setOf(10), isRead = false, lastPageRead = "3")
        assertEquals(emptyList<SyncTriggerKind>(), events)
        repository.setChaptersRead(setOf(10, 11), isRead = true)
        assertEquals(listOf(SyncTriggerKind.ChapterRead), events)
        repository.setChaptersRead(setOf(10), isRead = true)
        assertEquals(listOf(SyncTriggerKind.ChapterRead), events)
        repository.setLibraryEntriesRead(setOf(2), isRead = true)
        assertEquals(listOf(SyncTriggerKind.ChapterRead, SyncTriggerKind.EpisodeSeen), events)
    }

    @Test
    fun incognitoEmitsNothing() {
        database.updateSettings(database.settings().copy(incognitoMode = true))
        repository.chapterOpened(20)
        repository.setChaptersRead(setOf(20), isRead = true)
        assertEquals(emptyList<SyncTriggerKind>(), events)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/SeasonRecordsTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/SeasonRecordsTest.kt) · test / fixture · 130 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
20: class SeasonRecordsTest {
125: private class FakeRuntimes(private val detail: (String) -> RemoteDetail) : ExtensionRuntimeFactory {
126: override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, InMemoryYokanDatabase()) {
127: override suspend fun detail(url: String) = detail.invoke(url)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/SeasonRecordsTest.kt) · SHA-256 `7ea2c259c422e88cdbc8654657e5155188b320caa4e1510057a41028161f65d2`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.database.sync.SyncPaths
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.backup.BackupJson
import eu.friedcutlet.yokan.services.backup.BackupMerge
import eu.friedcutlet.yokan.services.backup.BackupSection
import eu.friedcutlet.yokan.services.backup.BackupSnapshot
import eu.friedcutlet.yokan.services.backup.MangayomiBackupCodec
import eu.friedcutlet.yokan.services.extensions.*
import eu.friedcutlet.yokan.services.extensions.js.remoteDetailFromJson
import eu.friedcutlet.yokan.services.extensions.js.seasonListFromJson
import eu.friedcutlet.yokan.services.library.DefaultLibraryUpdaterService
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.*
import kotlin.test.*

class SeasonRecordsTest {
    private val source = Source(id = 5, name = "Source", baseUrl = "https://example.com", lang = "en", itemType = ItemType.Anime, typeSource = "single")
    private val dbSource = DbSource(id = 5, name = "Source", baseUrl = "https://example.com", lang = "en", itemType = DbItemType.Anime,
        isActive = true, isAdded = true, sourceCodeLanguage = DbSourceCodeLanguage.JavaScript)

    @Test fun decoderReadsAnimetailFetchTypeAndBoundsSeasonLists() {
        val detail = remoteDetailFromJson(Json.parseToJsonElement("""{"title":"Show","url":"/show","fetch_type":"Seasons",
            "episodes":[{"name":"Ignored","url":"/e"}],
            "seasons":[{"title":"S1","url":"/s1","season_number":1},{"title":"Dup","url":"/s1"},{"title":"Movies","url":"/m","fetch_type":0,"season_number":-1}]}"""))
        assertEquals(listOf("/s1", "/m"), detail.seasons?.map { it.url })
        assertEquals(listOf(1.0, null), detail.seasons?.map { it.seasonNumber })
        assertEquals(listOf(false, true), detail.seasons?.map { it.fetchesSeasons })
        assertTrue(detail.chapters.isEmpty())
        // Older extensions omit fetch_type: an ordinary episode list, inline seasons ignored.
        val episodes = remoteDetailFromJson(Json.parseToJsonElement("""{"title":"Show","url":"/show","episodes":[{"name":"E1","url":"/e1"}],"seasons":[]}"""))
        assertNull(episodes.seasons)
        assertEquals(1, episodes.chapters.size)
        assertEquals(emptyList(), remoteDetailFromJson(Json.parseToJsonElement("""{"title":"Show","fetchType":"seasons"}""")).seasons)
        assertFailsWith<IllegalStateException> { seasonListFromJson(JsonObject(emptyMap())) }
        assertFailsWith<IllegalArgumentException> { seasonListFromJson(JsonArray(List(501) { buildJsonObject { put("title", "S$it") } })) }
    }

    @Test fun seasonRecordsKeepProgressFavoritesAndStayOutOfTheLibraryAndCleanup() {
        val db = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            sources = listOf(dbSource),
            // A season browsed earlier from the source becomes the season record, keeping its progress.
            mangas = listOf(DbManga(id = 7, name = "Browsed", link = "/s2", itemType = DbItemType.Anime, source = "Source", sourceId = 5)),
            chapters = listOf(DbChapter(id = 70, mangaId = 7, name = "E1", url = "/s2/e1", isRead = true)),
        ))
        val repository = DefaultYokanRepository(db)
        val detail = RemoteDetail("Show", "/show", seasons = listOf(RemoteManga("Season 1", "/s1", seasonNumber = 1.0), RemoteManga("Season 2", "/s2", seasonNumber = 2.0)))
        val show = repository.upsertRemoteDetail(source, detail, favorite = true)
        assertTrue(show.fetchesSeasons)
        val seasons = db.mangas().filter { it.parentId == show.id }.associateBy { it.link }
        assertEquals(setOf("/s1", "/s2"), seasons.keys)
        assertEquals(7L, seasons.getValue("/s2").id)
        assertTrue(seasons.values.none { it.favorite })
        assertTrue(db.chapter(70)!!.isRead)
        assertEquals(listOf(show.id), repository.library(ItemType.Anime).map { it.id })

        // A refresh keeps records stable and does not rewrite unchanged seasons.
        val stamped = db.mangas().filter { it.parentId == show.id }.associate { it.id to it.updatedAt }
        repository.upsertRemoteDetail(source, detail.copy(seasons = detail.seasons!!.take(1)), favorite = true)
        assertEquals(stamped, db.mangas().filter { it.parentId == show.id }.associate { it.id to it.updatedAt })

        // Cache cleanup keeps seasons of a library show but not unrelated browsed titles.
        db.upsertManga(DbManga(id = 99, name = "Stray", link = "/stray", itemType = DbItemType.Anime, sourceId = 5, source = "Source"))
        repository.cleanDatabase()
        assertNull(db.manga(99))
        assertEquals(setOf("/s1", "/s2"), db.mangas().filter { it.parentId == show.id }.map { it.link }.toSet())
        assertTrue(db.chapter(70)!!.isRead)
        // Once the show leaves the library its seasons are ordinary cache entries again.
        db.upsertManga(db.manga(show.id)!!.copy(favorite = false))
        repository.pruneBrowsedTitles()
        assertTrue(db.mangas().none { it.parentId == show.id })
    }

    @Test fun updaterRefreshesEachSeasonAndRecordsItsNewEpisodes() = runTest {
        val episodes = mutableMapOf("/s1" to listOf("/s1/e1"), "/s2" to listOf("/s2/e1"))
        val db = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            sources = listOf(dbSource),
            mangas = listOf(DbManga(id = 1, name = "Show", link = "/show", itemType = DbItemType.Anime, source = "Source", sourceId = 5, favorite = true)),
        ))
        val updater = DefaultLibraryUpdaterService(db, FakeRuntimes { url ->
            if (url == "/show") RemoteDetail("Show", url, seasons = listOf(RemoteManga("S1", "/s1", seasonNumber = 1.0), RemoteManga("S2", "/s2", seasonNumber = 2.0)))
            else RemoteDetail(url, url, chapters = episodes.getValue(url).map { RemoteChapter(it, it) })
        })
        assertEquals(1, updater.updateLibrary(DbItemType.Anime).updated)
        assertEquals(DbFetchType.Seasons, db.manga(1)!!.fetchType)
        val seasons = db.mangas().filter { it.parentId == 1L }.associateBy { it.link }
        assertTrue(db.chapters(1).isEmpty())
        assertEquals(listOf("/s2/e1"), db.chapters(seasons.getValue("/s2").id).map { it.url })
        val firstRun = db.updates().size
        episodes["/s2"] = listOf("/s2/e1", "/s2/e2")
        updater.updateLibrary(DbItemType.Anime)
        val added = db.updates().drop(firstRun).single()
        assertEquals(seasons.getValue("/s2").id, added.mangaId)
        assertEquals("/s2/e2", db.chapter(added.chapterId!!)!!.url)
        assertEquals(2, db.mangas().count { it.parentId == 1L })
    }

    @Test fun backupsRemapSeasonParentsAndOlderPayloadsDefaultToEpisodeTitles() {
        val show = DbManga(id = 100, name = "Show", link = "/show", itemType = DbItemType.Anime, favorite = true, fetchType = DbFetchType.Seasons)
        val season = DbManga(id = 101, name = "S1", link = "/s1", itemType = DbItemType.Anime, parentId = 100, seasonNumber = 1.0)
        val payload = BackupJson.decodeFromString(BackupSnapshot.serializer(),
            BackupJson.encodeToString(BackupSnapshot.serializer(), BackupSnapshot(createdAtMillis = 1, mangas = listOf(show, season))))
        val current = emptySnapshot().copy(mangas = listOf(DbManga(id = 100, name = "Other", link = "/other", itemType = DbItemType.Anime)))
        val merged = BackupMerge.merge(current, payload, setOf(BackupSection.Anime)).mangas
        val mergedShow = merged.single { it.link == "/show" }
        val mergedSeason = merged.single { it.link == "/s1" }
        assertNotEquals(100L, mergedShow.id)
        assertEquals(mergedShow.id, mergedSeason.parentId)
        assertEquals(DbFetchType.Seasons, mergedShow.fetchType)
        assertFalse(mergedSeason.favorite)
        assertEquals(1.0, mergedSeason.seasonNumber)
        val restored = SyncPaths.json.decodeFromJsonElement(DbManga.serializer(),
            SyncPaths.fromDoc(SyncPaths.KIND_MANGA, SyncPaths.doc(SyncPaths.KIND_MANGA, DbManga.serializer(), season)))
        assertEquals(Triple(100L, DbFetchType.Episodes, 1.0), Triple(restored.parentId, restored.fetchType, restored.seasonNumber))
        val legacy = BackupJson.decodeFromString(DbManga.serializer(), """{"id":3,"name":"Old","itemType":"Anime"}""")
        assertEquals(DbFetchType.Episodes, legacy.fetchType)
        assertNull(legacy.parentId)
        val exported = BackupJson.parseToJsonElement(MangayomiBackupCodec.encode(payload)).jsonObject.getValue("manga").jsonArray
        assertTrue(exported.none { "parentId" in it.jsonObject || "fetchType" in it.jsonObject || "seasonNumber" in it.jsonObject })
    }

    private class FakeRuntimes(private val detail: (String) -> RemoteDetail) : ExtensionRuntimeFactory {
        override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, InMemoryYokanDatabase()) {
            override suspend fun detail(url: String) = detail.invoke(url)
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/SnapshotProjectionTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/SnapshotProjectionTest.kt) · test / fixture · 82 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
22: class SnapshotProjectionTest {
23: private fun database() = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
29: fun projectionKeepsOneRevisionWhenDatabaseChangesDuringMapping() = runTest {
44: fun unrelatedWritesSkipMappingButMetadataChangesAndCancellationAreObserved() = runTest {
69: fun bulkMappingIndexesMetadataOnceAndPreservesFirstDuplicate() {
76: override fun get(index: Int): DbTitleMetadata { visits++; return entries[index] }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/SnapshotProjectionTest.kt) · SHA-256 `a5c11406053e513b411addbfccb3863875c6841b2d5b1ff54e10d8d2966a5b7c`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbTitleMetadata
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

@OptIn(ExperimentalCoroutinesApi::class)
class SnapshotProjectionTest {
    private fun database() = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
        mangas = listOf(DbManga(id = 1, name = "before", itemType = DbItemType.Manga)),
        settings = DbSettings(titleMetadata = listOf(DbTitleMetadata(1, metadataServerId = "before"))),
    ))

    @Test
    fun projectionKeepsOneRevisionWhenDatabaseChangesDuringMapping() = runTest {
        val db = database()
        val values = DefaultYokanRepository(db).observeSnapshot(
            { it.mangas to it.settings.titleMetadata }, UnconfinedTestDispatcher(testScheduler),
        ) { snapshot ->
            if (snapshot.mangas.single().name == "before") db.batch {
                db.upsertManga(db.mangas().single().copy(name = "after"))
                db.updateSettings(db.settings().copy(titleMetadata = listOf(DbTitleMetadata(1, metadataServerId = "after"))))
            }
            snapshot.mangas.toDomainMangas(snapshot.settings).single().let { it.name to it.metadataServerId }
        }.take(2).toList()
        assertEquals(listOf("before" to "before", "after" to "after"), values)
    }

    @Test
    fun unrelatedWritesSkipMappingButMetadataChangesAndCancellationAreObserved() = runTest {
        val db = database()
        var mappings = 0
        val values = mutableListOf<String?>()
        val job = DefaultYokanRepository(db).observeSnapshot(
            { it.mangas to it.settings.titleMetadata }, UnconfinedTestDispatcher(testScheduler),
        ) { snapshot ->
            mappings++
            snapshot.mangas.toDomainMangas(snapshot.settings).single().metadataServerId
        }.onEach { values += it }.launchIn(backgroundScope)
        testScheduler.runCurrent()
        repeat(20) { db.upsertDownload(DbDownload(id = 1, succeeded = it)) }
        db.updateSettings(db.settings().copy(themeIsDark = !db.settings().themeIsDark))
        testScheduler.runCurrent()
        assertEquals(1, mappings)
        db.updateSettings(db.settings().copy(titleMetadata = listOf(DbTitleMetadata(1, metadataServerId = "updated"))))
        testScheduler.runCurrent()
        assertEquals<List<String?>>(listOf("before", "updated"), values)
        job.cancel()
        db.upsertManga(db.mangas().single().copy(name = "closed"))
        testScheduler.runCurrent()
        assertEquals(2, mappings)
    }

    @Test
    fun bulkMappingIndexesMetadataOnceAndPreservesFirstDuplicate() {
        val rows = (1L..500L).map { DbManga(id = it, name = "Title $it", itemType = DbItemType.Manga) }
        val entries = rows.map { DbTitleMetadata(it.id, metadataServerId = "id-${it.id}") } +
            DbTitleMetadata(1, metadataServerId = "duplicate")
        var visits = 0
        val counted = object : AbstractList<DbTitleMetadata>() {
            override val size = entries.size
            override fun get(index: Int): DbTitleMetadata { visits++; return entries[index] }
        }
        val mapped = rows.toDomainMangas(DbSettings(titleMetadata = counted))
        assertEquals(rows.map { "id-${it.id}" }, mapped.map { it.metadataServerId })
        assertTrue(visits <= entries.size * 2, "Metadata must be indexed once, not searched for every title: $visits visits")
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LibraryAiringServiceTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LibraryAiringServiceTest.kt) · test / fixture · 192 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
11: class LibraryAiringServiceTest {
13: private fun database(count: Int = 1) = InMemoryYokanDatabase(emptySnapshot().copy(
20: private fun ids(request: HttpRequest) = DatabaseJson.parseToJsonElement(checkNotNull(request.body)).jsonObject
22: private fun response(request: HttpRequest, at: Long = now + 100_000, missing: Boolean = false): HttpResponse {
31: private fun TestScope.service(db: InMemoryYokanDatabase, http: HttpService, timeout: Long = 20_000) =
129: override suspend fun request(request: HttpRequest): HttpResponse = error("Must stream")
130: override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LibraryAiringServiceTest.kt) · SHA-256 `2bf806c6c5e1db9cce4cdbae028e614b84627fffa2bfc4e7ef30f089ad309af5`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.http.*
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlinx.serialization.json.*
import kotlin.test.*

@OptIn(ExperimentalCoroutinesApi::class)
class LibraryAiringServiceTest {
    private val now = 1_800_000_000_000L
    private fun database(count: Int = 1) = InMemoryYokanDatabase(emptySnapshot().copy(
        mangas = (1L..count.toLong()).map { DbManga(id = it, name = "Private title $it", link = "/title/$it", sourceId = 1,
            itemType = DbItemType.Anime, favorite = true) },
        tracks = (1L..count.toLong()).map { DbTrack(id = it, mangaId = it, mediaId = it + 100, syncId = 2,
            itemType = DbItemType.Anime, status = DbTrackStatus.Watching) },
        trackPreferences = listOf(DbTrackPreference(syncId = 2, oauth = "private-token")),
    ))
    private fun ids(request: HttpRequest) = DatabaseJson.parseToJsonElement(checkNotNull(request.body)).jsonObject
        .getValue("variables").jsonObject.getValue("ids").jsonArray.map { it.jsonPrimitive.int }
    private fun response(request: HttpRequest, at: Long = now + 100_000, missing: Boolean = false): HttpResponse {
        val mal = checkNotNull(request.body).contains("idMal_in")
        return HttpResponse(200, buildJsonObject { putJsonObject("data") { putJsonObject("Page") {
            putJsonArray("media") { ids(request).forEach { id -> add(buildJsonObject {
                put("id", if (mal) id + 1000 else id); put("idMal", if (mal) id else id + 1000); put("type", "ANIME")
                put("nextAiringEpisode", if (missing) JsonNull else buildJsonObject { put("airingAt", at / 1000); put("episode", 12) })
            }) } }
        } } }.toString())
    }
    private fun TestScope.service(db: InMemoryYokanDatabase, http: HttpService, timeout: Long = 20_000) =
        LibraryAiringService(db, http, backgroundScope, { now }, requestIntervalMillis = 0, requestTimeoutMillis = timeout)

    @Test fun refreshIsExplicitAndPersistsPublicSchedulesWithoutSendingTitlesOrCredentials() = runTest {
        val db = database()
        val http = RecordingHttpService { response(it) }
        val service = service(db, http)
        assertTrue(http.requests.isEmpty())
        val before = db.snapshot()
        assertEquals(LibraryAiringRefreshResult(updated = 1), service.refresh())
        val saved = checkNotNull(db.manga(1))
        assertEquals(now + 100_000, saved.nextEpisodeAiringAt)
        assertEquals(12, saved.nextEpisodeNumber)
        assertEquals(now, saved.airingScheduleUpdatedAt)
        assertNotEquals(before, db.snapshot())
        val request = http.requests.single()
        assertEquals("https://graphql.anilist.co", request.url)
        assertEquals("POST", request.method)
        assertFalse(checkNotNull(request.body).contains("Private title"))
        assertFalse(checkNotNull(request.body).contains("private-token"))
        assertTrue(request.headers.keys.none { it.equals("Authorization", true) || it.equals("Cookie", true) })
        val restarted = InMemoryYokanDatabase(checkNotNull(decodeDatabaseSnapshot(encodeDatabaseSnapshot(db.snapshot()))))
        assertEquals(saved.nextEpisodeAiringAt, restarted.manga(1)?.nextEpisodeAiringAt)
    }

    @Test fun requestsAreBatchedByPublicIdentityAndDuplicateSourceEntriesShareOneLookup() = runTest {
        val db = database(105)
        db.upsertTrack(checkNotNull(db.tracks().lastOrNull()).copy(mediaId = 101))
        val batches = mutableListOf<List<Int>>()
        val result = service(db, HttpService { batches += ids(it); response(it) }).refresh()
        assertEquals(listOf(50, 50, 4), batches.map { it.size })
        assertEquals(104, batches.flatten().toSet().size)
        assertEquals(105, result.updated)
        assertTrue(db.mangas().all { it.nextEpisodeAiringAt == now + 100_000 })
    }

    @Test fun malAndExplicitMetadataIdsUseTheCorrectNamespaceAndUnsupportedEntriesMakeNoRequests() = runTest {
        val db = database(4)
        db.upsertTrack(checkNotNull(db.tracks().firstOrNull()).copy(syncId = 1))
        db.removeTrack(2)
        db.updateSettings(db.settings().copy(titleMetadata = listOf(DbTitleMetadata(2, "222", "MyAnimeList"))))
        db.upsertTrack(checkNotNull(db.tracks().firstOrNull { it.id == 3L }).copy(itemType = DbItemType.Manga))
        db.upsertManga(checkNotNull(db.manga(4)).copy(favorite = false))
        val http = RecordingHttpService { response(it) }
        val result = service(db, http).refresh()
        assertEquals(2, result.updated)
        assertEquals(1, result.unavailable)
        assertEquals(1, http.requests.size)
        assertTrue(checkNotNull(http.requests.single().body).contains("idMal_in"))
        assertEquals(setOf(101, 222), ids(http.requests.single()).toSet())
        assertEquals(0L, db.manga(3)?.nextEpisodeAiringAt)
        val unsupported = database()
        unsupported.removeTrack(1)
        assertEquals(LibraryAiringRefreshResult(unavailable = 1), service(unsupported, HttpService { error("Unexpected lookup") }).refresh())
    }

    @Test fun sourceReplacementDeletionUnfavoriteAndRebindingRejectLateResponses() = runTest {
        for (mutation in listOf<(InMemoryYokanDatabase) -> Unit>(
            { db -> db.upsertManga(checkNotNull(db.manga(1)).copy(sourceId = 8, link = "/replacement")) },
            { db -> db.removeManga(1) },
            { db -> db.upsertManga(checkNotNull(db.manga(1)).copy(favorite = false)) },
            { db -> db.upsertTrack(checkNotNull(db.tracks().singleOrNull()).copy(mediaId = 999)) },
        )) {
            val db = database()
            val result = service(db, HttpService { request -> mutation(db); response(request) }).refresh()
            assertEquals(0, result.updated)
            assertTrue(db.manga(1)?.nextEpisodeAiringAt in listOf(null, 0L))
        }
    }

    @Test fun providerFailuresAndMalformedResponsesPreserveSavedSchedules() = runTest {
        val malformed = listOf(
            HttpResponse(429, "rate limited"), HttpResponse(500, "failed"), HttpResponse(200, "not json"),
            HttpResponse(200, "{\"errors\":[{\"message\":\"private remote detail\"}],\"data\":{\"Page\":{\"media\":[]}}}"),
            HttpResponse(200, "{\"data\":{\"Page\":{\"media\":[{\"id\":101,\"type\":\"ANIME\"}]}}}"),
            HttpResponse(200, "{\"data\":{\"Page\":{\"media\":[{\"id\":101,\"type\":\"MANGA\",\"nextAiringEpisode\":null}]}}}"),
        )
        malformed.forEach { reply ->
            val db = database()
            db.upsertManga(checkNotNull(db.manga(1)).copy(nextEpisodeAiringAt = now + 1_000_000))
            assertEquals(1, service(db, HttpService { reply }).refresh().failed)
            assertEquals(now + 1_000_000, db.manga(1)?.nextEpisodeAiringAt)
        }
    }

    @Test fun explicitNoScheduleClearsAnOldAnnouncementButMissingIdentityDoesNot() = runTest {
        val db = database()
        db.upsertManga(checkNotNull(db.manga(1)).copy(nextEpisodeAiringAt = now + 1_000_000))
        assertEquals(1, service(db, HttpService { HttpResponse(200, "{\"data\":{\"Page\":{\"media\":[]}}}") }).refresh().unavailable)
        assertEquals(now + 1_000_000, db.manga(1)?.nextEpisodeAiringAt)
        assertEquals(1, service(db, HttpService { response(it, missing = true) }).refresh().unavailable)
        assertEquals(0L, db.manga(1)?.nextEpisodeAiringAt)
    }

    @Test fun streamingResponseBoundStopsTheTransferBeforeUnboundedAllocation() = runTest {
        val db = database()
        var chunks = 0
        val transport = object : HttpService {
            override suspend fun request(request: HttpRequest): HttpResponse = error("Must stream")
            override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
                repeat(100) { chunks++; onChunk(ByteArray(32 * 1024)) }
                return HttpStreamResponse(200)
            }
        }
        assertEquals(1, service(db, transport).refresh().failed)
        assertEquals(9, chunks)
        assertEquals(0L, db.manga(1)?.nextEpisodeAiringAt)
    }

    @Test fun timeoutIsAnOrdinaryFailureAndDoesNotKillTheProfileOrFutureRefreshes() = runTest {
        val db = database()
        var slow = true
        val service = service(db, HttpService { if (slow) delay(100); response(it) }, timeout = 5)
        assertEquals(1, service.refresh().failed)
        assertTrue(backgroundScope.isActive)
        slow = false
        assertEquals(1, service.refresh().updated)
    }

    @Test fun callerCancellationJoinsItsTransferAndLeavesTheOwnerAvailable() = runTest {
        val db = database()
        val started = CompletableDeferred<Unit>()
        var finalized = false
        val service = service(db, HttpService { started.complete(Unit); try { awaitCancellation() } finally { finalized = true } })
        val request = async { service.refresh() }
        started.await()
        request.cancelAndJoin()
        assertTrue(finalized)
        assertTrue(backgroundScope.isActive)
        assertEquals(0L, db.manga(1)?.nextEpisodeAiringAt)
    }

    @Test fun retiringOneProfileCancelsAndJoinsOnlyItsCapturedWork() = runTest {
        val a = database()
        val b = database()
        val owner = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler))
        val started = CompletableDeferred<Unit>()
        var finalized = false
        val serviceA = LibraryAiringService(a, HttpService { started.complete(Unit); try { awaitCancellation() } finally { finalized = true } }, owner,
            { now }, requestIntervalMillis = 0)
        val request = async { serviceA.refresh() }
        try {
            started.await()
            owner.coroutineContext[Job]?.cancelAndJoin()
            request.join()
            assertTrue(finalized)
            assertTrue(request.isCancelled)
            assertEquals(0L, a.manga(1)?.nextEpisodeAiringAt)
            assertEquals(1, service(b, HttpService { response(it) }).refresh().updated)
            assertEquals(now + 100_000, b.manga(1)?.nextEpisodeAiringAt)
        } finally { owner.cancel(); request.cancelAndJoin() }
    }

    @Test fun requestsAreRateSpacedAcrossBatches() = runTest {
        val db = database(51)
        val times = mutableListOf<Long>()
        val service = LibraryAiringService(db, HttpService { times += testScheduler.currentTime; response(it) }, backgroundScope,
            { now + testScheduler.currentTime }, requestIntervalMillis = 2100)
        assertEquals(51, service.refresh().updated)
        assertEquals(listOf(0L, 2100L), times)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LibraryUpdaterServiceTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LibraryUpdaterServiceTest.kt) · test / fixture · 473 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
34: class LibraryUpdaterServiceTest {
36: fun automaticAdmissionCanDeferBeforeAnySourceRequestWithoutClearingErrors() = runTest {
52: fun automaticAdmissionIsRecheckedAfterWaitingForTheServiceLock() = runTest {
70: fun losingAdmissionBetweenTitlesPreservesUncheckedErrorsAndDoesNotStartAnotherRequest() = runTest {
87: fun emptyAndExplicitScopesDoNotExpandAndPreserveOtherErrorReports() = runTest {
107: fun scheduledAndManualLibraryEntryPointsUseTheSameRestrictionRules() = runTest {
125: fun serviceSerializesSchedulerAndSingleTitleCallsAndCancelledWaitersDoNotFetch() = runTest {
149: fun discoveredChaptersAreHandedToQueueOnceAndExistingChaptersAreNotRequeued() = runTest {
172: fun defaultMeanCadenceSkipsRecentChecksAndAlwaysOverridesIt() = runTest {
190: fun updateTitlePreservesLocalEditsMadeWhileDetailLoads() = runTest {
221: fun updateLibraryPreservesLocalEditsMadeWhileDetailLoads() = runTest {
253: fun updateTitleLeavesUnchangedChaptersUntouched() = runTest {
264: fun cancelledUpdateStopsWithoutRecordingFailures() = runTest {
277: fun updateTitleDoesNotResurrectDeletedTitle() = runTest {
293: fun updateLibraryDoesNotResurrectDeletedTitle() = runTest {
310: fun updateTitleDiscardsResponseAfterLinkChanges() = runTest {
327: fun updateLibraryDiscardsResponseAfterLinkChanges() = runTest {
345: fun updateTitleDiscardsResponseAfterSourceChanges() = runTest {
366: fun updateLibraryDiscardsResponseAfterSourceChanges() = runTest {
387: private fun updater(
397: override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, database) {
398: override suspend fun detail(url: String): RemoteDetail {
407: private fun database(
420: private fun manga(
435: private fun chapter(): DbChapter = DbChapter(
442: private fun source(id: Long = SOURCE_ID): DbSource = DbSource(
454: private fun remoteDetail(): RemoteDetail = RemoteDetail(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LibraryUpdaterServiceTest.kt) · SHA-256 `d6376f6d5aebef9fef428b36d84c75afbbee97f6708e608cfd58783dca503648`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.extensions.DatabaseFallbackRuntimeService
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.database.DbDownloadPolicy
import eu.friedcutlet.yokan.services.download.DownloadAutomation
import eu.friedcutlet.yokan.services.download.PolicyDownloads
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.runCurrent
import eu.friedcutlet.yokan.database.DbUpdateError
import eu.friedcutlet.yokan.database.DbSmartUpdateRules
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import kotlin.test.assertTrue

class LibraryUpdaterServiceTest {
    @Test
    fun automaticAdmissionCanDeferBeforeAnySourceRequestWithoutClearingErrors() = runTest {
        val db = database(manga(), listOf(chapter()))
        val errors = listOf(DbUpdateError(MANGA_ID, "Title", "Keep until checked"))
        db.updateSettings(db.settings().copy(updateErrors = errors))
        val started = CompletableDeferred<Unit>()
        val service = updater(db, started, CompletableDeferred(remoteDetail()))
        val progress = mutableListOf<LibraryUpdateProgress>()
        val result = service.updateLibrary(DbItemType.Manga, onProgress = { progress += it }, mayStartTitle = { false })
        assertTrue(result.deferred)
        assertEquals(0, result.checked)
        assertFalse(started.isCompleted)
        assertEquals(errors, db.settings().updateErrors)
        assertFalse(progress.single().isRunning)
    }

    @Test
    fun automaticAdmissionIsRecheckedAfterWaitingForTheServiceLock() = runTest {
        val db = database(manga(), listOf(chapter()))
        val started = CompletableDeferred<Unit>()
        val response = CompletableDeferred<RemoteDetail>()
        var calls = 0
        var allowed = true
        val service = updater(db, started, response, onDetail = { calls++ })
        val manual = async { service.updateLibrary(DbItemType.Manga) }
        started.await()
        val automatic = async { service.updateLibrary(DbItemType.Manga, mayStartTitle = { allowed }) }
        allowed = false
        response.complete(remoteDetail())
        assertEquals(1, manual.await().updated)
        assertTrue(automatic.await().deferred)
        assertEquals(1, calls)
    }

    @Test
    fun losingAdmissionBetweenTitlesPreservesUncheckedErrorsAndDoesNotStartAnotherRequest() = runTest {
        val db = database(manga(), listOf(chapter()))
        db.upsertManga(manga().copy(id = MANGA_ID + 1, link = "/second"))
        db.updateSettings(db.settings().copy(updateErrors = listOf(DbUpdateError(MANGA_ID, "Title", "Old"),
            DbUpdateError(MANGA_ID + 1, "Second", "Unchecked failure"))))
        var allowed = true
        var calls = 0
        val service = updater(db, CompletableDeferred(), CompletableDeferred(remoteDetail()), onDetail = { calls++; allowed = false })
        val result = service.updateLibrary(DbItemType.Manga, mayStartTitle = { allowed })
        assertTrue(result.deferred)
        assertEquals(1, result.checked)
        assertEquals(1, result.updated)
        assertEquals(1, calls)
        assertNull(db.manga(MANGA_ID + 1)?.lastUpdate)
        assertEquals(listOf(MANGA_ID + 1), db.settings().updateErrors.orEmpty().map { it.mangaId })
    }
    @Test
    fun emptyAndExplicitScopesDoNotExpandAndPreserveOtherErrorReports() = runTest {
        val db = database(manga(), listOf(chapter()))
        db.upsertManga(manga().copy(id = MANGA_ID + 1, link = "/other"))
        db.upsertManga(manga().copy(id = MANGA_ID + 2, itemType = DbItemType.Anime, link = "/anime"))
        db.updateSettings(db.settings().copy(updateErrors = listOf(
            DbUpdateError(MANGA_ID, "Title", "Old failure"),
            DbUpdateError(MANGA_ID + 1, "Other", "Keep other group"),
            DbUpdateError(MANGA_ID + 2, "Anime", "Keep other media"))))
        val started = CompletableDeferred<Unit>()
        val updater = updater(db, started, CompletableDeferred(remoteDetail()))
        assertEquals(0, updater.updateLibrary(DbItemType.Manga, titleIds = emptySet()).checked)
        assertFalse(started.isCompleted)
        assertEquals(3, db.settings().updateErrors.orEmpty().size)
        assertEquals(1, updater.updateLibrary(DbItemType.Manga, titleIds = setOf(MANGA_ID, MANGA_ID + 2, 999L)).checked)
        assertEquals(setOf(MANGA_ID + 1, MANGA_ID + 2), db.settings().updateErrors.orEmpty().map { it.mangaId }.toSet())
        assertNull(db.manga(MANGA_ID + 1)?.lastUpdate)
        assertNull(db.manga(MANGA_ID + 2)?.lastUpdate)
    }

    @Test
    fun scheduledAndManualLibraryEntryPointsUseTheSameRestrictionRules() = runTest {
        val db = database(manga(), listOf(chapter()))
        db.updateSettings(db.settings().copy(features = db.settings().features.copy(library = db.settings().features.library
            .withUpdateRules(DbItemType.Manga, DbSmartUpdateRules(onlyStarted = true)))))
        val started = CompletableDeferred<Unit>()
        val updater = updater(db, started, CompletableDeferred(remoteDetail()))
        assertEquals(0, updater.updateLibrary(DbItemType.Manga).checked)
        assertEquals(0, updater.updateLibrary(DbItemType.Manga, titleIds = setOf(MANGA_ID)).checked)
        assertFalse(started.isCompleted)
        db.upsertChapter(chapter().copy(lastPageRead = "3"))
        assertEquals(1, updater.updateLibrary(DbItemType.Manga).checked)
        // Explicit single-title refresh remains available even when library restrictions exclude it.
        db.upsertChapter(chapter())
        assertTrue(updater.updateTitle(MANGA_ID))
    }

    @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
    @Test
    fun serviceSerializesSchedulerAndSingleTitleCallsAndCancelledWaitersDoNotFetch() = runTest {
        val db = database(manga(), listOf(chapter()))
        val started = CompletableDeferred<Unit>()
        val response = CompletableDeferred<RemoteDetail>()
        var calls = 0
        val updater = updater(db, started, response, onDetail = { calls++ })
        val first = async { updater.updateLibrary(DbItemType.Manga) }
        started.await()
        val queued = async { updater.updateTitle(MANGA_ID) }
        runCurrent()
        assertFalse(queued.isCompleted)
        assertEquals(1, calls, "A queued caller must not open another extension request")
        queued.cancelAndJoin()
        db.updateSettings(db.settings().copy(incognitoMode = true))
        response.complete(remoteDetail())
        assertEquals(1, first.await().updated)
        assertTrue(db.settings().incognitoMode, "Final error publication must preserve concurrent settings")
        assertTrue(queued.isCancelled)
        assertEquals(1, calls)
        assertTrue(updater.updateTitle(MANGA_ID), "Cancellation of a waiting caller must leave the mutex usable")
        assertEquals(2, calls)
    }

    @Test
    fun discoveredChaptersAreHandedToQueueOnceAndExistingChaptersAreNotRequeued() = runTest {
        val database = database(manga = manga(), chapters = listOf(chapter()))
        val settings = database.settings()
        database.updateSettings(settings.copy(features = settings.features.copy(downloads = DbDownloadPolicy(autoDownloadNew = true))))
        val downloads = PolicyDownloads(database)
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        val detail = remoteDetail().copy(chapters = remoteDetail().chapters + RemoteChapter(title = "Chapter 2", url = "$ORIGINAL_LINK/chapter-2"))
        val updater = updater(database, CompletableDeferred(), CompletableDeferred(detail), automation)
        assertTrue(updater.updateTitle(MANGA_ID))
        val discovered = database.chapters(MANGA_ID).single { it.url.endsWith("chapter-2") }.id
        val fetchedAt = checkNotNull(database.chapter(discovered)).fetchedAt
        assertTrue(fetchedAt > 0)
        assertEquals(setOf(discovered), database.settings().features.downloads.pendingNewChapterIds)
        automation.reconcile()
        assertEquals(listOf(discovered), downloads.enqueued)
        assertEquals(fetchedAt, database.chapter(discovered)?.fetchedAt)
        assertTrue(updater.updateTitle(MANGA_ID))
        automation.reconcile()
        assertEquals(listOf(discovered), downloads.enqueued)
        assertEquals(fetchedAt, database.chapter(discovered)?.fetchedAt)
    }

    @Test
    fun defaultMeanCadenceSkipsRecentChecksAndAlwaysOverridesIt() = runTest {
        val now = eu.friedcutlet.yokan.util.nowMillis()
        val db = database(
            manga = manga().copy(lastUpdate = now),
            chapters = listOf(
                chapter().copy(dateUpload = "2026-01-01"),
                chapter().copy(id = CHAPTER_ID + 1, url = "/chapter-2", dateUpload = "2026-01-08"),
            ),
        )
        val updater = updater(db, CompletableDeferred(), CompletableDeferred(remoteDetail()))
        assertEquals(0, updater.updateLibrary(DbItemType.Manga).checked)
        db.upsertManga(checkNotNull(db.manga(MANGA_ID)).copy(smartUpdateDays = 0))
        assertEquals(1, updater.updateLibrary(DbItemType.Manga).checked)
        db.upsertManga(checkNotNull(db.manga(MANGA_ID)).copy(smartUpdateDays = null, lastUpdate = now - 8L * 86_400_000L))
        assertEquals(1, updater.updateLibrary(DbItemType.Manga).checked)
    }

    @Test
    fun updateTitlePreservesLocalEditsMadeWhileDetailLoads() = runTest {
        val database = database(
            manga = manga(),
            chapters = listOf(chapter()),
        )
        val started = CompletableDeferred<Unit>()
        val response = CompletableDeferred<RemoteDetail>()
        val updater = updater(database, started, response)

        val request = async { updater.updateTitle(MANGA_ID) }
        started.await()
        database.upsertManga(checkNotNull(database.manga(MANGA_ID)).copy(favorite = false))
        database.upsertChapter(
            checkNotNull(database.chapters(MANGA_ID).single()).copy(
                isRead = true,
                lastPageRead = "8",
                isBookmarked = true,
            ),
        )
        response.complete(remoteDetail())

        assertTrue(request.await())
        assertFalse(checkNotNull(database.manga(MANGA_ID)).favorite)
        assertEquals("Remote description", database.manga(MANGA_ID)?.description)
        val savedChapter = database.chapters(MANGA_ID).single()
        assertTrue(savedChapter.isRead)
        assertEquals("8", savedChapter.lastPageRead)
        assertTrue(savedChapter.isBookmarked)
    }

    @Test
    fun updateLibraryPreservesLocalEditsMadeWhileDetailLoads() = runTest {
        val database = database(
            manga = manga(),
            chapters = listOf(chapter()),
        )
        val started = CompletableDeferred<Unit>()
        val response = CompletableDeferred<RemoteDetail>()
        val updater = updater(database, started, response)

        val request = async { updater.updateLibrary(DbItemType.Manga) }
        started.await()
        database.upsertManga(checkNotNull(database.manga(MANGA_ID)).copy(favorite = false))
        database.upsertChapter(
            checkNotNull(database.chapters(MANGA_ID).single()).copy(
                isRead = true,
                lastPageRead = "8",
                isBookmarked = true,
            ),
        )
        response.complete(remoteDetail())

        val result = request.await()
        assertEquals(1, result.updated)
        assertFalse(checkNotNull(database.manga(MANGA_ID)).favorite)
        assertEquals("Remote description", database.manga(MANGA_ID)?.description)
        val savedChapter = database.chapters(MANGA_ID).single()
        assertTrue(savedChapter.isRead)
        assertEquals("8", savedChapter.lastPageRead)
        assertTrue(savedChapter.isBookmarked)
    }

    @Test
    fun updateTitleLeavesUnchangedChaptersUntouched() = runTest {
        val database = database(manga = manga(), chapters = listOf(chapter().copy(updatedAt = 1)))
        val updater = updater(database, CompletableDeferred(), CompletableDeferred(remoteDetail()))

        assertTrue(updater.updateTitle(MANGA_ID))

        assertEquals(1L, database.chapter(CHAPTER_ID)?.updatedAt, "an unchanged chapter is not rewritten")
        assertEquals("Remote description", database.manga(MANGA_ID)?.description)
    }

    @Test
    fun cancelledUpdateStopsWithoutRecordingFailures() = runTest {
        val database = database(manga = manga(), chapters = listOf(chapter()))
        val response = CompletableDeferred<RemoteDetail>().apply {
            completeExceptionally(CancellationException("update cancelled"))
        }
        val updater = updater(database, CompletableDeferred(), response)

        assertFailsWith<CancellationException> { updater.updateLibrary(DbItemType.Manga) }

        assertTrue(database.settings().updateErrors.isNullOrEmpty())
    }

    @Test
    fun updateTitleDoesNotResurrectDeletedTitle() = runTest {
        val database = database(manga())
        val started = CompletableDeferred<Unit>()
        val response = CompletableDeferred<RemoteDetail>()
        val updater = updater(database, started, response)

        val request = async { updater.updateTitle(MANGA_ID) }
        started.await()
        database.removeManga(MANGA_ID)
        response.complete(remoteDetail())

        assertFalse(request.await())
        assertNull(database.manga(MANGA_ID))
    }

    @Test
    fun updateLibraryDoesNotResurrectDeletedTitle() = runTest {
        val database = database(manga())
        val started = CompletableDeferred<Unit>()
        val response = CompletableDeferred<RemoteDetail>()
        val updater = updater(database, started, response)

        val request = async { updater.updateLibrary(DbItemType.Manga) }
        started.await()
        database.removeManga(MANGA_ID)
        response.complete(remoteDetail())

        val result = request.await()
        assertEquals(1, result.failed)
        assertNull(database.manga(MANGA_ID))
    }

    @Test
    fun updateTitleDiscardsResponseAfterLinkChanges() = runTest {
        val database = database(manga(description = "Local description"))
        val started = CompletableDeferred<Unit>()
        val response = CompletableDeferred<RemoteDetail>()
        val updater = updater(database, started, response)

        val request = async { updater.updateTitle(MANGA_ID) }
        started.await()
        database.upsertManga(checkNotNull(database.manga(MANGA_ID)).copy(link = CHANGED_LINK))
        response.complete(remoteDetail())

        assertFalse(request.await())
        assertEquals(CHANGED_LINK, database.manga(MANGA_ID)?.link)
        assertEquals("Local description", database.manga(MANGA_ID)?.description)
    }

    @Test
    fun updateLibraryDiscardsResponseAfterLinkChanges() = runTest {
        val database = database(manga(description = "Local description"))
        val started = CompletableDeferred<Unit>()
        val response = CompletableDeferred<RemoteDetail>()
        val updater = updater(database, started, response)

        val request = async { updater.updateLibrary(DbItemType.Manga) }
        started.await()
        database.upsertManga(checkNotNull(database.manga(MANGA_ID)).copy(link = CHANGED_LINK))
        response.complete(remoteDetail())

        val result = request.await()
        assertEquals(1, result.failed)
        assertEquals(CHANGED_LINK, database.manga(MANGA_ID)?.link)
        assertEquals("Local description", database.manga(MANGA_ID)?.description)
    }

    @Test
    fun updateTitleDiscardsResponseAfterSourceChanges() = runTest {
        val replacementSourceId = 200L
        val database = database(
            manga = manga(description = "Local description"),
            sources = listOf(source(), source(replacementSourceId)),
        )
        val started = CompletableDeferred<Unit>()
        val response = CompletableDeferred<RemoteDetail>()
        val updater = updater(database, started, response)

        val request = async { updater.updateTitle(MANGA_ID) }
        started.await()
        database.upsertManga(checkNotNull(database.manga(MANGA_ID)).copy(sourceId = replacementSourceId))
        response.complete(remoteDetail())

        assertFalse(request.await())
        assertEquals(replacementSourceId, database.manga(MANGA_ID)?.sourceId)
        assertEquals("Local description", database.manga(MANGA_ID)?.description)
    }

    @Test
    fun updateLibraryDiscardsResponseAfterSourceChanges() = runTest {
        val replacementSourceId = 200L
        val database = database(
            manga = manga(description = "Local description"),
            sources = listOf(source(), source(replacementSourceId)),
        )
        val started = CompletableDeferred<Unit>()
        val response = CompletableDeferred<RemoteDetail>()
        val updater = updater(database, started, response)

        val request = async { updater.updateLibrary(DbItemType.Manga) }
        started.await()
        database.upsertManga(checkNotNull(database.manga(MANGA_ID)).copy(sourceId = replacementSourceId))
        response.complete(remoteDetail())

        val result = request.await()
        assertEquals(1, result.failed)
        assertEquals(replacementSourceId, database.manga(MANGA_ID)?.sourceId)
        assertEquals("Local description", database.manga(MANGA_ID)?.description)
    }

    private fun updater(
        database: InMemoryYokanDatabase,
        started: CompletableDeferred<Unit>,
        response: CompletableDeferred<RemoteDetail>,
        automation: DownloadAutomation? = null,
        onDetail: () -> Unit = {},
    ): DefaultLibraryUpdaterService = DefaultLibraryUpdaterService(
        database = database,
        downloadAutomation = automation,
        runtimeFactory = object : ExtensionRuntimeFactory {
            override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, database) {
                override suspend fun detail(url: String): RemoteDetail {
                    onDetail()
                    started.complete(Unit)
                    return response.await()
                }
            }
        },
    )

    private fun database(
        manga: DbManga,
        chapters: List<DbChapter> = emptyList(),
        sources: List<DbSource> = listOf(source()),
    ): InMemoryYokanDatabase = InMemoryYokanDatabase(
        seedDatabaseSnapshot().copy(
            mangas = listOf(manga),
            chapters = chapters,
            sources = sources,
            settings = DbSettings(),
        ),
    )

    private fun manga(
        link: String = ORIGINAL_LINK,
        sourceId: Long = SOURCE_ID,
        favorite: Boolean = true,
        description: String? = null,
    ): DbManga = DbManga(
        id = MANGA_ID,
        name = "Title",
        link = link,
        description = description,
        sourceId = sourceId,
        itemType = DbItemType.Manga,
        favorite = favorite,
    )

    private fun chapter(): DbChapter = DbChapter(
        id = CHAPTER_ID,
        mangaId = MANGA_ID,
        name = "Chapter 1",
        url = "$ORIGINAL_LINK/chapter-1",
    )

    private fun source(id: Long = SOURCE_ID): DbSource = DbSource(
        id = id,
        name = "Source $id",
        baseUrl = "https://example.com",
        lang = "en",
        itemType = DbItemType.Manga,
        typeSource = "single",
        sourceCodeLanguage = DbSourceCodeLanguage.JavaScript,
        isAdded = true,
        isActive = true,
    )

    private fun remoteDetail(): RemoteDetail = RemoteDetail(
        title = "Title",
        url = ORIGINAL_LINK,
        description = "Remote description",
        chapters = listOf(
            RemoteChapter(
                title = "Chapter 1",
                url = "$ORIGINAL_LINK/chapter-1",
            ),
        ),
    )

    private companion object {
        const val MANGA_ID = 1L
        const val CHAPTER_ID = 2L
        const val SOURCE_ID = 100L
        const val ORIGINAL_LINK = "https://example.com/title"
        const val CHANGED_LINK = "https://example.com/changed-title"
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/RedVideoFixtures.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/RedVideoFixtures.kt) · test / fixture · 66 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
11: internal object RedVideoFixtures {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/RedVideoFixtures.kt) · SHA-256 `bd594475999a3ca2e541607afbe5d414d3ec059219e74d888335f1a12a2e252e`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi

/**
 * One-second, 64x48, solid red videos generated with
 * `ffmpeg -f lavfi -i color=c=red:s=64x48:r=5:d=1` (H.264 in MP4 and Matroska; VP8 in WebM).
 */
@OptIn(ExperimentalEncodingApi::class)
internal object RedVideoFixtures {
    val mp4: ByteArray get() = Base64.decode(MP4)
    val mkv: ByteArray get() = Base64.decode(MKV)
    val webm: ByteArray get() = Base64.decode(WEBM)

    private const val MP4 =
        "AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAN4bW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAAA+gAAQAAAQAAAAAAAAAAAAAA" +
        "AAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAqJ0cmFrAAAAXHRraGQAAAAD" +
        "AAAAAAAAAAAAAAABAAAAAAAAA+gAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAEAAAAAwAAAAAAAk" +
        "ZWR0cwAAABxlbHN0AAAAAAAAAAEAAAPoAAAQAAABAAAAAAIabWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAAoAAAAKABVxAAAAAAALWhkbHIAAAAA" +
        "AAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABxW1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAA" +
        "AQAAAAx1cmwgAAAAAQAAAYVzdGJsAAAAwXN0c2QAAAAAAAAAAQAAALFhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAEAAMABIAAAASAAAAAAA" +
        "AAABFUxhdmM2Mi4yOC4xMDIgbGlieDI2NAAAAAAAAAAAAAAAGP//AAAAN2F2Y0MBZAAK/+EAGWdkAAqscgREewEQAAADABAAAAMAoPEiWEYBAAdo" +
        "6EOPEyEw/fj4AAAAABBwYXNwAAAAAQAAAAEAAAAUYnRydAAAAAAAABjIAAAAAAAAABhzdHRzAAAAAAAAAAEAAAAFAAAIAAAAABRzdHNzAAAAAAAA" +
        "AAEAAAABAAAAOGN0dHMAAAAAAAAABQAAAAEAABAAAAAAAQAAKAAAAAABAAAQAAAAAAEAAAAAAAAAAQAACAAAAAAcc3RzYwAAAAAAAAABAAAAAQAA" +
        "AAUAAAABAAAAKHN0c3oAAAAAAAAAAAAAAAUAAALfAAAAEAAAAA4AAAAOAAAADgAAABRzdGNvAAAAAAAAAAEAAAOoAAAAYnVkdGEAAABabWV0YQAA" +
        "AAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAtaWxzdAAAACWpdG9vAAAAHWRhdGEAAAABAAAAAExhdmY2Mi4xMi4xMDIAAAAI" +
        "ZnJlZQAAAyFtZGF0AAACsQYF//+t3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE2NSByMzIyMiBiMzU2MDVhIC0gSC4yNjQvTVBFRy00IEFW" +
        "QyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAyNSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEg" +
        "cmVmPTE2IGRlYmxvY2s9MTotMzotMyBhbmFseXNlPTB4MzoweDEzMyBtZT11bWggc3VibWU9MTAgcHN5PTEgcHN5X3JkPTIuMDA6MC43MCBtaXhl" +
        "ZF9yZWY9MSBtZV9yYW5nZT0yNCBjaHJvbWFfbWU9MSB0cmVsbGlzPTIgOHg4ZGN0PTEgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0x" +
        "IGNocm9tYV9xcF9vZmZzZXQ9LTQgdGhyZWFkcz0xIGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEg" +
        "aW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9OCBiX3B5cmFtaWQ9MiBiX2FkYXB0PTIgYl9i" +
        "aWFzPTAgZGlyZWN0PTMgd2VpZ2h0Yj0xIG9wZW5fZ29wPTAgd2VpZ2h0cD0yIGtleWludD0yNTAga2V5aW50X21pbj01IHNjZW5lY3V0PTQwIGlu" +
        "dHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NjAgcmM9Y3JmIG1idHJlZT0xIGNyZj0yMy4wIHFjb21wPTAuNjAgcXBtaW49MCBxcG1heD02OSBx" +
        "cHN0ZXA9NCBpcF9yYXRpbz0xLjQwIGFxPTE6MS4yMACAAAAAJmWIgQACuc/+7M9+BTZo5i/D8UVzjnx145jTpoV06HSGEhWxQC43AAAADEGaCI2I" +
        "JZz//rU5WAAAAApBnhBHEE85/wL3AAAACgGeGCaIJZz/A34AAAAKAZ4YbUglnP8Dfw=="
    private const val MKV =
        "GkXfo6NChoEBQveBAULygQRC84EIQoKIbWF0cm9za2FCh4EEQoWBAhhTgGcBAAAAAAAFfBFNm3TAv4QdavBFTbuLU6uEFUmpZlOsgaFNu4tTq4QW" +
        "VK5rU6yB8U27jFOrhBJUw2dTrIIBkE27jFOrhBxTu2tTrIIFYOwBAAAAAAAAUwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
        "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFUmpZsu/hC1UsxEq17GDD0JATYCNTGF2ZjYyLjEyLjEwMldBjUxh" +
        "dmY2Mi4xMi4xMDJzpJA1AVw/a+q0EqebaRmxLGbJRImIQI9AAAAAAAAWVK5rQJm/hDcjXViuAQAAAAAAAIrXgQFzxYgTiq8O3aUKf5yBACK1nIN1" +
        "bmSIgQCGj1ZfTVBFRzQvSVNPL0FWQ4OBASPjg4QL68IA4JCwgUC6gTCagQJVsIRVuYEBVe6BAOwBAAAAAAAAAgAAY6KvAWQACv/hABlnZAAKrHIE" +
        "RHsBEAAAAwAQAAADAKDxIlhGAQAHaOhDjxMhMP34+AASVMNnQIO/hOcAK3Zzc6BjwIBnyJpFo4dFTkNPREVSRIeNTGF2ZjYyLjEyLjEwMnNz12PA" +
        "i2PFiBOKrw7dpQp/Z8iiRaOHRU5DT0RFUkSHlUxhdmM2Mi4yOC4xMDIgbGlieDI2NGfIoUWjiERVUkFUSU9ORIeTMDA6MDA6MDEuMDAwMDAwMDAw" +
        "AB9DtnVDQb+E3GGC4+eBAKNC44EAAIAAAAKxBgX//63cRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY1IHIzMjIyIGIzNTYwNWEgLSBILjI2" +
        "NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDI1IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9u" +
        "czogY2FiYWM9MSByZWY9MTYgZGVibG9jaz0xOi0zOi0zIGFuYWx5c2U9MHgzOjB4MTMzIG1lPXVtaCBzdWJtZT0xMCBwc3k9MSBwc3lfcmQ9Mi4w" +
        "MDowLjcwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTI0IGNocm9tYV9tZT0xIHRyZWxsaXM9MiA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBm" +
        "YXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tNCB0aHJlYWRzPTEgbG9va2FoZWFkX3RocmVhZHM9MSBzbGljZWRfdGhyZWFkcz0wIG5yPTAg" +
        "ZGVjaW1hdGU9MSBpbnRlcmxhY2VkPTAgYmx1cmF5X2NvbXBhdD0wIGNvbnN0cmFpbmVkX2ludHJhPTAgYmZyYW1lcz04IGJfcHlyYW1pZD0yIGJf" +
        "YWRhcHQ9MiBiX2JpYXM9MCBkaXJlY3Q9MyB3ZWlnaHRiPTEgb3Blbl9nb3A9MCB3ZWlnaHRwPTIga2V5aW50PTI1MCBrZXlpbnRfbWluPTUgc2Nl" +
        "bmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD02MCByYz1jcmYgbWJ0cmVlPTEgY3JmPTIzLjAgcWNvbXA9MC42MCBxcG1pbj0w" +
        "IHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjIwAIAAAAAmZYiBAAK5z/7sz34FNmjmL8PxRXOOfHXjmNOmhXTodIYSFbFA" +
        "LjejlIEDIAAAAAAMQZoIjYglnP/+tTlYo5KBAZAAAAAACkGeEEcQTzn/AvejkoEAyAAAAAAKAZ4YJoglnP8DfqOSgQJYAAAAAAoBnhhtSCWc/wN/" +
        "HFO7a5e/hDbJIVK7j7OBALeK94EB8YICGfCBCQ=="
    private const val WEBM =
        "GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAJpEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHYTbuM" +
        "U6uEElTDZ1OsggElTbuMU6uEHFO7a1OsggJT7AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
        "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmsirXsYMPQkBNgI1MYXZmNjIuMTIuMTAyV0GNTGF2ZjYyLjEyLjEw" +
        "MkSJiECPQAAAAAAAFlSua8iuAQAAAAAAAD/XgQFzxYhwT8UwOSZ3FpyBACK1nIN1bmSIgQCGhVZfVlA4g4EBI+ODhAvrwgDgkLCBQLqBMJqBAlWw" +
        "hFW5gQESVMNn/HNzoGPAgGfImkWjh0VOQ09ERVJEh41MYXZmNjIuMTIuMTAyc3PWY8CLY8WIcE/FMDkmdxZnyKFFo4dFTkNPREVSRIeUTGF2YzYy" +
        "LjI4LjEwMiBsaWJ2cHhnyKFFo4hEVVJBVElPTkSHkzAwOjAwOjAxLjAwMDAwMDAwMAAfQ7Z1QKfngQCjwoEAAICQAwCdASpAADAAAEcIhYWIhYSI" +
        "AgICdaoD+AP6Agc7eeLPMx5eAP79bvP/45k3MMT/jm3/8WE8DijI//FRAKOWgQDIANEBAAEQEAAYABhYL/QACIwAAKOWgQGQANEBAAEQEAAYABhY" +
        "L/QACIwAAKOWgQJYANEBAAEQEAAYABhYL/QACIwAAKOWgQMgANEBAAEQEAAYABhYL/QACIwAABxTu2uRu4+zgQC3iveBAfGCAabwgQM="
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/SelectiveDataClearServiceTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/SelectiveDataClearServiceTest.kt) · test / fixture · 137 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
15: class SelectiveDataClearServiceTest {
17: fun clearingMangaRemovesItsDatabaseDependentsAndKeepsOtherMediaUntouched() {
40: fun replacementOutboxContainsTitleAndKeyedSettingsTombstones() {
52: fun mismatchedExplicitHistoryTypeRejectsUnsafeCascade() {
61: fun clearingSourcesRemovesOnlyTheirPreferencesAndCache() {
79: fun activePersistedDownloadRefusesClearWithoutChangingSnapshot() = runTest {
90: fun successfulClearRemovesRowsWithoutCallingPhysicalFileDeletion() = runTest {
99: private fun mixedSnapshot(): YokanDatabaseSnapshot {
126: private object NoDownloads : DownloadService {
127: override suspend fun initialize(poolSize: Int) = Unit
128: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
129: override fun cancel(taskId: String) = Unit
130: override fun pause(taskId: String) = Unit
131: override fun resume(taskId: String) = Unit
132: override fun retry(taskId: String) = false
133: override fun storageLocation(taskId: String): String? = null
134: override fun deleteArtifacts(taskId: String) = error("Selective clear must not delete media files")
135: override fun activeDownloads(): List<DownloadProgress> = emptyList()
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/SelectiveDataClearServiceTest.kt) · SHA-256 `fcbd8e19b59214e9ae5583b008c139ff2f77a47d20ca1f962a3ca6bc1bc2797e`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.database.sync.SyncPaths
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.download.DownloadProgress
import eu.friedcutlet.yokan.services.download.DownloadRequest
import eu.friedcutlet.yokan.services.download.DownloadService
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue

class SelectiveDataClearServiceTest {
    @Test
    fun clearingMangaRemovesItsDatabaseDependentsAndKeepsOtherMediaUntouched() {
        val snapshot = mixedSnapshot()
        val plan = planLibraryClear(snapshot, setOf(DbItemType.Manga))

        assertNotNull(plan.after)
        assertTrue(plan.error == null)
        assertEquals(listOf(2L, 3L), plan.after.mangas.map { it.id })
        assertEquals(listOf(20L, 30L), plan.after.chapters.map { it.id })
        assertEquals(listOf(2L, 3L), plan.after.histories.map { it.id })
        assertEquals(listOf(2L, 3L), plan.after.updates.map { it.id })
        assertEquals(listOf(2L, 3L), plan.after.tracks.map { it.id })
        assertEquals(listOf(2L, 3L), plan.after.trackSearches.map { it.libraryId })
        assertEquals(listOf(2L, 3L), plan.after.downloads.map { it.id })
        assertEquals(listOf(20L, 30L), plan.after.pageCache.mapNotNull { it.chapterId })
        assertEquals(snapshot.categories, plan.after.categories)
        assertEquals(snapshot.sources, plan.after.sources)
        assertEquals(snapshot.mangas.drop(1), plan.after.mangas)
        assertEquals(snapshot.chapters.drop(1), plan.after.chapters)
        assertEquals(listOf(2L, 3L), plan.after.settings.titleMetadata?.map { it.mangaId })
        assertEquals(listOf(20L, 30L), plan.after.settings.chapterPageIndexList?.mapNotNull { it.chapterId })
    }

    @Test
    fun replacementOutboxContainsTitleAndKeyedSettingsTombstones() {
        val before = mixedSnapshot().copy(
            syncPreferences = listOf(DbSyncPreference(syncOn = true, authToken = "token", server = "https://hub", hubEpoch = 1, hubBootstrapComplete = true)),
        )
        val after = planLibraryClear(before, setOf(DbItemType.Manga)).after
        val outbox = SyncPaths.outboxForReplacement(before, after)

        assertTrue(outbox.any { it.kind == SyncPaths.KIND_MANGA && it.id == 1L && it.path == SyncPaths.DELETED })
        assertTrue(outbox.any { it.kind == SyncPaths.KIND_SETTINGS && it.path == "titleMetadata.1" && it.value == null })
    }

    @Test
    fun mismatchedExplicitHistoryTypeRejectsUnsafeCascade() {
        val snapshot = mixedSnapshot().copy(histories = listOf(DbHistory(id = 1, mangaId = 1, chapterId = 10, itemType = DbItemType.Anime)))
        val plan = planLibraryClear(snapshot, setOf(DbItemType.Manga))

        assertNotNull(plan.error)
        assertEquals(snapshot, plan.after)
    }

    @Test
    fun clearingSourcesRemovesOnlyTheirPreferencesAndCache() {
        val snapshot = mixedSnapshot().copy(
            settings = DbSettings(sourcePreferences = listOf(
                DbSourcePreference(1, "a", "1"),
                DbSourcePreference(2, "b", "2"),
            )),
            pageCache = listOf(DbChapterPageUrls(chapterId = 10, sourceId = 1), DbChapterPageUrls(chapterId = 20, sourceId = 2)),
        )

        val after = planSourceClear(snapshot, setOf(DbItemType.Manga)).after

        assertEquals(listOf(2L), after.sources.map { it.id })
        assertEquals(listOf(DbSourcePreference(2, "b", "2")), after.settings.sourcePreferences)
        assertEquals(listOf(20L), after.pageCache.mapNotNull { it.chapterId })
        assertEquals(snapshot.mangas, after.mangas)
    }

    @Test
    fun activePersistedDownloadRefusesClearWithoutChangingSnapshot() = runTest {
        val snapshot = mixedSnapshot().copy(downloads = listOf(DbDownload(id = 1, chapterId = 10, isDownload = false, isStartDownload = true)))
        val database = InMemoryYokanDatabase(snapshot)
        val result = SelectiveDataClearService(database, NoDownloads).clearLibrary(setOf(ItemType.Manga))

        assertTrue(!result.cleared)
        assertNotNull(result.error)
        assertEquals(snapshot, database.snapshot())
    }

    @Test
    fun successfulClearRemovesRowsWithoutCallingPhysicalFileDeletion() = runTest {
        val database = InMemoryYokanDatabase(mixedSnapshot())
        val result = SelectiveDataClearService(database, NoDownloads).clearLibrary(setOf(ItemType.Manga))

        assertTrue(result.cleared)
        assertEquals(1, result.titlesRemoved)
        assertEquals(listOf(2L, 3L), database.snapshot().mangas.map { it.id })
    }

    private fun mixedSnapshot(): YokanDatabaseSnapshot {
        val manga = DbManga(id = 1, itemType = DbItemType.Manga, favorite = false, isLocalArchive = true)
        val anime = DbManga(id = 2, itemType = DbItemType.Anime, favorite = true)
        val novel = DbManga(id = 3, itemType = DbItemType.Novel)
        return YokanDatabaseSnapshot(
            settings = DbSettings(
                titleMetadata = listOf(DbTitleMetadata(1), DbTitleMetadata(2), DbTitleMetadata(3)),
                chapterPageIndexList = listOf(DbChapterPageIndex(10, 1), DbChapterPageIndex(20, 2), DbChapterPageIndex(30, 3)),
                downloadQueueOrder = listOf(1, 2, 3),
            ),
            mangas = listOf(manga, anime, novel),
            chapters = listOf(DbChapter(id = 10, mangaId = 1), DbChapter(id = 20, mangaId = 2), DbChapter(id = 30, mangaId = 3)),
            categories = listOf(DbCategory(id = 1, name = "Manga", forItemType = DbItemType.Manga)),
            sources = listOf(DbSource(id = 1, itemType = DbItemType.Manga), DbSource(id = 2, itemType = DbItemType.Anime)),
            histories = listOf(1, 2, 3).map { DbHistory(id = it.toLong(), mangaId = it.toLong(), chapterId = it * 10L, itemType = DbItemType.entries[it - 1]) },
            updates = listOf(1, 2, 3).map { DbUpdate(id = it.toLong(), mangaId = it.toLong(), chapterId = it * 10L) },
            downloads = listOf(1, 2, 3).map { DbDownload(id = it.toLong(), chapterId = it * 10L, isStartDownload = false) },
            tracks = listOf(1, 2, 3).map { DbTrack(id = it.toLong(), mangaId = it.toLong(), itemType = DbItemType.entries[it - 1], status = DbTrackStatus.Reading) },
            trackPreferences = emptyList(),
            trackSearches = listOf(1, 2, 3).map { DbTrackSearch(id = it.toLong(), libraryId = it.toLong()) },
            syncPreferences = emptyList(),
            changedParts = emptyList(),
            customButtons = emptyList(),
            pageCache = listOf(10L, 20L, 30L).map { DbChapterPageUrls(chapterId = it) },
        )
    }

    private object NoDownloads : DownloadService {
        override suspend fun initialize(poolSize: Int) = Unit
        override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
        override fun cancel(taskId: String) = Unit
        override fun pause(taskId: String) = Unit
        override fun resume(taskId: String) = Unit
        override fun retry(taskId: String) = false
        override fun storageLocation(taskId: String): String? = null
        override fun deleteArtifacts(taskId: String) = error("Selective clear must not delete media files")
        override fun activeDownloads(): List<DownloadProgress> = emptyList()
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/SmartUpdateRulesTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/SmartUpdateRulesTest.kt) · test / fixture · 65 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
6: class SmartUpdateRulesTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/SmartUpdateRulesTest.kt) · SHA-256 `cb020c7af46bd96c9bc5f9a3040321343514be9a4abccd8697dac81538a92e24`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.*
import kotlin.test.*

class SmartUpdateRulesTest {
    private val now = 1_800_000_000_000L
    private val title = DbManga(id = 1, lastUpdate = now, smartUpdateDays = 7)
    private val chapter = DbChapter(id = 1, mangaId = 1)

    @Test fun defaultsPreserveManualAndAutomaticCadenceAndZeroOverride() {
        val rules = DbSmartUpdateRules()
        assertFalse(rules.permits(title, emptyList(), now))
        assertTrue(rules.permits(title.copy(lastUpdate = now - 7L * 86_400_000), emptyList(), now))
        assertTrue(rules.permits(title.copy(smartUpdateDays = 0), emptyList(), now))
        val releases = listOf(chapter.copy(dateUpload = "2026-01-01"), chapter.copy(id = 2, dateUpload = "2026-01-08"))
        assertFalse(rules.permits(title.copy(smartUpdateDays = null), releases, now))
        assertTrue(rules.permits(title.copy(smartUpdateDays = null), emptyList(), now))
    }

    @Test fun disablingExpectedPeriodBypassesCadenceWithoutBypassingOtherRules() {
        assertTrue(DbSmartUpdateRules(respectExpectedReleasePeriod = false).permits(title, listOf(chapter), now))
        assertFalse(DbSmartUpdateRules(onlyCaughtUp = true, respectExpectedReleasePeriod = false).permits(title, listOf(chapter), now))
    }

    @Test fun completionRestrictionIsOptIn() {
        val completed = title.copy(status = DbStatus.Completed, smartUpdateDays = 0)
        assertTrue(DbSmartUpdateRules().permits(completed, emptyList(), now))
        assertFalse(DbSmartUpdateRules(skipCompleted = true).permits(completed, emptyList(), now))
    }

    @Test fun caughtUpRequiresAllKnownReleasesReadButKeepsEmptyTitlesEligible() {
        val rules = DbSmartUpdateRules(onlyCaughtUp = true, respectExpectedReleasePeriod = false)
        assertFalse(rules.permits(title, listOf(chapter.copy(lastPageRead = "2")), now))
        assertTrue(rules.permits(title, listOf(chapter.copy(isRead = true)), now))
        assertTrue(rules.permits(title, emptyList(), now))
    }

    @Test fun startedAllowsFinitePositiveProgressOrCompletedReleasesAndKeepsEmptyTitlesEligible() {
        val rules = DbSmartUpdateRules(onlyStarted = true, respectExpectedReleasePeriod = false)
        assertTrue(rules.permits(title, emptyList(), now))
        assertTrue(rules.permits(title, listOf(chapter.copy(lastPageRead = "0.5")), now))
        assertTrue(rules.permits(title, listOf(chapter.copy(isRead = true)), now))
        for (progress in listOf("", "0", "-1", "NaN", "Infinity", "invalid"))
            assertFalse(rules.permits(title, listOf(chapter.copy(lastPageRead = progress)), now))
    }

    @Test fun combinedRestrictionsNeverOverrideOneAnother() {
        val rules = DbSmartUpdateRules(skipCompleted = true, onlyCaughtUp = true, onlyStarted = true, respectExpectedReleasePeriod = false)
        assertTrue(rules.permits(title, listOf(chapter.copy(isRead = true)), now))
        assertFalse(rules.permits(title, listOf(chapter.copy(isRead = true), chapter.copy(id = 2)), now))
        assertFalse(rules.permits(title.copy(status = DbStatus.Completed), listOf(chapter.copy(isRead = true)), now))
    }

    @Test fun rulesAndGroupScopePersistIndependentlyForEachMediaType() {
        val rules = DbSmartUpdateRules(skipCompleted = true, onlyStarted = true)
        val prefs = DbLibraryPreferences().withUpdateRules(DbItemType.Anime, rules)
            .withUpdateGroupMode(DbItemType.Anime, DbGroupUpdateMode.CurrentExceptUngrouped)
        assertEquals(DbSmartUpdateRules(), prefs.updateRules(DbItemType.Manga))
        assertEquals(DbGroupUpdateMode.Global, prefs.updateGroupMode(DbItemType.Manga))
        assertEquals(prefs, DatabaseJson.decodeFromString(DbLibraryPreferences.serializer(), DatabaseJson.encodeToString(DbLibraryPreferences.serializer(), prefs)))
        assertEquals(DbLibraryPreferences(), prefs.withUpdateRules(DbItemType.Anime, DbSmartUpdateRules())
            .withUpdateGroupMode(DbItemType.Anime, DbGroupUpdateMode.Global))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/TorrentUtilsTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/TorrentUtilsTest.kt) · test / fixture · 145 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
10: class TorrentUtilsTest {
13: fun normalizeInfoHashNormalizes40CharHexHashToLowercase() {
22: fun normalizeInfoHashConverts32CharBase32HashTo40CharHex() {
31: fun normalizeInfoHashLeavesNonStandardStringsUntouched() {
40: fun normalizeInfoHashSupports64CharV2Multihash() {
49: fun extractInfoHashFromUrlExtractsFromStreamQueryParam() {
56: fun extractInfoHashFromMagnetExtractsHexAndBase32() {
65: fun extractMagnetDisplayNameExtractsAndDecodesName() {
77: fun extractMagnetFallbacksExtractsAndNormalizesUrls() {
89: fun parseMagnetExtractsCompleteMetadata() {
99: fun importTorrentExtractsMagnetDisplayNameAndDeduplicatesByInfoHash() = runTest {
105: override fun writeBytes(path: String, bytes: ByteArray) = Unit
106: override fun readBytes(path: String) = ByteArray(0)
107: override fun canonicalPath(path: String) = path
108: override fun exists(path: String) = false
109: override fun deleteRecursively(path: String) = true
110: override fun directorySize(path: String) = 0L
111: override fun openLocation(path: String) = false
112: override fun listLocalEntries(root: String) = emptyList<eu.friedcutlet.yokan.services.files.LocalEntry>()
113: override fun listFiles(root: String) = emptyList<eu.friedcutlet.yokan.services.files.LocalFileEntry>()
116: override fun listPages(archivePath: String) = emptyList<eu.friedcutlet.yokan.database.DbPageUrl>()
117: override fun listEpubChapters(archivePath: String) = emptyList<eu.friedcutlet.yokan.services.files.LocalEpubChapter>()
118: override fun readEpubChapter(archivePath: String, index: Int) = ""
119: override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null
120: override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean) = null
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/TorrentUtilsTest.kt) · SHA-256 `80e07b5a119cdf6f59394aeaac39a6f79698ba0d9409a74d0ad9e739774f9704`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue

class TorrentUtilsTest {

    @Test
    fun normalizeInfoHashNormalizes40CharHexHashToLowercase() {
        val hexUpper = "4C811CA573A16A00F742512F58900609B2DE4190"
        val hexLower = "4c811ca573a16a00f742512f58900609b2de4190"
        assertEquals(hexLower, TorrentUtils.normalizeInfoHash(hexUpper))
        assertEquals(hexLower, TorrentUtils.normalizeInfoHash(hexLower))
        assertEquals(hexLower, TorrentUtils.normalizeInfoHash("  $hexUpper  "))
    }

    @Test
    fun normalizeInfoHashConverts32CharBase32HashTo40CharHex() {
        val base32 = "JSCBJJTTSFWQB52CKEXVRQAGBGZNYQMQ"
        val hex = TorrentUtils.normalizeInfoHash(base32)
        assertEquals(40, hex.length)
        assertTrue(Regex("^[0-9a-f]{40}$").matches(hex))
        assertEquals("4c8414a673916d00f742512f58c00609b2dc4190", hex)
    }

    @Test
    fun normalizeInfoHashLeavesNonStandardStringsUntouched() {
        assertEquals("", TorrentUtils.normalizeInfoHash(""))
        assertEquals("short", TorrentUtils.normalizeInfoHash("short"))
        // 32 chars with invalid base32 characters ('8', '9')
        val invalidBase32 = "JSCBJJTTSFWQB52CKEXVRQAGBGZNYQM8"
        assertEquals(invalidBase32, TorrentUtils.normalizeInfoHash(invalidBase32))
    }

    @Test
    fun normalizeInfoHashSupports64CharV2Multihash() {
        val v2Upper = "1220A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F61234"
        val expected = v2Upper.lowercase()
        // 64-char hex
        val sha256Upper = "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4E5F61234"
        assertEquals(sha256Upper.lowercase(), TorrentUtils.normalizeInfoHash(sha256Upper))
    }

    @Test
    fun extractInfoHashFromUrlExtractsFromStreamQueryParam() {
        val url = "http://127.0.0.1:5000/torrent/stream?infohash=4c811ca573a16a00f742512f58900609b2de4190&file=0"
        val infoHash = TorrentUtils.extractInfoHashFromUrl(url)
        assertEquals("4c811ca573a16a00f742512f58900609b2de4190", infoHash)
    }

    @Test
    fun extractInfoHashFromMagnetExtractsHexAndBase32() {
        val magnetHex = "magnet:?xt=urn:btih:4c811ca573a16a00f742512f58900609b2de4190&dn=Test"
        assertEquals("4c811ca573a16a00f742512f58900609b2de4190", TorrentUtils.extractInfoHashFromMagnet(magnetHex))

        val magnetBase32 = "magnet:?xt=urn:btih:JSCBJJTTSFWQB52CKEXVRQAGBGZNYQMQ&dn=Test"
        assertEquals("4c8414a673916d00f742512f58c00609b2dc4190", TorrentUtils.extractInfoHashFromMagnet(magnetBase32))
    }

    @Test
    fun extractMagnetDisplayNameExtractsAndDecodesName() {
        val magnetWithPlus = "magnet:?xt=urn:btih:4c811ca573a16a00f742512f58900609b2de4190&dn=Sousou+no+Frieren+-+01"
        assertEquals("Sousou no Frieren - 01", TorrentUtils.extractMagnetDisplayName(magnetWithPlus))

        val magnetWithPercent = "magnet:?xt=urn:btih:4c811ca573a16a00f742512f58900609b2de4190&dn=Dungeon%20Meshi%20S01E01"
        assertEquals("Dungeon Meshi S01E01", TorrentUtils.extractMagnetDisplayName(magnetWithPercent))

        val magnetNoDn = "magnet:?xt=urn:btih:4c811ca573a16a00f742512f58900609b2de4190"
        assertNull(TorrentUtils.extractMagnetDisplayName(magnetNoDn))
    }

    @Test
    fun extractMagnetFallbacksExtractsAndNormalizesUrls() {
        val magnet = "magnet:?xt=urn:btih:4c811ca573a16a00f742512f58900609b2de4190" +
            "&xs=http://example.com/source1.torrent" +
            "&as=https://example.com/source2.torrent" +
            "&ws=http://example.com/webseed" +
            "&ws=ftp://invalid.com/file" // ignored: not http/https
        val (sources, webseeds) = TorrentUtils.extractMagnetFallbacks(magnet)
        assertEquals(listOf("http://example.com/source1.torrent", "https://example.com/source2.torrent"), sources)
        assertEquals(listOf("http://example.com/webseed"), webseeds)
    }

    @Test
    fun parseMagnetExtractsCompleteMetadata() {
        val magnet = "magnet:?xt=urn:btih:JSCBJJTTSFWQB52CKEXVRQAGBGZNYQMQ&dn=Frieren+Episode+1&tr=http%3A%2F%2Ftracker.example.com%3A80%2Fannounce&ws=http://webseed.example.com"
        val info = TorrentUtils.parseMagnet(magnet)
        assertEquals("4c8414a673916d00f742512f58c00609b2dc4190", info.infoHash)
        assertEquals("Frieren Episode 1", info.displayName)
        assertEquals(listOf("http://tracker.example.com:80/announce"), info.trackers)
        assertEquals(listOf("http://webseed.example.com"), info.webseeds)
    }

    @Test
    fun importTorrentExtractsMagnetDisplayNameAndDeduplicatesByInfoHash() = runTest {
        val db = eu.friedcutlet.yokan.database.InMemoryYokanDatabase()
        val dummyFiles = object : eu.friedcutlet.yokan.services.files.LocalFileService {
            override val downloadRoot = "/downloads"
            override val backupRoot = "/backups"
            override val cacheRoot = "/cache"
            override fun writeBytes(path: String, bytes: ByteArray) = Unit
            override fun readBytes(path: String) = ByteArray(0)
            override fun canonicalPath(path: String) = path
            override fun exists(path: String) = false
            override fun deleteRecursively(path: String) = true
            override fun directorySize(path: String) = 0L
            override fun openLocation(path: String) = false
            override fun listLocalEntries(root: String) = emptyList<eu.friedcutlet.yokan.services.files.LocalEntry>()
            override fun listFiles(root: String) = emptyList<eu.friedcutlet.yokan.services.files.LocalFileEntry>()
        }
        val dummyArchives = object : eu.friedcutlet.yokan.services.files.LocalArchiveService {
            override fun listPages(archivePath: String) = emptyList<eu.friedcutlet.yokan.database.DbPageUrl>()
            override fun listEpubChapters(archivePath: String) = emptyList<eu.friedcutlet.yokan.services.files.LocalEpubChapter>()
            override fun readEpubChapter(archivePath: String, index: Int) = ""
            override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null
            override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean) = null
        }
        val localLibrary = eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService(db, dummyFiles, dummyArchives)

        val magnet1 = "magnet:?xt=urn:btih:4c811ca573a16a00f742512f58900609b2de4190&dn=Sousou+no+Frieren+-+01"
        val id1 = localLibrary.importTorrent(magnet1)
        assertNotNull(id1)

        val saved1 = db.manga(id1)
        assertNotNull(saved1)
        assertEquals("Sousou no Frieren - 01", saved1.name)

        // Importing same magnet with different query params or uppercase hash deduplicates by infohash
        val magnet2 = "magnet:?xt=urn:btih:4C811CA573A16A00F742512F58900609B2DE4190&tr=http%3A%2F%2Ftracker.example.com"
        val id2 = localLibrary.importTorrent(magnet2)
        assertEquals(id1, id2)

        // Importing magnet without dn uses infohash prefix
        val magnet3 = "magnet:?xt=urn:btih:JSCBJJTTSFWQB52CKEXVRQAGBGZNYQMQ"
        val id3 = localLibrary.importTorrent(magnet3)
        assertNotNull(id3)
        val saved3 = db.manga(id3)
        assertNotNull(saved3)
        assertEquals("Torrent (4c8414a6)", saved3.name)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/UpdateErrorsTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/UpdateErrorsTest.kt) · test / fixture · 134 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
23: class UpdateErrorsTest {
27: fun updateErrorSerializesAndDeserializes() {
35: fun dbSettingsPreservesUpdateErrorsList() {
51: fun preserveDeviceLocalSettingsRetainsUpdateErrors() {
64: fun libraryUpdaterRecordsFailuresAndPersistsToSettings() = runTest {
102: override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, database) {
103: override suspend fun detail(url: String): RemoteDetail {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/UpdateErrorsTest.kt) · SHA-256 `3499ad30fde8cf82571fc86269853e188e64bcfcaeabf08229a777a214a4a0c2`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.DbUpdateError
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.database.sync.preserveDeviceLocalSettings
import eu.friedcutlet.yokan.services.extensions.DatabaseFallbackRuntimeService
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class UpdateErrorsTest {
    private val json = Json { ignoreUnknownKeys = true; prettyPrint = false }

    @Test
    fun updateErrorSerializesAndDeserializes() {
        val error = DbUpdateError(mangaId = 123L, name = "One Piece", error = "HTTP 502 Bad Gateway")
        val encoded = json.encodeToString(DbUpdateError.serializer(), error)
        val decoded = json.decodeFromString(DbUpdateError.serializer(), encoded)
        assertEquals(error, decoded)
    }

    @Test
    fun dbSettingsPreservesUpdateErrorsList() {
        val settings = DbSettings(
            updateErrors = listOf(
                DbUpdateError(mangaId = 1L, name = "Naruto", error = "Cloudflare blocked"),
                DbUpdateError(mangaId = 2L, name = "Bleach", error = "Timeout 60s"),
            ),
        )
        val encoded = json.encodeToString(DbSettings.serializer(), settings)
        val decoded = json.decodeFromString(DbSettings.serializer(), encoded)
        assertEquals(2, decoded.updateErrors?.size)
        assertEquals("Naruto", decoded.updateErrors?.get(0)?.name)
        assertEquals("Cloudflare blocked", decoded.updateErrors?.get(0)?.error)
        assertEquals("Bleach", decoded.updateErrors?.get(1)?.name)
    }

    @Test
    fun preserveDeviceLocalSettingsRetainsUpdateErrors() {
        val current = DbSettings(
            updateErrors = listOf(DbUpdateError(mangaId = 99L, name = "Berserk", error = "Host not found")),
        )
        val incoming = DbSettings(
            updateErrors = listOf(DbUpdateError(mangaId = 1L, name = "Remote", error = "Remote err")),
        )
        val preserved = preserveDeviceLocalSettings(current, incoming)
        assertEquals(1, preserved.updateErrors?.size)
        assertEquals(99L, preserved.updateErrors?.first()?.mangaId)
    }

    @Test
    fun libraryUpdaterRecordsFailuresAndPersistsToSettings() = runTest {
        val testSource = DbSource(
            id = 100L,
            name = "Test Source",
            baseUrl = "https://example.com",
            lang = "en",
            itemType = DbItemType.Manga,
            typeSource = "single",
            sourceCodeLanguage = DbSourceCodeLanguage.JavaScript,
            isAdded = true,
            isActive = true,
        )
        val successManga = DbManga(
            id = 10L,
            name = "Succeeding Manga",
            link = "https://example.com/manga/success",
            sourceId = 100L,
            itemType = DbItemType.Manga,
            favorite = true,
        )
        val failingManga = DbManga(
            id = 20L,
            name = "Failing Manga",
            link = "https://example.com/manga/failing",
            sourceId = 100L,
            itemType = DbItemType.Manga,
            favorite = true,
        )

        val database = InMemoryYokanDatabase(
            seedDatabaseSnapshot().copy(
                sources = listOf(testSource),
                mangas = listOf(successManga, failingManga),
                settings = DbSettings(),
            ),
        )

        val fakeFactory = object : ExtensionRuntimeFactory {
            override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, database) {
                override suspend fun detail(url: String): RemoteDetail {
                    if (url.contains("failing")) {
                        throw RuntimeException("Cloudflare challenge unresolved")
                    }
                    return RemoteDetail(
                        title = "Succeeding Manga",
                        url = url,
                        chapters = listOf(
                            RemoteChapter(title = "Chapter 1", url = "$url/ch1", dateUpload = "2026-09-05"),
                        ),
                    )
                }
            }
        }

        val updater = DefaultLibraryUpdaterService(database, fakeFactory)
        val result = updater.updateLibrary(DbItemType.Manga)

        assertEquals(2, result.checked)
        assertEquals(1, result.updated)
        assertEquals(1, result.failed)
        assertEquals(1, result.errors.size)
        assertEquals(20L, result.errors[0].mangaId)
        assertEquals("Failing Manga", result.errors[0].name)
        assertTrue(result.errors[0].error.contains("Cloudflare challenge unresolved"))

        val storedErrors = database.settings().updateErrors
        assertEquals(1, storedErrors?.size)
        assertEquals(20L, storedErrors?.get(0)?.mangaId)
        assertEquals("Failing Manga", storedErrors?.get(0)?.name)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/LibrarySearchTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/LibrarySearchTest.kt) · test / fixture · 114 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
15: class LibrarySearchTest {
111: private fun matches(query: String, entry: Manga = manga) =
113: private fun date(value: String) = LocalDate.parse(value).atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds()
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/LibrarySearchTest.kt) · SHA-256 `10351958ea404256a35b7bb2aaaf5057762dbbced452d329fb7a392672b22260`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui

import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Status
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn

class LibrarySearchTest {
    private val manga = Manga(
        id = 42, name = "One Piece", alternativeTitles = listOf("Pirate King"), link = "/one-piece",
        description = "A voyage across the grand line", author = "Eiichiro Oda", artist = "O'Neil",
        status = Status.Ongoing, itemType = ItemType.Manga, source = "My Source", lang = "en",
        genres = listOf("Action", "Science Fiction", "Mystery, Drama"), privateNote = "Read with family",
        dateAddedMillis = date("2026-10-01") + 50_000, lastUpdateMillis = date("2026-10-10"),
        sourceId = 123, smartUpdateDays = 7,
    )
    private val index = LibraryIndex(chaptersByManga = mapOf(42L to listOf(
        Chapter(1, 42, "Chapter 1", "/1", isRead = true, dateUpload = "2026-10-01"),
        Chapter(2, 42, "Chapter 2", "/2", dateUpload = "2026-10-08"),
        Chapter(3, 42, "Chapter 3", "/3", dateUpload = "2026-10-15"),
    )))

    @Test fun existingPhraseCommaAndGenreSearchesKeepTheirMeaning() {
        assertTrue(matches("one piece"))
        assertTrue(matches("other title, one piece"))
        assertFalse(matches("piece one"))
        assertTrue(matches("pirate king"))
        assertTrue(matches("genre:science fiction"))
        assertTrue(matches("genre:Mystery, Drama"))
        assertFalse(matches("genre:Act"))
        assertTrue(matches(""))
        assertTrue(matches(" , "))
    }

    @Test fun licensedAndUpcomingTitlesRemainDistinctFromUnknownInStatusSearch() {
        assertTrue(matches("status:licensed", manga.copy(status = Status.Licensed)))
        assertTrue(matches("status:upcoming", manga.copy(status = Status.Upcoming)))
        assertFalse(matches("status:unknown", manga.copy(status = Status.Licensed)))
        assertFalse(matches("status:unknown", manga.copy(status = Status.Upcoming)))
        assertFalse(matches("status:licensed", manga.copy(status = Status.Upcoming)))
    }

    @Test fun booleanPrecedenceGroupingAndNegationCombineFields() {
        assertTrue(matches("title:missing OR author:oda AND -tag:romance"))
        assertFalse(matches("(title:missing OR author:oda) AND tag:romance"))
        assertTrue(matches("NOT (title:missing || genre:romance) && unread>=2"))
        assertTrue(matches("--title:piece"))
        assertFalse(matches("title:piece -author:oda"))
        assertTrue(matches("genre:Action unread>1"))
        assertTrue(matches("genre:Action -title:missing"))
        assertFalse(matches("title:missing, author:oda unread=0"))
    }

    @Test fun quotedValuesAliasesAndPrivateNotesUseTheCorrectFields() {
        for (query in listOf("title:\"pirate king\"", "author:'Eiichiro Oda'", "artist:O'Neil",
            "desc:\"grand line\"", "note:family", "src:'My Source'", "lang:EN", "srcid:123",
            "tag:\"science fiction\"", "status:ongoing", "type:manga")) assertTrue(matches(query), query)
        assertFalse(matches("lang:e"))
        assertFalse(matches("source_id:12"))
        assertFalse(matches("artist:Oda"))
        assertFalse(matches("family")) // Notes remain explicit; no surprise disclosure in ordinary searches.
        assertTrue(matches("\"genre:action\"", manga.copy(name = "Guide to genre:action")))
        assertTrue(matches("title:\"He said \\\"hello\\\"\"", manga.copy(name = "He said \"hello\"")))
    }

    @Test fun countsUseTheSelectedChapterIndexAndDatesUseUtcCalendarDays() {
        for (query in listOf("total=3", "read=1", "unread=2", "id>=42", "id<=42", "total>2", "read<2",
            "added=2026-10-01", "added<2026-10-02", "fi=7", "nu=2026-10-17")) assertTrue(matches(query), query)
        assertFalse(matches("added>2026-10-01"))
        assertFalse(matches("read>1"))
        assertFalse(matches("nu<2026-10-17"))
        assertTrue(matches("fi=7 nu=2026-10-17", manga.copy(smartUpdateDays = null)))
        assertTrue(matches("fi=0 nu=2026-10-10", manga.copy(smartUpdateDays = 0)))
        assertFalse(matches("nu<2026-10-20", manga.copy(lastUpdateMillis = 0)))
        assertFalse(LibrarySearchQuery("unread>0").matches(manga))
    }

    @Test fun malformedAndOversizedExpressionsNeverApplyAPartialFilter() {
        for (query in listOf("title:piece OR", "(title:piece", "title:piece)", "title:piece AND AND author:oda",
            "title:\"piece", "title:", "NOT unread=nope", "-added=2026-02-30", "-source_id:nope",
            "id>99999999999999999999999999999", "(".repeat(30) + "title:piece" + ")".repeat(30),
            List(260) { "title:piece" }.joinToString(" OR "), "title:piece " + "x".repeat(4096))) {
            assertFalse(matches(query), query.take(80))
        }
        assertTrue(matches("unknown:value", manga.copy(name = "unknown:value")))
        assertTrue(matches("One Piece (Color)", manga.copy(name = "One Piece (Color)")))
    }

    @Test fun scheduleQueriesKeepTheUpdaterCadenceWhenReleaseFiltersHideDates() {
        val selected = LibraryIndex(chaptersByManga = mapOf(42L to index.chapters(42).take(1)))
        val query = LibrarySearchQuery("total=1 fi=7 nu=2026-10-17", selected,
            date("2026-10-15"), scheduleIndex = index)
        assertTrue(query.matches(manga.copy(smartUpdateDays = null)))
    }

    @Test fun allMediaTypesUseTheSameParserAndNoMutableGlobalContext() {
        val query = LibrarySearchQuery("author:oda total=3", index)
        ItemType.entries.forEach { assertTrue(query.matches(manga.copy(itemType = it))) }
        assertFalse(query.matches(manga.copy(id = 43)))
        assertTrue(query.matches(manga))
        assertFalse(LibrarySearchQuery("total=3").matches(manga))
    }

    private fun matches(query: String, entry: Manga = manga) =
        LibrarySearchQuery(query, index, date("2026-10-15")).matches(entry)
    private fun date(value: String) = LocalDate.parse(value).atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds()
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryBadgeSummaryTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryBadgeSummaryTest.kt) · test / fixture · 44 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
9: class LibraryBadgeSummaryTest {
11: fun countsUnreadChaptersAndEveryCompletedDownloadButIgnoresMissingOrIncompleteIds() {
37: private fun chapter(id: Long, isRead: Boolean) = Chapter(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryBadgeSummaryTest.kt) · SHA-256 `ec94d86a4b7c2cd0ea0c2498ce4853adf211970d405ec205b9d690c80ff33769`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.data.buildCompletedDownloadCountsByChapterId
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.domain.Chapter
import kotlin.test.Test
import kotlin.test.assertEquals

class LibraryBadgeSummaryTest {
    @Test
    fun countsUnreadChaptersAndEveryCompletedDownloadButIgnoresMissingOrIncompleteIds() {
        val downloads = listOf(
            DbDownload(id = 1, chapterId = 11, isDownload = true),
            DbDownload(id = 2, chapterId = 11, isDownload = true),
            DbDownload(id = 3, chapterId = 12, isDownload = false),
            DbDownload(id = 4, chapterId = null, isDownload = true),
            DbDownload(id = 5, chapterId = 99, isDownload = true),
        )
        val summaries = buildLibraryBadgeSummaries(
            chaptersByManga = mapOf(
                7L to listOf(
                    chapter(11, isRead = false),
                    chapter(12, isRead = true),
                ),
                8L to emptyList(),
            ),
            completedDownloadCountsByChapterId = buildCompletedDownloadCountsByChapterId(downloads),
        )

        assertEquals(LibraryBadgeSummary(unreadCount = 1, downloadedCount = 2, totalCount = 2, readCount = 1), summaries[7L])
        assertEquals(0.5f, summaries[7L]?.progress)
        assertEquals(LibraryBadgeSummary(), summaries[8L])
        assertEquals(0f, summaries[8L]?.progress)
        assertEquals(mapOf(11L to 2, 99L to 1), buildCompletedDownloadCountsByChapterId(downloads))
    }

    private fun chapter(id: Long, isRead: Boolean) = Chapter(
        id = id,
        mangaId = 7,
        name = "Chapter $id",
        url = "/chapter/$id",
        isRead = isRead,
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryCategoryPreferencesTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryCategoryPreferencesTest.kt) · test / fixture · 46 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
7: class LibraryCategoryPreferencesTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryCategoryPreferencesTest.kt) · SHA-256 `4da5496f035e4844ec1e7043b96548be4b6ecc48ecd3de90712b6ece9c70f17b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.ItemType
import kotlin.test.*

class LibraryCategoryPreferencesTest {
    @Test fun scopedDisplayControlsStartFromTheEffectiveCategoryAndPreserveGlobalAndOtherMediaSettings() {
        val before = DbSettings().withLibraryGridSize(ItemType.Manga, 3).withLibraryDisplay(ItemType.Manga, language = false)
        val scoped = before.withCategoryLibraryPreferences(ItemType.Manga, 42, DbCategoryLibraryPreferences(
            sort = DbSortLibraryManga(index = 3),
            display = before.libraryDisplay(ItemType.Manga).copy(gridSize = 5, language = true).categoryPreferences(),
        ))
        val changed = scoped.withCategoryLibraryDisplay(ItemType.Manga, 42) { it.withLibraryGridSize(ItemType.Manga, 7) }
        assertEquals(before.libraryDisplay(ItemType.Manga), changed.libraryDisplay(ItemType.Manga))
        val category = changed.features.library.categories(DbItemType.Manga).getValue(42)
        assertEquals(7, changed.libraryDisplay(ItemType.Manga).forCategory(category).gridSize)
        assertTrue(changed.libraryDisplay(ItemType.Manga).forCategory(category).language)
        assertEquals(DbSortLibraryManga(index = 3), category.sort)
        assertTrue(changed.features.library.categories(DbItemType.Anime).isEmpty())
        assertEquals(before.libraryDisplay(ItemType.Anime), changed.libraryDisplay(ItemType.Anime))
    }

    @Test fun categorySortDirectionAndResetDoNotMutateGlobalSort() {
        val initial = DbSettings().withCategoryLibraryPreferences(ItemType.Anime, 5, DbCategoryLibraryPreferences())
        val selected = initial.withCategoryLibrarySortSelected(ItemType.Anime, 5, 4)
        val reversed = selected.withCategoryLibrarySortSelected(ItemType.Anime, 5, 4)
        assertEquals(initial.librarySort(ItemType.Anime), reversed.librarySort(ItemType.Anime))
        assertEquals(DbSortLibraryManga(index = 4, reverse = true), reversed.features.library.categories(DbItemType.Anime)[5]?.sort)
        val reset = reversed.withCategoryLibraryPreferences(ItemType.Anime, 5, null)
        assertTrue(reset.features.library.categories(DbItemType.Anime).isEmpty())
        assertEquals(initial.libraryDisplay(ItemType.Anime), reset.libraryDisplay(ItemType.Anime).forCategory(null))
    }

    @Test fun serializedPreferencesKeepMediaGroupingAndCategoryScopesSeparate() {
        val settings = DbSettings().withLibraryGrouping(ItemType.Manga, DbLibraryGrouping.Tags)
            .withLibraryGrouping(ItemType.Novel, DbLibraryGrouping.Ungrouped)
            .withCategoryLibraryPreferences(ItemType.Anime, 5, DbCategoryLibraryPreferences(sort = DbSortLibraryManga(index = 6)))
        val restored = DatabaseJson.decodeFromString(DbSettings.serializer(), DatabaseJson.encodeToString(DbSettings.serializer(), settings))
        assertEquals(settings, restored)
        assertEquals(DbLibraryGrouping.Categories, restored.features.library.grouping(DbItemType.Anime))
        assertEquals(DbLibraryGrouping.Tags, restored.features.library.grouping(DbItemType.Manga))
        assertTrue(restored.features.library.categories(DbItemType.Manga).isEmpty())
        assertEquals(DbLibraryGrouping.Categories, DatabaseJson.decodeFromString(DbSettings.serializer(), "{}").features.library.grouping(DbItemType.Manga))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryContentTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryContentTest.kt) · test / fixture · 150 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
15: class LibraryContentTest {
17: fun trackerMetadataRefreshKeepsReleaseSelectionAndExposesNewStatus() {
28: fun searchAndSortReuseReleaseSelectionButOfflinePolicyInvalidatesIt() {
39: fun advancedSearchCountsUseSelectedReleasesAndIgnoreFiltersReusesTheSameMatches() {
53: fun unreadFiltersSortAndBadgesUseSelectedReleasesAndAggregatedProgress() {
87: fun filterAndSortRunBeforeTheCategorySplitAndTabsFollowTheUnfilteredLibrary() {
106: fun downloadedOnlyHidesTitlesWithoutDownloadsButIgnoringFiltersSearchStillFindsThem() {
121: private fun query(
128: private fun manga(id: Long, name: String, categories: List<Long> = emptyList()) = Manga(
143: private fun chapter(id: Long, mangaId: Long, isRead: Boolean) = Chapter(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryContentTest.kt) · SHA-256 `69a55ce04dfa03542b1d403b419295646c127bb36b08d1f394537a546750c3da`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.database.DbSortLibraryManga
import eu.friedcutlet.yokan.database.DbChapterReleasePreference
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Status
import kotlin.test.Test
import kotlin.test.assertEquals

class LibraryContentTest {
    @Test
    fun trackerMetadataRefreshKeepsReleaseSelectionAndExposesNewStatus() {
        val selector = LibraryReleaseSelector()
        val selected = selector.select(library, index, query())
        val changed = LibraryIndex(index.chaptersByManga, index.completedDownloadCountsByChapterId, setOf(1),
            mapOf(1L to listOf(eu.friedcutlet.yokan.data.LibraryTrack(1, eu.friedcutlet.yokan.database.DbTrackStatus.Completed, 7))))
        val after = selector.select(library, changed, query())
        kotlin.test.assertSame(selected.chaptersByManga, after.chaptersByManga)
        assertEquals(changed.tracksByManga, after.tracksByManga)
    }

    @Test
    fun searchAndSortReuseReleaseSelectionButOfflinePolicyInvalidatesIt() {
        val selector = LibraryReleaseSelector()
        val selected = selector.select(library, index, query())
        kotlin.test.assertSame(selected, selector.select(library, index, query(search = "alpha")))
        kotlin.test.assertSame(selected, selector.select(library, index, query(sort = DbSortLibraryManga(index = 3))))
        val offline = selector.select(library, index, query(downloadedOnly = true))
        kotlin.test.assertNotSame(selected, offline)
        assertEquals(listOf(beta), libraryContent(library, categories, index, query(downloadedOnly = true), offline).items(null))
    }

    @Test
    fun advancedSearchCountsUseSelectedReleasesAndIgnoreFiltersReusesTheSameMatches() {
        val rows = listOf(chapter(11, 1, true).copy(name = "Chapter 1", scanlator = "Old"),
            chapter(12, 1, false).copy(name = "Chapter 1", scanlator = "Preferred"))
        val raw = LibraryIndex(chaptersByManga = mapOf(1L to rows, 3L to index.chapters(3)))
        val advanced = query(search = "unread=0 AND title:alpha", downloadedOnly = true).copy(
            releasePreferences = listOf(DbChapterReleasePreference(scanlatorPriority = listOf("Preferred"), skipDuplicateReleases = true)),
        )
        val content = libraryContent(listOf(alpha, gamma), categories, raw, advanced)
        assertEquals(emptyList(), content.items(null))
        assertEquals(listOf(alpha), content.searchMatches)
        assertEquals(listOf(alpha), libraryContent(listOf(alpha, gamma), categories, raw, advanced.copy(downloadedOnly = false)).items(null))
    }

    @Test
    fun unreadFiltersSortAndBadgesUseSelectedReleasesAndAggregatedProgress() {
        val rows = listOf(chapter(11, 1, true).copy(name = "Chapter 1", scanlator = "Old"),
            chapter(12, 1, false).copy(name = "Chapter 1", scanlator = "Preferred"))
        val releaseIndex = LibraryIndex(chaptersByManga = mapOf(1L to rows, 3L to index.chapters(3)))
        val db = DbSettings(chapterReleasePreferences = listOf(DbChapterReleasePreference(
            scanlatorPriority = listOf("Preferred"), skipDuplicateReleases = true)))
        val selectedQuery = query(filters = noFilters.copy(unread = 1)).copy(releasePreferences = db.chapterReleasePreferences)
        assertEquals(listOf(gamma), libraryContent(listOf(alpha, gamma), categories, releaseIndex, selectedQuery).items(null))
        val badges = buildLibraryBadgeSummaries(releaseIndex.chaptersByManga, emptyMap(), mapOf(1L to alpha.name, 3L to gamma.name), db)
        assertEquals(LibraryBadgeSummary(unreadCount = 0, totalCount = 1, readCount = 1), badges[1])
        assertEquals(3, badges[3]?.unreadCount)
        assertEquals(listOf(alpha, gamma), libraryContent(listOf(gamma, alpha), categories, releaseIndex,
            selectedQuery.copy(filters = noFilters, sort = DbSortLibraryManga(index = 3))).items(null))
    }

    private val alpha = manga(1, "Alpha", categories = listOf(10))
    private val beta = manga(2, "Beta")
    private val gamma = manga(3, "Gamma", categories = listOf(10, 20))
    private val delta = manga(4, "Delta", categories = listOf(20)).copy(alternativeTitles = listOf("Delta", "Zeta"))
    private val library = listOf(alpha, beta, gamma, delta)
    private val categories = listOf(
        Category(id = 10, name = "Reading", forItemType = ItemType.Manga, position = 0),
        Category(id = 20, name = "Hidden", forItemType = ItemType.Manga, position = 1, hidden = true),
    )
    private val index = LibraryIndex(
        chaptersByManga = mapOf(
            1L to listOf(chapter(11, 1, isRead = false), chapter(12, 1, isRead = true)),
            2L to listOf(chapter(21, 2, isRead = true)),
            3L to listOf(chapter(31, 3, isRead = false), chapter(32, 3, isRead = false), chapter(33, 3, isRead = false)),
        ),
        completedDownloadCountsByChapterId = mapOf(21L to 1),
    )

    @Test
    fun filterAndSortRunBeforeTheCategorySplitAndTabsFollowTheUnfilteredLibrary() {
        val content = libraryContent(
            library = library,
            categories = categories,
            index = index,
            query = query(filters = noFilters.copy(unread = 1), sort = DbSortLibraryManga(reverse = true, index = 3)),
        )

        assertEquals(listOf(gamma, alpha), content.items(null))
        assertEquals(listOf(gamma, alpha), content.items(10))
        assertEquals(listOf(gamma), content.items(20))
        assertEquals(emptyList(), content.items(UncategorizedCategoryId))
        assertEquals(
            listOf(LibraryCategoryTab(UncategorizedCategoryId, "", 0), LibraryCategoryTab(10, "Reading", 2)),
            content.tabs,
        )
    }

    @Test
    fun downloadedOnlyHidesTitlesWithoutDownloadsButIgnoringFiltersSearchStillFindsThem() {
        val content = libraryContent(
            library = library,
            categories = categories,
            index = index,
            query = query(search = "zeta", downloadedOnly = true),
        )

        assertEquals(emptyList(), content.items(null))
        assertEquals(listOf(delta), content.searchMatches)
        assertEquals(listOf(beta), libraryContent(library, categories, index, query(downloadedOnly = true)).items(null))
    }

    private val noFilters = LibraryFilterTypes(downloaded = 0, unread = 0, started = 0, bookmarked = 0, completed = 0, tracking = 0)

    private fun query(
        search: String = "",
        filters: LibraryFilterTypes = noFilters,
        sort: DbSortLibraryManga = DbSortLibraryManga(),
        downloadedOnly: Boolean = false,
    ) = LibraryQuery(search = search, filters = filters, sort = sort, downloadedOnly = downloadedOnly)

    private fun manga(id: Long, name: String, categories: List<Long> = emptyList()) = Manga(
        id = id,
        name = name,
        link = "/manga/$id",
        description = "",
        status = Status.Ongoing,
        itemType = ItemType.Manga,
        favorite = true,
        source = "Source",
        lang = "en",
        dateAddedMillis = id,
        lastUpdateMillis = id,
        categories = categories,
    )

    private fun chapter(id: Long, mangaId: Long, isRead: Boolean) = Chapter(
        id = id,
        mangaId = mangaId,
        name = "Chapter $id",
        url = "/chapter/$id",
        isRead = isRead,
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGroupingTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGroupingTest.kt) · test / fixture · 110 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
9: class LibraryGroupingTest {
16: private fun query(group: DbLibraryGrouping, search: String = "") = LibraryQuery(search, noFilters, DbSortLibraryManga(), false, grouping = group)
108: private fun manga(id: Long, name: String) = Manga(id, name, link = "/$id", description = "", status = Status.Ongoing,
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGroupingTest.kt) · SHA-256 `75c7d2f48a2c5042a9450be937784312ee33fd673c53cbf3561ddff56fc00b42`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.data.LibraryTrack
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.*
import kotlin.test.*

class LibraryGroupingTest {
    private val alpha = manga(1, "Alpha").copy(sourceId = 10, genres = listOf(" Action ", "ACTION", "Drama"), categories = listOf(100))
    private val beta = manga(2, "Beta").copy(sourceId = 20, genres = listOf("action"), categories = listOf(100, 200))
    private val gamma = manga(3, "Gamma").copy(sourceId = 10, status = Status.Completed)
    private val titles = listOf(gamma, beta, alpha)
    private val categories = listOf(Category(100, "One", ItemType.Manga, 0), Category(200, "Hidden", ItemType.Manga, 1, hidden = true))
    private val noFilters = LibraryFilterTypes(0, 0, 0, 0, 0, 0)
    private fun query(group: DbLibraryGrouping, search: String = "") = LibraryQuery(search, noFilters, DbSortLibraryManga(), false, grouping = group)

    @Test fun sourceIdentitySeparatesEqualNamesAndKeepsEachTitleOnce() {
        val content = libraryContent(titles, categories, LibraryIndex.Empty, query(DbLibraryGrouping.Source))
        assertEquals(2, content.tabs.size)
        assertEquals(setOf(listOf(1L, 3L), listOf(2L)), content.tabs.map { content.items(it.id).map(Manga::id) }.toSet())
        assertTrue(content.tabs.all { it.id < -1 && it.id != AllLibraryTabId })
        assertEquals(categories, content.categories)
        assertEquals(listOf(100L), alpha.categories)
        assertEquals(listOf(100L, 200L), beta.categories)
    }

    @Test fun tagsNormalizeWhitespaceAndCaseWithoutDuplicateMemberships() {
        val content = libraryContent(titles, categories, LibraryIndex.Empty, query(DbLibraryGrouping.Tags))
        val action = content.tabs.single { it.name.equals("action", true) }
        assertEquals(2, action.count)
        assertEquals(listOf(1L, 2L), content.items(action.id).map(Manga::id))
        assertEquals(1, content.tabs.single { it.label == LibraryTabLabel.Untagged }.count)
        assertEquals(1, content.tabs.single { it.name == "Drama" }.count)
        val searched = libraryContent(titles.reversed(), categories, LibraryIndex.Empty, query(DbLibraryGrouping.Tags, "Gamma"))
        assertEquals(content.tabs.map { it.id }.toSet(), searched.tabs.map { it.id }.toSet())
        assertEquals(0, searched.tabs.single { it.id == action.id }.count)
    }

    @Test fun trackerStatusUsesEveryProviderAndKeepsUntrackedEntriesVisible() {
        val index = LibraryIndex(tracksByManga = mapOf(
            1L to listOf(LibraryTrack(1, DbTrackStatus.Reading, 5), LibraryTrack(2, DbTrackStatus.Completed, 7), LibraryTrack(3, DbTrackStatus.Reading, 0)),
            2L to listOf(LibraryTrack(1, DbTrackStatus.Completed, null)),
        ))
        val content = libraryContent(titles, categories, index, query(DbLibraryGrouping.TrackerStatus))
        assertEquals(3, content.tabs.size)
        assertEquals(listOf(1L), content.items(content.tabs.single { it.name == "Reading" }.id).map(Manga::id))
        assertEquals(listOf(1L, 2L), content.items(content.tabs.single { it.name == "Completed" }.id).map(Manga::id))
        assertEquals(listOf(3L), content.items(content.tabs.single { it.label == LibraryTabLabel.Untracked }.id).map(Manga::id))
    }

    @Test fun statusAndUngroupedWorkForEveryMediaTypeWithoutChangingCategories() {
        ItemType.entries.forEach { type ->
            val library = titles.map { it.copy(itemType = type) }
            val status = libraryContent(library, categories, LibraryIndex.Empty, query(DbLibraryGrouping.Status))
            assertEquals(setOf(1, 2), status.tabs.map { it.count }.toSet())
            val ungrouped = libraryContent(library, categories, LibraryIndex.Empty, query(DbLibraryGrouping.Ungrouped))
            assertTrue(ungrouped.tabs.isEmpty())
            assertTrue(ungrouped.items(100).isEmpty())
            assertEquals(listOf(1L, 2L, 3L), ungrouped.items(null).map(Manga::id))
            assertEquals(library.map { it.categories }, ungrouped.library.map { it.categories })
        }
    }

    @Test fun licensedUpcomingAndUnknownHaveSeparateStableStatusGroups() {
        val library = listOf(alpha.copy(status = Status.Licensed), beta.copy(status = Status.Upcoming), gamma.copy(status = Status.Unknown))
        val content = libraryContent(library, categories, LibraryIndex.Empty, query(DbLibraryGrouping.Status))
        assertEquals(setOf("Licensed", "Upcoming", "Unknown"), content.tabs.map { it.name }.toSet())
        for (entry in library) {
            val group = content.tabs.single { it.name == entry.status.label }
            assertEquals(listOf(entry.id), content.items(group.id).map { it.id })
        }
        val reordered = libraryContent(library.reversed(), categories, LibraryIndex.Empty, query(DbLibraryGrouping.Status))
        assertEquals(content.tabs.associate { it.name to it.id }, reordered.tabs.associate { it.name to it.id })
    }

    @Test fun missingSourcesAndTagsNeverDropTitles() {
        val library = listOf(alpha.copy(sourceId = null, source = "", genres = emptyList()), beta.copy(sourceId = null, lang = "fr"))
        val source = libraryContent(library, categories, LibraryIndex.Empty, query(DbLibraryGrouping.Source))
        assertEquals(1, source.tabs.single { it.label == LibraryTabLabel.UnknownSource }.count)
        assertEquals(2, source.tabs.sumOf { source.items(it.id).size })
        assertEquals(1, libraryContent(library, categories, LibraryIndex.Empty, query(DbLibraryGrouping.Tags)).tabs.single { it.label == LibraryTabLabel.Untagged }.count)
    }

    @Test fun idsAreStableAndCollisionsNeverOverwriteManualOrOtherAutomaticGroups() {
        val keys = linkedSetOf("b", "a", "c")
        val reserved = setOf(-2L, -3L, AllLibraryTabId)
        val ids = libraryGroupIds(keys, DbLibraryGrouping.Tags, reserved) { 2 }
        assertEquals(ids, libraryGroupIds(keys.reversed().toSet(), DbLibraryGrouping.Tags, reserved) { 2 })
        assertEquals(3, ids.values.toSet().size)
        assertTrue(ids.values.none { it in reserved || it == UncategorizedCategoryId || it == 0L })
        assertEquals(libraryGroupIds(keys, DbLibraryGrouping.Tags, emptySet()),
            libraryGroupIds(keys.reversed().toSet(), DbLibraryGrouping.Tags, emptySet()))
    }

    @Test fun categorySortOverridesDoNotChangeOtherCategoriesOrAutomaticViews() {
        val prefs = mapOf(100L to DbCategoryLibraryPreferences(sort = DbSortLibraryManga(reverse = true)))
        val q = query(DbLibraryGrouping.Categories).copy(categoryPreferences = prefs)
        val content = libraryContent(titles, categories, LibraryIndex.Empty, q)
        assertEquals(listOf(1L, 2L, 3L), content.items(null).map(Manga::id))
        assertEquals(listOf(2L, 1L), content.items(100).map(Manga::id))
        assertEquals(listOf(2L), content.items(200).map(Manga::id))
        assertEquals(listOf(100L), content.tabs.filter { it.id >= 0 }.map { it.id })
        val automatic = libraryContent(titles, categories, LibraryIndex.Empty, q.copy(grouping = DbLibraryGrouping.Tags))
        assertEquals(listOf(1L, 2L), automatic.items(automatic.tabs.single { it.name.equals("action", true) }.id).map(Manga::id))
    }

    private fun manga(id: Long, name: String) = Manga(id, name, link = "/$id", description = "", status = Status.Ongoing,
        itemType = ItemType.Manga, favorite = true, source = "Same", lang = "en", dateAddedMillis = 0, lastUpdateMillis = 0)
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibrarySortAndFiltersTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibrarySortAndFiltersTest.kt) · test / fixture · 117 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
10: class LibrarySortAndFiltersTest {
12: private fun query(sort: Int = 0, reverse: Boolean = false, filters: LibraryFilterTypes = off, seed: Long = 0) =
20: fun ids(filters: Map<Int, Int>) = libraryContent(titles, emptyList(), index,
115: private fun track(provider: Int, score: Int? = null) = LibraryTrack(provider, DbTrackStatus.Reading, score)
116: private fun chapter(id: Long, title: Long, at: Long) = Chapter(id, title, "Chapter $id", "/$id", fetchedAt = at)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibrarySortAndFiltersTest.kt) · SHA-256 `d0e7c2256d88a334ce5f7637b2c148991b189669b71395df05be2e6a69d025c9`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.domain.testManga
import eu.friedcutlet.yokan.data.LibraryTrack
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.*
import kotlin.test.*

class LibrarySortAndFiltersTest {
    private val off = LibraryFilterTypes(0, 0, 0, 0, 0, 0)
    private fun query(sort: Int = 0, reverse: Boolean = false, filters: LibraryFilterTypes = off, seed: Long = 0) =
        LibraryQuery("", filters, DbSortLibraryManga(reverse, sort), false, randomSeed = seed)

    @Test fun providerIncludesUseAnyWhileAnExcludedProviderAlwaysWins() {
        val titles = (1L..4L).map { testManga(it) }
        val index = LibraryIndex(trackedMangaIds = setOf(1, 2, 3), tracksByManga = mapOf(
            1L to listOf(track(1), track(2)), 2L to listOf(track(1)), 3L to listOf(track(3)),
        ))
        fun ids(filters: Map<Int, Int>) = libraryContent(titles, emptyList(), index,
            query(filters = off.copy(providerTracking = filters))).items(null).map(Manga::id)
        assertEquals(listOf(1L, 2L, 3L), ids(mapOf(1 to 1, 3 to 1)))
        assertEquals(listOf(2L, 3L), ids(mapOf(1 to 1, 3 to 1, 2 to 2)))
        assertEquals(listOf(2L, 3L, 4L), ids(mapOf(2 to 2)))
        assertEquals(emptyList(), ids(mapOf(999 to 1)))
        assertEquals(listOf(1L, 2L, 3L, 4L), ids(emptyMap()))
        assertEquals(listOf(4L), libraryContent(titles, emptyList(), index, query(filters = off.copy(tracking = 2))).items(null).map(Manga::id))
    }

    @Test fun manualEveryUpdateAndPositiveIntervalsAreCustomWhileAutomaticIsNot() {
        val titles = listOf(testManga(1), testManga(2).copy(smartUpdateDays = 0), testManga(3).copy(smartUpdateDays = 7))
        assertEquals(listOf(2L, 3L), libraryContent(titles, emptyList(), LibraryIndex.Empty,
            query(filters = off.copy(customInterval = 1))).items(null).map(Manga::id))
        assertEquals(listOf(1L), libraryContent(titles, emptyList(), LibraryIndex.Empty,
            query(filters = off.copy(customInterval = 2))).items(null).map(Manga::id))
    }

    @Test fun meanScoresNormalizeProvidersIgnoreUnratedInvalidAndDuplicateRowsAndKeepMissingLast() {
        val titles = listOf(testManga(5, "Epsilon"), testManga(3, "Gamma"), testManga(2, "Beta"), testManga(1, "Alpha"), testManga(4, "Delta"))
        val index = LibraryIndex(tracksByManga = mapOf(
            1L to listOf(track(1, 0), track(2, 80), track(2, 100)),
            2L to listOf(track(3, 95)),
            3L to listOf(track(2, 0)),
            4L to listOf(LibraryTrack(99, DbTrackStatus.Reading, 10, scoreMaximum = 20)),
            5L to listOf(track(2, 101), track(1, -5), track(98, 100)),
        ))
        assertEquals(listOf(4L, 1L, 2L, 5L, 3L), libraryContent(titles, emptyList(), index, query(sort = 8)).items(null).map(Manga::id))
        assertEquals(listOf(2L, 1L, 4L, 5L, 3L), libraryContent(titles, emptyList(), index, query(sort = 8, reverse = true)).items(null).map(Manga::id))
    }

    @Test fun fetchDateUsesAllKnownReleasesAndKeepsLegacyUnknownDatesLast() {
        val titles = (1L..3L).map { testManga(it) }
        val raw = LibraryIndex(chaptersByManga = mapOf(
            1L to listOf(chapter(1, 1, 10), chapter(2, 1, 50)),
            2L to listOf(chapter(3, 2, 30)), 3L to listOf(chapter(4, 3, 0)),
        ))
        val selected = LibraryIndex(chaptersByManga = mapOf(1L to raw.chapters(1).take(1), 2L to raw.chapters(2), 3L to raw.chapters(3)))
        assertEquals(listOf(2L, 1L, 3L), libraryContent(titles, emptyList(), raw, query(sort = 9), selected).items(null).map(Manga::id))
        assertEquals(listOf(1L, 2L, 3L), libraryContent(titles, emptyList(), raw, query(sort = 9, reverse = true), selected).items(null).map(Manga::id))
    }

    @Test fun randomOrderingSurvivesReorderingFilteringAndSettingsSerializationUntilReshuffled() {
        val titles = (1L..40L).map { testManga(it) }
        val q = query(sort = 7, seed = 123456)
        val before = libraryContent(titles, emptyList(), LibraryIndex.Empty, q).items(null)
        assertEquals(before, libraryContent(titles.reversed(), emptyList(), LibraryIndex.Empty, q).items(null))
        assertEquals(before.filter { it.name.contains("Title 1") },
            libraryContent(titles, emptyList(), LibraryIndex.Empty, q.copy(search = "Title 1")).items(null))
        assertNotEquals(before, libraryContent(titles, emptyList(), LibraryIndex.Empty, q.copy(randomSeed = 987654)).items(null))
        val settings = DbSettings(sortLibraryManga = q.sort).withLibraryRandomSeed(ItemType.Manga, q.randomSeed)
        val restored = DatabaseJson.decodeFromString(DbSettings.serializer(), DatabaseJson.encodeToString(DbSettings.serializer(), settings))
        assertEquals(before, libraryContent(titles, emptyList(), LibraryIndex.Empty, restored.libraryQuery(ItemType.Manga)).items(null))
    }

    @Test fun airingSortUsesUnreadCountsThenKnownTimesAndLeavesUnknownTimesLastWithinEachCount() {
        val titles = listOf(testManga(1).copy(nextEpisodeAiringAt = 2000), testManga(2).copy(nextEpisodeAiringAt = 1000),
            testManga(3), testManga(4).copy(nextEpisodeAiringAt = 500)).map { it.copy(itemType = ItemType.Anime) }
        val index = LibraryIndex(chaptersByManga = mapOf(4L to listOf(chapter(40, 4, 0))))
        assertEquals(listOf(2L, 1L, 3L, 4L), libraryContent(titles, emptyList(), index, query(sort = 10)).items(null).map(Manga::id))
        assertEquals(listOf(4L, 1L, 2L, 3L), libraryContent(titles, emptyList(), index, query(sort = 10, reverse = true)).items(null).map(Manga::id))
    }

    @Test fun extraFilterCyclesPersistPerMediaAndInvalidValuesAreIgnored() {
        var db = DbSettings()
        ItemType.entries.forEach { type ->
            db = db.withLibraryProviderTrackingCycled(type, 2).withLibraryFilterCycled(type, LibraryFilterKind.CustomInterval)
            assertEquals(1, db.libraryFilters(type).customInterval)
            assertEquals(mapOf(2 to 1), db.libraryFilters(type).providerTracking)
        }
        db = db.withLibraryProviderTrackingCycled(ItemType.Manga, 2).withLibraryFilterCycled(ItemType.Manga, LibraryFilterKind.CustomInterval)
        assertEquals(2, db.libraryFilters(ItemType.Manga).customInterval)
        assertEquals(mapOf(2 to 2), db.libraryFilters(ItemType.Manga).providerTracking)
        assertEquals(1, db.libraryFilters(ItemType.Anime).customInterval)
        db = db.withLibraryProviderTrackingCycled(ItemType.Manga, 2).withLibraryFilterCycled(ItemType.Manga, LibraryFilterKind.CustomInterval)
        assertTrue(db.libraryFilters(ItemType.Manga).providerTracking.isEmpty())
        assertEquals(0, db.libraryFilters(ItemType.Manga).customInterval)
        val malformed = db.copy(features = db.features.copy(library = db.features.library.withFilters(DbItemType.Manga,
            DbLibraryExtraFilters(mapOf(-1 to 1, 0 to 2, 2 to 99), customInterval = -3))))
        assertTrue(malformed.libraryFilters(ItemType.Manga).providerTracking.isEmpty())
        assertEquals(0, malformed.libraryFilters(ItemType.Manga).customInterval)
        assertEquals(malformed, malformed.withLibraryProviderTrackingCycled(ItemType.Manga, 0))
        assertEquals(db, DatabaseJson.decodeFromString(DbSettings.serializer(), DatabaseJson.encodeToString(DbSettings.serializer(), db)))
    }

    @Test fun manualMembershipsRemainUniqueWithDuplicateAssignmentsAndIndependentCategorySorts() {
        val titles = listOf(testManga(1).copy(categories = listOf(10, 10)), testManga(2).copy(categories = listOf(10, 20)), testManga(3))
        val categories = listOf(Category(10, "First", ItemType.Manga, 0), Category(20, "Second", ItemType.Manga, 1))
        val q = query().copy(categoryPreferences = mapOf(10L to DbCategoryLibraryPreferences(sort = DbSortLibraryManga(reverse = true))))
        val content = libraryContent(titles, categories, LibraryIndex.Empty, q)
        assertEquals(listOf(2L, 1L), content.items(10).map(Manga::id))
        assertEquals(listOf(2L), content.items(20).map(Manga::id))
        assertEquals(listOf(3L), content.items(UncategorizedCategoryId).map(Manga::id))
    }

    private fun track(provider: Int, score: Int? = null) = LibraryTrack(provider, DbTrackStatus.Reading, score)
    private fun chapter(id: Long, title: Long, at: Long) = Chapter(id, title, "Chapter $id", "/$id", fetchedAt = at)
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryUpdateScopeTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryUpdateScopeTest.kt) · test / fixture · 41 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
8: class LibraryUpdateScopeTest {
9: private fun title(id: Long, categories: List<Long> = emptyList(), tags: List<String> = emptyList()) = Manga(id = id,
14: private fun content(group: DbLibraryGrouping = DbLibraryGrouping.Categories, search: String = "") = libraryContent(titles, categories,
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryUpdateScopeTest.kt) · SHA-256 `c2bc64cc0dbf4904201d98988bdc15474d64e8afcf7b705d7d0a832d25e8f1bc`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.*
import kotlin.test.*

class LibraryUpdateScopeTest {
    private fun title(id: Long, categories: List<Long> = emptyList(), tags: List<String> = emptyList()) = Manga(id = id,
        name = "Title $id", link = "/$id", description = "", status = Status.Ongoing, itemType = ItemType.Manga,
        favorite = true, source = "Source", lang = "en", dateAddedMillis = 0, lastUpdateMillis = 0, categories = categories, genres = tags)
    private val titles = listOf(title(1, listOf(10), listOf("One")), title(2, listOf(10, 20), listOf("One", "Two")), title(3))
    private val categories = listOf(Category(10, "One", ItemType.Manga, 0), Category(20, "Two", ItemType.Manga, 1))
    private fun content(group: DbLibraryGrouping = DbLibraryGrouping.Categories, search: String = "") = libraryContent(titles, categories,
        LibraryIndex.Empty, LibraryQuery(search, LibraryFilterTypes(0, 0, 0, 0, 0, 0), DbSortLibraryManga(), false, grouping = group))

    @Test fun globalAndAllRemainGlobalButUnloadedOrStaleGroupsCannotExpandToGlobal() {
        assertNull(libraryUpdateTitleIds(null, 10, DbGroupUpdateMode.Global, LibraryIndex.Empty))
        assertEquals(emptySet(), libraryUpdateTitleIds(null, 10, DbGroupUpdateMode.CurrentGroup, LibraryIndex.Empty))
        assertEquals(emptySet(), libraryUpdateTitleIds(content(), 999, DbGroupUpdateMode.CurrentGroup, LibraryIndex.Empty))
        assertNull(libraryUpdateTitleIds(content(), null, DbGroupUpdateMode.CurrentGroup, LibraryIndex.Empty))
    }

    @Test fun categoryScopeUsesRawMembershipInsteadOfSearchAndRowMatches() {
        val hidden = content(search = "not found")
        assertTrue(hidden.items(10).isEmpty())
        assertEquals(setOf(1L, 2L), libraryUpdateTitleIds(hidden, 10, DbGroupUpdateMode.CurrentGroup, LibraryIndex.Empty))
        assertEquals(setOf(3L), libraryUpdateTitleIds(hidden, UncategorizedCategoryId, DbGroupUpdateMode.CurrentGroup, LibraryIndex.Empty))
    }

    @Test fun automaticGroupsUseStableRawMembershipAndDeduplicateMultiTagEntries() {
        val hidden = content(DbLibraryGrouping.Tags, search = "not found")
        val id = hidden.tabs.single { it.name == "One" }.id
        assertEquals(setOf(1L, 2L), libraryUpdateTitleIds(hidden, id, DbGroupUpdateMode.CurrentGroup, LibraryIndex.Empty))
    }

    @Test fun ungroupedExceptionUsesTheWholeLibrary() {
        assertNull(libraryUpdateTitleIds(content(DbLibraryGrouping.Ungrouped), null, DbGroupUpdateMode.CurrentExceptUngrouped, LibraryIndex.Empty))
        assertEquals(setOf(2L), libraryUpdateTitleIds(content(), 20, DbGroupUpdateMode.CurrentExceptUngrouped, LibraryIndex.Empty))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryViewModelTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryViewModelTest.kt) · test / fixture · 168 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
44: class LibraryViewModelTest {
61: fun tearDown() = host.close()
63: private fun TestScope.viewModel(settings: SettingsStore = SettingsStore(repository, backgroundScope) {}): LibraryViewModel {
90: fun listsOnlyFavouritesOfItsItemType() = runTest(dispatcher) {
98: fun markingTheSelectionReadClearsItAndWritesEveryChapter() = runTest(dispatcher) {
112: fun searchShowsImmediatelyAndPersistsAfterTheDebounce() = runTest(dispatcher) {
126: private object NoScanLibrary : LocalLibraryService {
127: override suspend fun scan() = LocalLibraryScanResult(0, 0, 0)
128: override suspend fun reconcile() = LocalLibraryReconciliationResult()
129: override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? = null
132: private object NoMetadata : MetadataService {
133: override suspend fun health(baseUrl: String) = false
134: override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int) = emptyList<MetadataMedia>()
135: override suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List<Pair<MetadataLibraryEntry, MetadataMedia>> = emptyList()
136: override suspend fun upsertLibraryEntry(
147: private object NoUpdater : LibraryUpdaterService {
148: override suspend fun updateLibrary(
155: override suspend fun updateTitle(mangaId: Long) = false
158: private object NoDownloads : DownloadService {
159: override suspend fun initialize(poolSize: Int) = Unit
160: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
161: override fun cancel(taskId: String) = Unit
162: override fun pause(taskId: String) = Unit
163: override fun resume(taskId: String) = Unit
164: override fun retry(taskId: String) = false
165: override fun storageLocation(taskId: String): String? = null
166: override fun deleteArtifacts(taskId: String) = Unit
167: override fun activeDownloads(): List<DownloadProgress> = emptyList()
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryViewModelTest.kt) · SHA-256 `ae52263ae46338c6f4a15f5d27b29eb830251f593499eec317bd18bd1c87ce69`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.download.ChapterDownloads
import eu.friedcutlet.yokan.services.download.DownloadProgress
import eu.friedcutlet.yokan.services.download.DownloadRequest
import eu.friedcutlet.yokan.services.download.DownloadService
import eu.friedcutlet.yokan.services.files.NoFiles
import eu.friedcutlet.yokan.services.library.DefaultLocalEntryManagementService
import eu.friedcutlet.yokan.services.library.LibraryUpdateController
import eu.friedcutlet.yokan.services.library.LibraryUpdateProgress
import eu.friedcutlet.yokan.services.library.LibraryUpdateResult
import eu.friedcutlet.yokan.services.library.LibraryUpdaterService
import eu.friedcutlet.yokan.services.library.LocalLibraryController
import eu.friedcutlet.yokan.services.library.LocalLibraryReconciliationResult
import eu.friedcutlet.yokan.services.library.LocalLibraryScanResult
import eu.friedcutlet.yokan.services.library.LocalLibraryService
import eu.friedcutlet.yokan.services.metadata.MetadataLibraryEntry
import eu.friedcutlet.yokan.services.metadata.MetadataMedia
import eu.friedcutlet.yokan.services.metadata.MetadataService
import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import eu.friedcutlet.yokan.ui.navigation.LibraryRequest
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest

@OptIn(ExperimentalCoroutinesApi::class)
class LibraryViewModelTest {
    private val host = ViewModelTestHost()
    private val dispatcher = host.dispatcher
    private val database = InMemoryYokanDatabase(
        emptySnapshot().copy(
            mangas = listOf(
                DbManga(id = 1, name = "Alpha", favorite = true),
                DbManga(id = 2, name = "Beta", favorite = true),
                DbManga(id = 3, name = "Anime", itemType = DbItemType.Anime, favorite = true),
                DbManga(id = 4, name = "Browsed"),
            ),
            chapters = listOf(DbChapter(id = 11, mangaId = 1, name = "One"), DbChapter(id = 12, mangaId = 1, name = "Two")),
        ),
    )
    private val repository = DefaultYokanRepository(database)

    @AfterTest
    fun tearDown() = host.close()

    private fun TestScope.viewModel(settings: SettingsStore = SettingsStore(repository, backgroundScope) {}): LibraryViewModel {
        val localLibrary = LocalLibraryController(
            localLibrary = NoScanLibrary,
            entryManagement = DefaultLocalEntryManagementService(database, NoScanLibrary),
            repository = repository,
            metadata = NoMetadata,
            trackers = emptyList(),
            files = NoFiles,
            settings = settings,
            importScope = backgroundScope,
        )
        return host.create {
            LibraryViewModel(
                itemType = ItemType.Manga,
                repository = repository,
                settings = settings,
                libraryIndex = LibraryIndexStore(repository, backgroundScope, dispatcher),
                libraryUpdates = LibraryUpdateController(NoUpdater, repository, NoNotifications, backgroundScope),
                localLibrary = localLibrary,
                chapterDownloads = ChapterDownloads(repository, database, NoDownloads, NoNotifications, settings, NoFiles, backgroundScope),
                libraryRequests = MutableStateFlow<LibraryRequest?>(null),
                workDispatcher = dispatcher,
            )
        }
    }

    @Test
    fun listsOnlyFavouritesOfItsItemType() = runTest(dispatcher) {
        val vm = viewModel()
        runCurrent()

        assertEquals(setOf(1L, 2L), vm.state.value.currentItems.map { it.id }.toSet())
    }

    @Test
    fun markingTheSelectionReadClearsItAndWritesEveryChapter() = runTest(dispatcher) {
        val vm = viewModel()
        runCurrent()

        vm.onEvent(LibraryEvent.BeginSelection(1))
        assertTrue(vm.state.value.selectionMode)
        vm.onEvent(LibraryEvent.MarkSelectedRead(isRead = true))
        runCurrent()

        assertEquals(emptySet(), vm.state.value.selectedIds)
        assertTrue(repository.chapters(1).all { it.isRead })
    }

    @Test
    fun searchShowsImmediatelyAndPersistsAfterTheDebounce() = runTest(dispatcher) {
        val settings = SettingsStore(repository, backgroundScope) {}
        val vm = viewModel(settings)
        runCurrent()

        vm.onEvent(LibraryEvent.Search("alp"))
        assertEquals("alp", vm.state.value.query.search)
        assertEquals("", settings.db.value.libraryQuery(ItemType.Manga).search)
        advanceTimeBy(251)

        assertEquals("alp", settings.db.value.libraryQuery(ItemType.Manga).search)
    }
}

private object NoScanLibrary : LocalLibraryService {
    override suspend fun scan() = LocalLibraryScanResult(0, 0, 0)
    override suspend fun reconcile() = LocalLibraryReconciliationResult()
    override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? = null
}

private object NoMetadata : MetadataService {
    override suspend fun health(baseUrl: String) = false
    override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int) = emptyList<MetadataMedia>()
    override suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List<Pair<MetadataLibraryEntry, MetadataMedia>> = emptyList()
    override suspend fun upsertLibraryEntry(
        baseUrl: String,
        token: String,
        mediaId: String,
        status: String,
        progress: Int,
        score: Int?,
        isFavorite: Boolean,
    ) = false
}

private object NoUpdater : LibraryUpdaterService {
    override suspend fun updateLibrary(
        itemType: DbItemType,
        onProgress: (LibraryUpdateProgress) -> Unit,
        shouldCancel: () -> Boolean,
        titleIds: Set<Long>?,
        mayStartTitle: suspend () -> Boolean,
    ) = LibraryUpdateResult(0, 0, 0)
    override suspend fun updateTitle(mangaId: Long) = false
}

private object NoDownloads : DownloadService {
    override suspend fun initialize(poolSize: Int) = Unit
    override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
    override fun cancel(taskId: String) = Unit
    override fun pause(taskId: String) = Unit
    override fun resume(taskId: String) = Unit
    override fun retry(taskId: String) = false
    override fun storageLocation(taskId: String): String? = null
    override fun deleteArtifacts(taskId: String) = Unit
    override fun activeDownloads(): List<DownloadProgress> = emptyList()
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/data/SettingsMutationAtomicityTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/data/SettingsMutationAtomicityTest.kt) · test / fixture · 42 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
9: class SettingsMutationAtomicityTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/data/SettingsMutationAtomicityTest.kt) · SHA-256 `c29c278a432056b6f451c007f3ef4c185baa8703152d05bcbee30476444977e2`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.data

import eu.friedcutlet.yokan.database.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
import kotlin.test.*

class SettingsMutationAtomicityTest {
    @Test fun uiPreferenceUpdateCannotOverwriteConcurrentRemoteQueueReceipt() {
        val database = InMemoryYokanDatabase(emptySnapshot())
        val repository = DefaultYokanRepository(database)
        val transforming = CountDownLatch(1)
        val secondStarted = CountDownLatch(1)
        val allowTransform = CountDownLatch(1)
        val ui = thread(start = true) {
            repository.updateDbSettings { old ->
                transforming.countDown()
                check(allowTransform.await(5, TimeUnit.SECONDS))
                old.copy(userAgent = "new-user-agent")
            }
        }
        assertTrue(transforming.await(5, TimeUnit.SECONDS))
        val queue = thread(start = true) {
            secondStarted.countDown()
            database.batch {
                val current = database.settings()
                database.updateSettings(current.copy(features = current.features.copy(externalDownloads = current.features.externalDownloads.copy(directory = "/remote-queue"))))
            }
        }
        assertTrue(secondStarted.await(5, TimeUnit.SECONDS))
        // Wait until the second writer either blocks behind the transaction or finishes without it.
        // This makes the lost-update interleaving deterministic instead of depending on thread timing.
        val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
        while (queue.isAlive && queue.state !in setOf(Thread.State.BLOCKED, Thread.State.WAITING, Thread.State.TIMED_WAITING) && System.nanoTime() < deadline) Thread.yield()
        allowTransform.countDown()
        ui.join(5000); queue.join(5000)
        assertFalse(ui.isAlive || queue.isAlive)
        assertEquals("new-user-agent", database.settings().userAgent)
        assertEquals("/remote-queue", database.settings().features.externalDownloads.directory)
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGroupingRenderTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGroupingRenderTest.kt) · test / fixture · 77 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
27: class LibraryGroupingRenderTest {
72: private fun <T> onUi(block: () -> T): T {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryGroupingRenderTest.kt) · SHA-256 `206e1b7266d4f2ef4f193c7a2d4228975cd5a1ec9d4732427bdeb060db24ec02`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.library

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier
import androidx.compose.ui.use
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.compose.LocalLifecycleOwner
import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.database.DbLibraryGrouping
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Status
import eu.friedcutlet.yokan.ui.theme.YokanTheme
import java.io.File
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlin.test.Test
import kotlin.test.assertEquals

class LibraryGroupingRenderTest {
    @Test fun aThousandTagGroupsLayOutAndNavigateAtPhoneAndDesktopWidths() {
        val manga = Manga(1, "A title with many tags", link = "/title", description = "", status = Status.Ongoing,
            itemType = ItemType.Manga, source = "Source", lang = "en", dateAddedMillis = 0, lastUpdateMillis = 0,
            genres = List(1000) { "Tag ${it.toString().padStart(4, '0')}" })
        val settings = DbSettings().withLibraryGrouping(ItemType.Manga, DbLibraryGrouping.Tags)
            .withLibraryDisplay(ItemType.Manga, categoryTabs = true)
        val query = settings.libraryQuery(ItemType.Manga)
        val content = libraryContent(listOf(manga), emptyList(), LibraryIndex.Empty, query)
        assertEquals(1000, content.tabs.size)
        listOf(360 to 800, 1024 to 800).forEach { (width, height) ->
            val state = mutableStateOf(LibraryState(ItemType.Manga, query, settings.libraryDisplay(ItemType.Manga), content = content))
            val owner = object : LifecycleOwner { override val lifecycle = LifecycleRegistry.createUnsafe(this) }
            onUi { owner.lifecycle.currentState = Lifecycle.State.RESUMED }
            val scene = onUi { ImageComposeScene(width, height) {
                CompositionLocalProvider(LocalLifecycleOwner provides owner) {
                    YokanTheme(darkTheme = true) {
                        Surface(Modifier.fillMaxSize()) {
                            LibraryScreen(state.value, compact = width < 600, onEvent = { event ->
                                if (event is LibraryEvent.SelectCategory) state.value = state.value.copy(selectedCategoryId = event.categoryId)
                            }, onOpenDetail = {}, onContinue = {})
                        }
                    }
                }
            } }
            try {
                var time = 0L
                repeat(12) { time += 100_000_000L; onUi { scene.render(time).close() } }
                assertEquals(null, state.value.selectedCategoryId)
                val last = content.tabs.last().id
                onUi { state.value = state.value.copy(selectedCategoryId = last) }
                repeat(12) { time += 100_000_000L; onUi { scene.render(time).close() } }
                assertEquals(last, state.value.selectedCategoryId)
                onUi { scene.render(time).use { image ->
                    assertEquals(width, image.width)
                    val output = File("build/reports/library-ui/library-1000-tags-$width.png")
                    output.parentFile.mkdirs()
                    checkNotNull(image.encodeToData()).use { output.writeBytes(it.bytes) }
                } }
            } finally {
                onUi { scene.close(); owner.lifecycle.currentState = Lifecycle.State.DESTROYED }
            }
        }
    }

    private fun <T> onUi(block: () -> T): T {
        val task = FutureTask<T> { block() }
        SwingUtilities.invokeAndWait(task)
        return task.get()
    }
}
```
[complete-source-end]: #

## `composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/library/BrowserLocalVideoTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/library/BrowserLocalVideoTest.kt) · test / fixture · 58 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
21: class BrowserLocalVideoTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/library/BrowserLocalVideoTest.kt) · SHA-256 `bd50293556bed88989c60064a36ac47fe2d82eb70e5a3c5594d373465b7267bf`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.app.profiles.deletePlatformProfileStorage
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContentTest
import eu.friedcutlet.yokan.services.files.createPlatformLocalArchiveService
import eu.friedcutlet.yokan.services.files.createPlatformLocalFileService
import eu.friedcutlet.yokan.services.media.createPlatformVideoFrameExtractor
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.runTest
import kotlin.test.*

/** Real OPFS files, the media worker URL the player opens, and a real `<video>` decode in the test browser. */
class BrowserLocalVideoTest {
    @Test fun opfsEpisodeResolvesToTheMediaWorkerAndYieldsFrameArtwork() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val root = "${files.downloadRoot}/anime"
        val owner = SupervisorJob()
        try {
            files.writeBytesAsync("$root/Show/Episode 1.webm", RedVideoFixtures.webm)
            val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root)))))
            val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))
            scanner.scan()
            val title = db.mangas().single()
            val stored = db.chapters(title.id).single()
            val factory = ProfileReaderContentTest.RuntimeFactory(db, "local")
            val content = ProfileReaderContent(
                id, db, factory, ChapterPageResolver(DefaultYokanRepository(db), db, factory),
                files, createPlatformLocalArchiveService(id), CoroutineScope(owner),
            )
            val episode = Chapter(id = stored.id, mangaId = title.id, name = stored.name.orEmpty(), url = stored.url, archivePath = stored.archivePath)
            val url = content.videos(null, episode).single().url
            content.closeAndJoin()
            assertTrue("__yokan_files__/" in url && url.endsWith("/Show/Episode%201.webm"), url)

            val frame = assertNotNull(createPlatformVideoFrameExtractor().extractJpeg(url, 512), "the browser decoded no frame")
            assertTrue(frame.size > 4 && frame[0] == 0xFF.toByte() && frame[1] == 0xD8.toByte(), "not a JPEG")

            assertTrue(LocalVideoArtwork(db, files, scanner, createPlatformVideoFrameExtractor()).generate())
            val cover = assertNotNull(db.manga(title.id)?.customCoverImage)
            assertTrue(cover[0] == 0xFF.toByte() && cover[1] == 0xD8.toByte())
            val thumbnail = assertNotNull(db.chapter(stored.id)?.thumbnailUrl)
            assertTrue("__yokan_files__/" in thumbnail && "/.yokan-artwork/" in thumbnail, thumbnail)
        } finally {
            owner.cancelAndJoin()
            files.close()
            deletePlatformProfileStorage(id, emptyList())
        }
    }
}
```
[complete-source-end]: #

