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 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 fun chapters(mangaId: Long): List /** * 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 fun categories(itemType: ItemType): List 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 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 fun upsertRepository(itemType: ItemType, repo: DbRepo) fun removeRepository(itemType: ItemType, jsonUrl: String) fun allTitles(itemType: ItemType): List fun manga(mangaId: Long): Manga? fun history(): List fun updates(): List fun tracks(): List fun downloads(): List fun removeDownload(downloadId: Long) fun cancelDownload(downloadId: Long) fun clearChapterDownloads(chapterIds: Set) /** The saved page list as stored, fresh or not; readers go through `ChapterPageResolver`. */ fun pageUrls(chapterId: Long): List /** Saves [pageUrls] as fetched from [source] at [fetchedAt], minus Cookie/Authorization headers. */ fun cachePageUrls( chapterId: Long, chapterUrl: String, pageUrls: List, 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): 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, favorite: Boolean = false) fun setLibraryEntriesRead(mangaIds: Set, 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) = Unit fun setChaptersRead( chapterIds: Set, isRead: Boolean, lastPageRead: String? = null, readingTimeSeconds: Int = 0, autoReadDuplicates: Boolean = false, ) fun setChaptersBookmarked(chapterIds: Set, bookmarked: Boolean) /** Manual filler mark that wins over the source value; null clears it. */ fun setChaptersFillerOverride(chapterIds: Set, 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) fun deleteChapters(chapterIds: Set) 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 YokanRepository.observe( key: (YokanDatabaseSnapshot) -> K, context: CoroutineContext = Dispatchers.Default, read: YokanRepository.() -> T, ): Flow = snapshots.distinctUntilChangedBy(key).map { read() }.flowOn(context) /** Derive a read model from the exact published revision whose dependencies changed. */ fun YokanRepository.observeSnapshot( key: (YokanDatabaseSnapshot) -> K, context: CoroutineContext = Dispatchers.Default, read: (YokanDatabaseSnapshot) -> T, ): Flow = snapshots.distinctUntilChangedBy(key).map(read).flowOn(context)