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) { 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() val seenCompositeKeys = mutableSetOf() 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())) } }