package eu.friedcutlet.yokan.services.migration import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.domain.mergePrivateNotes import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory import eu.friedcutlet.yokan.services.extensions.RemoteManga import eu.friedcutlet.yokan.services.extensions.RemoteDetail import eu.friedcutlet.yokan.services.extensions.withSourceRuntime import eu.friedcutlet.yokan.services.library.withoutUpdateError import eu.friedcutlet.yokan.services.logging.AppLogger import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.Job import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.isActive import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.update /** * Moves library titles to another source. Single and mass migration share [migrate]; a mass run * lives in the app [scope], so it keeps going after its screen is left. */ class MigrationService( private val repository: YokanRepository, private val database: YokanDatabase, private val runtimeFactory: ExtensionRuntimeFactory, private val settings: SettingsStore, private val scope: CoroutineScope, private val searchLimits: MigrationSearchLimits = MigrationSearchLimits(), private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) { private var job: Job? = null private val _progress = MutableStateFlow(null) /** The latest mass run; stays at its final value until the next [start]. */ val progress: StateFlow = _progress.asStateFlow() /** * Fetches [candidate]'s detail from [destination] (which stores its chapters), copies read and * bookmark state where chapter names align, transfers categories, unfavorites [from] and * clears its update error. Returns the new title id, or null when the destination is no longer * installed or the fetch fails. */ suspend fun migrate(from: Manga, destination: Source, candidate: RemoteManga): Long? = catchingNonCancellation { val detail = runtimeFactory.withSourceRuntime(database, destination.id) { it.detail(candidate.url) } migratePrepared(from, destination, detail) }.getOrNull() /** The reviewed detail is reused; applying a proposal never performs a fresh network fetch. */ private suspend fun migratePrepared(from: Manga, destination: Source, detail: RemoteDetail): Long? = catchingNonCancellation { val installed = repository.source(destination.id) ?: return@catchingNonCancellation null check(installed.isAdded && installed.isActive && installed.itemType == destination.itemType && installed.name == destination.name && installed.lang == destination.lang && installed.baseUrl == destination.baseUrl && installed.sourceCodeLanguage == destination.sourceCodeLanguage) val original = repository.manga(from.id) ?: return@catchingNonCancellation null check(original.favorite && original.link == from.link && original.sourceId == from.sourceId) currentCoroutineContext().ensureActive() val newManga = repository.upsertRemoteDetail(destination, detail, favorite = true) check(newManga.id != from.id) val oldChapters = repository.chapters(from.id) repository.chapters(newManga.id).forEach { newChapter -> val match = oldChapters.firstOrNull { old -> old.name.equals(newChapter.name, ignoreCase = true) || old.url.endsWith(newChapter.url.substringAfterLast('/')) } ?: return@forEach if (match.isRead || match.isBookmarked) { repository.setChaptersRead(setOf(newChapter.id), match.isRead, match.lastPageRead.takeIf { it.isNotBlank() }, 0) repository.setChaptersBookmarked(setOf(newChapter.id), match.isBookmarked) } } val oldNote = repository.manga(from.id)?.privateNote.orEmpty() checkNotNull(repository.setMangaPrivateNote(newManga.id, mergePrivateNotes(newManga.privateNote, oldNote))) repository.setMangaCategories(newManga.id, from.categories) settings.updateDb { it.withoutUpdateError(from.id) } currentCoroutineContext().ensureActive() repository.setMangaFavorite(from.id, false) newManga.id }.onFailure { AppLogger.warn("[migration] title ${from.id} to ${destination.name} failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") } .getOrNull() /** Starts discovery only. Re-entering the same route attaches to its existing run. */ fun start(sourceId: Long, destinationIds: List, mangaIds: List): Boolean { val ids = destinationIds.distinct() val titles = mangaIds.distinct() val current = _progress.value if (current?.sourceId == sourceId && current.destinationIds == ids && current.mangaIds == titles) return true if (current?.running == true || current?.phase == MigrationPhase.Reviewing || job?.isActive == true) return false val source = repository.source(sourceId) ?: return false val destinations = ids.mapNotNull(repository::source) if (destinations.size != ids.size || destinations.isEmpty() || destinations.any { it.id == source.id || !it.isAdded || !it.isActive || it.itemType != source.itemType }) return false val targets = titles.mapNotNull(repository::manga).filter { it.favorite && it.itemType == source.itemType && (it.sourceId == source.id || (it.sourceId == null && it.source == source.name && (it.lang.isBlank() || it.lang == source.lang))) } val started = MassMigrationProgress(sourceId, ids, titles, targets.map { MigrationReviewItem(it, repository.chapters(it.id).size) }, MigrationPhase.Searching) if (!_progress.compareAndSet(current, started)) return false job = scope.launch(workDispatcher) { try { val planner = MigrationPlanner(database, runtimeFactory, searchLimits) for (target in targets) discover(target.id, destinations, planner) _progress.update { it?.copy(phase = MigrationPhase.Reviewing) } } finally { if (!currentCoroutineContext().isActive) _progress.update { it?.copy(phase = MigrationPhase.Cancelled) } } } return true } private suspend fun discover(mangaId: Long, destinations: List, planner: MigrationPlanner = MigrationPlanner(database, runtimeFactory, searchLimits)) { val original = _progress.value?.items?.firstOrNull { it.original.id == mangaId }?.original ?: return val results = planner.discover(original, destinations) val candidates = rankedMigrationCandidates(results) updateItem(mangaId) { item -> item.copy( sources = results, candidates = candidates, selected = candidates.firstOrNull()?.key, status = when { candidates.isNotEmpty() -> MigrationItemStatus.Ready results.any { it.issues.isNotEmpty() } -> MigrationItemStatus.Failed else -> MigrationItemStatus.Unmatched }, ) } } fun select(mangaId: Long, key: MigrationCandidateKey?) { _progress.update { run -> if (run?.phase != MigrationPhase.Reviewing) run else run.copy(items = run.items.map { item -> if (item.original.id != mangaId || item.status == MigrationItemStatus.Migrated || item.status == MigrationItemStatus.Pending || (key != null && item.candidates.none { it.key == key })) item else item.copy(selected = key, status = if (key == null) MigrationItemStatus.Skipped else MigrationItemStatus.Ready) }) } } /** Retry is explicit and refreshes search/details; other reviewed rows stay intact. */ fun retry(mangaId: Long) { val current = _progress.value ?: return if (current.running || job?.isActive == true) return val item = current.items.firstOrNull { it.original.id == mangaId } ?: return if (item.status == MigrationItemStatus.Migrated) return val destinations = current.destinationIds.mapNotNull { id -> repository.source(id) ?: current.items.flatMap { it.sources }.firstOrNull { it.source.id == id }?.source } if (!_progress.compareAndSet(current, current.copy(phase = MigrationPhase.Searching, items = current.items.map { if (it.original.id == mangaId) it.copy(status = MigrationItemStatus.Pending, selected = null) else it }))) return job = scope.launch(workDispatcher) { try { discover(mangaId, destinations) _progress.update { it?.copy(phase = MigrationPhase.Reviewing) } } finally { if (!currentCoroutineContext().isActive) _progress.update { it?.copy(phase = MigrationPhase.Cancelled) } } } } /** Called only from review. Incomplete source results stay visible beside the chosen winner. */ fun commitSelected() { val current = _progress.value ?: return if (current.phase != MigrationPhase.Reviewing || current.selectedCount == 0 || current.items.any { it.status == MigrationItemStatus.Pending } || job?.isActive == true) return if (!_progress.compareAndSet(current, current.copy(phase = MigrationPhase.Migrating))) return job = scope.launch(workDispatcher) { try { for (item in current.items.filter { it.status == MigrationItemStatus.Ready && it.selected != null }) { currentCoroutineContext().ensureActive() val candidate = item.candidates.firstOrNull { it.key == item.selected } ?: continue val migrated = migratePrepared(item.original, candidate.source, candidate.detail) != null updateItem(item.original.id) { it.copy(status = if (migrated) MigrationItemStatus.Migrated else MigrationItemStatus.Failed) } } _progress.update { it?.copy(phase = MigrationPhase.Completed) } } finally { if (!currentCoroutineContext().isActive) _progress.update { it?.copy(phase = MigrationPhase.Cancelled) } } } } fun cancel() { if (job?.isActive == true) job?.cancel() else _progress.update { it?.copy(phase = MigrationPhase.Cancelled) } } private fun updateItem(mangaId: Long, transform: (MigrationReviewItem) -> MigrationReviewItem) { _progress.update { run -> run?.copy(items = run.items.map { if (it.original.id == mangaId) transform(it) else it }) } } }