package eu.friedcutlet.yokan.ui.screens.local import kotlinx.coroutines.CoroutineDispatcher import eu.friedcutlet.yokan.services.library.LocalMetadataSourceResult import eu.friedcutlet.yokan.services.library.LocalLibraryOverview import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.LibraryIndexStore import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.toDb import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.colorization.ColorizationJob import eu.friedcutlet.yokan.services.colorization.LocalColorizationQueue import eu.friedcutlet.yokan.services.library.LocalEntryManagementApplyStatus import eu.friedcutlet.yokan.services.library.LocalEntryManagementOperation import eu.friedcutlet.yokan.services.library.LocalEntryManagementPreview import eu.friedcutlet.yokan.services.library.LocalLibraryController import eu.friedcutlet.yokan.services.library.LocalLibraryDuplicateGroup import eu.friedcutlet.yokan.services.library.LocalImportProgress import eu.friedcutlet.yokan.services.library.PendingLocalImport import eu.friedcutlet.yokan.services.files.LocalMediaSelection import eu.friedcutlet.yokan.services.files.pickLocalMedia import eu.friedcutlet.yokan.services.metadata.LocalMetadataField import eu.friedcutlet.yokan.services.metadata.MetadataMedia import eu.friedcutlet.yokan.services.library.visibleChapters import kotlinx.coroutines.CancellationException 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.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** Candidate search and field selection for one local title; nothing is written until applied. */ data class LocalMetadataReviewState( val manga: Manga, val sourceResults: List = emptyList(), val selectedCandidate: MetadataMedia? = null, val selectedFields: Set = emptySet(), val error: String? = null, val loading: Boolean = false, ) { val candidates: List = sourceResults.flatMap { it.candidates } } data class LocalLibraryUiState( val overview: LocalLibraryOverview = LocalLibraryOverview(folders = emptyList(), manga = 0, anime = 0, novels = 0), val titlesByType: Map> = emptyMap(), val reviewQueue: List = emptyList(), /** Names of the titles the reconciliation refers to, for the stale and duplicate rows. */ val titleNames: Map = emptyMap(), val message: String? = null, val managementPreview: LocalEntryManagementPreview? = null, val selectedEntry: Manga? = null, val selectedEntryChapters: List = emptyList(), val metadataReview: LocalMetadataReviewState? = null, val colorizationJobs: List = emptyList(), val colorizationSupported: Boolean = false, val colorizationError: String? = null, val importBusy: Boolean = false, val importProgress: LocalImportProgress? = null, val importFailed: Boolean = false, val importError: String? = null, val importCompleted: Boolean = false, val pendingImports: List = emptyList(), ) sealed interface LocalLibraryEvent { data object Rescan : LocalLibraryEvent data object FullRescan : LocalLibraryEvent data class ImportMedia(val type: ItemType, val directory: Boolean) : LocalLibraryEvent data object CancelImport : LocalLibraryEvent data class RecoverImport(val id: String) : LocalLibraryEvent data class DiscardIncompleteImport(val id: String) : LocalLibraryEvent data class PreviewOperation(val operation: LocalEntryManagementOperation) : LocalLibraryEvent data class PreviewMerge(val group: LocalLibraryDuplicateGroup, val canonicalTitleId: Long) : LocalLibraryEvent data object ConfirmOperation : LocalLibraryEvent data object DismissOperation : LocalLibraryEvent data class SelectEntry(val manga: Manga?) : LocalLibraryEvent data class OpenMetadataReview(val manga: Manga) : LocalLibraryEvent data object DismissMetadataReview : LocalLibraryEvent data object SearchMetadataCandidates : LocalLibraryEvent data class SelectCandidate(val candidate: MetadataMedia) : LocalLibraryEvent data class SetFieldSelected(val field: LocalMetadataField, val selected: Boolean) : LocalLibraryEvent data object ApplyMetadata : LocalLibraryEvent data class EnqueueColorization(val manga: Manga) : LocalLibraryEvent data class ColorizationAction(val jobId: String, val action: ColorizationJobAction) : LocalLibraryEvent } enum class ColorizationJobAction { Pause, Resume, Retry, Cancel } /** Local media overview: folders, scan state, metadata review queue, and forget/merge management. */ class LocalLibraryViewModel( private val controller: LocalLibraryController, settings: SettingsStore, libraryIndex: LibraryIndexStore, private val colorizationQueue: LocalColorizationQueue? = null, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, private val mediaPicker: suspend (Boolean) -> LocalMediaSelection? = ::pickLocalMedia, ) : ViewModel() { private val _state = MutableStateFlow(LocalLibraryUiState()) val state: StateFlow = _state.asStateFlow() private var searchJob: Job? = null private var importJob: Job? = null init { refreshPendingImports() viewModelScope.launch { combine(controller.observeLibrary(workDispatcher), settings.db.map(controller::folders).distinctUntilChanged(), controller.scan) { library, folders, scan -> Derived( overview = library.overview(folders, scan), titlesByType = library.titlesByType, reviewQueue = library.reviewQueue, titleNames = library.titleNames(scan.reconciliation), ) }.flowOn(workDispatcher).collect { derived -> _state.update { it.copy( overview = derived.overview, titlesByType = derived.titlesByType, reviewQueue = derived.reviewQueue, titleNames = derived.titleNames, ) } } } colorizationQueue?.let { queue -> viewModelScope.launch { queue.jobs.collect { jobs -> _state.update { it.copy(colorizationJobs = jobs) } } } _state.update { it.copy(colorizationSupported = queue.supported) } } viewModelScope.launch { combine(_state.map { it.selectedEntry }.distinctUntilChanged(), libraryIndex.index, settings.db) { manga, index, db -> manga to manga?.let { visibleChapters(it, index.chapters(it.id), db, index.downloadedChapterIds) }.orEmpty() }.flowOn(workDispatcher).collect { (manga, chapters) -> _state.update { if (it.selectedEntry?.id == manga?.id) it.copy(selectedEntryChapters = chapters) else it } } } } fun onEvent(event: LocalLibraryEvent) { when (event) { LocalLibraryEvent.Rescan -> rescan() LocalLibraryEvent.FullRescan -> rescan(forceRefresh = true) is LocalLibraryEvent.ImportMedia -> importMedia(event) LocalLibraryEvent.CancelImport -> importJob?.cancel() is LocalLibraryEvent.RecoverImport -> importAction { controller.recoverImport(event.id); controller.rescanAndReconcile() } is LocalLibraryEvent.DiscardIncompleteImport -> importAction { controller.discardIncompleteImport(event.id) } is LocalLibraryEvent.PreviewOperation -> preview(event.operation) is LocalLibraryEvent.PreviewMerge -> _state.value.overview.reconciliation?.let { evidence -> preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, event.group.ids, event.canonicalTitleId)) } LocalLibraryEvent.ConfirmOperation -> confirmOperation() LocalLibraryEvent.DismissOperation -> _state.update { it.copy(managementPreview = null) } is LocalLibraryEvent.SelectEntry -> _state.update { it.copy(selectedEntry = event.manga, selectedEntryChapters = emptyList()) } is LocalLibraryEvent.OpenMetadataReview -> { searchJob?.cancel() _state.update { it.copy(selectedEntry = null, metadataReview = LocalMetadataReviewState(event.manga)) } } LocalLibraryEvent.DismissMetadataReview -> { searchJob?.cancel() _state.update { it.copy(metadataReview = null) } } LocalLibraryEvent.SearchMetadataCandidates -> searchCandidates() is LocalLibraryEvent.SelectCandidate -> updateReview { it.copy(selectedCandidate = event.candidate) } is LocalLibraryEvent.SetFieldSelected -> updateReview { it.copy(selectedFields = if (event.selected) it.selectedFields + event.field else it.selectedFields - event.field) } LocalLibraryEvent.ApplyMetadata -> applyMetadata() is LocalLibraryEvent.EnqueueColorization -> colorizationQueue?.let { queue -> if (event.manga.itemType == ItemType.Manga && event.manga.isLocalArchive && !event.manga.source.equals("torrent", true)) { viewModelScope.launch { try { withContext(workDispatcher) { queue.enqueue(event.manga.id) } _state.update { it.copy(colorizationError = null) } } catch (error: CancellationException) { throw error } catch (error: Throwable) { _state.update { it.copy(colorizationError = error.message ?: "Could not start colorization.") } } } } } is LocalLibraryEvent.ColorizationAction -> colorizationQueue?.let { queue -> viewModelScope.launch { try { withContext(workDispatcher) { when (event.action) { ColorizationJobAction.Pause -> queue.pause(event.jobId) ColorizationJobAction.Resume -> queue.resume(event.jobId) ColorizationJobAction.Retry -> queue.retry(event.jobId) ColorizationJobAction.Cancel -> queue.cancel(event.jobId) } } _state.update { it.copy(colorizationError = null) } } catch (error: CancellationException) { throw error } catch (error: Throwable) { _state.update { it.copy(colorizationError = error.message ?: "Could not update colorization.") } } } } } } private fun refreshPendingImports() { viewModelScope.launch { catchingNonCancellation { controller.pendingImports() } .onSuccess { pending -> _state.update { it.copy(pendingImports = pending) } } } } private fun importMedia(event: LocalLibraryEvent.ImportMedia) = importAction { // Keep the picker on Main and before any dispatcher hop so browsers retain user activation. val selection = mediaPicker(event.directory) ?: return@importAction try { controller.importMedia(selection, event.type.toDb()) { progress -> _state.update { it.copy(importProgress = progress) } } } finally { selection.close() } controller.rescanAndReconcile() _state.update { it.copy(importCompleted = true) } } private fun importAction(action: suspend () -> Unit) { if (importJob?.isActive == true) return _state.update { it.copy(importBusy = true, importProgress = null, importFailed = false, importError = null, importCompleted = false) } importJob = viewModelScope.launch { try { action() } catch (cancelled: CancellationException) { throw cancelled } catch (error: Throwable) { _state.update { it.copy(importFailed = true, importError = error.message) } } finally { _state.update { it.copy(importBusy = false, importProgress = null) } refreshPendingImports() } } } private fun rescan(forceRefresh: Boolean = false) { _state.update { it.copy(message = null) } viewModelScope.launch { catchingNonCancellation { controller.rescanAndReconcile(forceRefresh) } .onFailure { error -> _state.update { it.copy(message = error.message ?: "Scan or reconciliation failed") } } } } private fun preview(operation: LocalEntryManagementOperation) { viewModelScope.launch { val preview = withContext(workDispatcher) { controller.preview(operation) } _state.update { it.copy(managementPreview = preview) } } } private fun confirmOperation() { val preview = _state.value.managementPreview ?: return viewModelScope.launch { val result = controller.apply(preview.command) _state.update { if (result.status == LocalEntryManagementApplyStatus.Applied) { it.copy(managementPreview = null) } else { it.copy(message = "Operation blocked: ${result.blocker ?: "unknown reason"}") } } } } private fun searchCandidates() { val review = _state.value.metadataReview ?: return if (review.loading) return updateReview { it.copy(sourceResults = emptyList(), error = null, loading = true) } searchJob = viewModelScope.launch { val result = catchingNonCancellation { controller.searchMetadataCandidates(review.manga) } updateReview { current -> result.fold( onSuccess = { current.copy(sourceResults = it, loading = false) }, onFailure = { current.copy(error = it.message ?: "Search failed", loading = false) }, ) } } } private fun applyMetadata() { val review = _state.value.metadataReview ?: return val candidate = review.selectedCandidate ?: return controller.applyMetadataCandidate(review.manga, candidate, review.selectedFields) onEvent(LocalLibraryEvent.DismissMetadataReview) } private fun updateReview(transform: (LocalMetadataReviewState) -> LocalMetadataReviewState) { _state.update { state -> state.metadataReview?.let { state.copy(metadataReview = transform(it)) } ?: state } } private class Derived( val overview: LocalLibraryOverview, val titlesByType: Map>, val reviewQueue: List, val titleNames: Map, ) }