package eu.friedcutlet.yokan.domain data class ChapterReleasePreferences( val scanlatorPriority: List = emptyList(), val skipDuplicates: Boolean = false, ) /** Only explicit chapter/episode numbers or leading numeric chapter labels establish equivalence. */ data class ChapterReleaseIdentity( val number: Double, val season: Int?, val volume: Int?, val part: String, val language: String, val edition: String, ) private val explicitNumber = Regex("\\b(?:chapter|chap|ch|episode|ep|folge)\\.?\\s*#?\\s*(\\d+(?:[.,]\\d+)?)([a-z]?)(?=\\s|[:.\\-]|$)") private val leadingNumber = Regex("^#?(\\d+(?:[.,]\\d+)?)([a-z]?)(?=\\s|[:.\\-]|$)") private val seasonLabel = Regex("\\b(?:season|staffel|saison|temporada|s)\\.?\\s*(\\d+)\\b") private val volumeLabel = Regex("\\b(?:volume|vol|v)\\.?\\s*(\\d+)\\b") private val editionLabel = Regex("\\b(?:special|extra|omake|oneshot|one-shot|colored|coloured|color|colour|remaster(?:ed)?|uncensored|censored|revised|bonus|part\\s*\\d+)\\b") private val languageLabel = Regex("\\[(?:lang[:=]\\s*)?([a-z]{2}(?:-[a-z]{2})?)\\]") private val whitespace = Regex("\\s+") private val numberRange = Regex("^\\s*(?:[-–/&]|and|\\.)\\s*\\d") private val namedLanguage = Regex("\\b(?:english|spanish|french|german|russian|portuguese|japanese|chinese|korean|italian|turkish)\\b") /** Case/whitespace normalization only: punctuation and combined group names keep their meaning. */ fun normalizeScanlator(name: String): String = name.trim().replace(whitespace, " ").lowercase() fun chapterReleaseIdentity( mangaTitle: String, chapterName: String, number: Double? = null, season: Int? = null, numberingName: String? = null, ): ChapterReleaseIdentity? { val named = namedChapterReleaseIdentity(mangaTitle, numberingName?.takeIf(String::isNotBlank) ?: chapterName) val validSeason = season?.takeIf { it >= 0 } val explicit = number?.takeIf { it.isFinite() && it >= 0 } return if (explicit != null) { named?.copy(number = explicit, season = validSeason ?: named.season) ?: ChapterReleaseIdentity(explicit, validSeason, null, "", "", "") } else named?.let { if (validSeason == null) it else it.copy(season = validSeason) } } private fun namedChapterReleaseIdentity(mangaTitle: String, chapterName: String): ChapterReleaseIdentity? { var name = chapterName.lowercase().trim() if (mangaTitle.isNotBlank()) name = name.replace(mangaTitle.lowercase(), "").trim() val matches = explicitNumber.findAll(name).toList() if (matches.size > 1) return null // Ranges/combined chapters are uncertain. val number = matches.singleOrNull() ?: leadingNumber.find(name) ?: return null val value = number.groupValues[1].replace(',', '.').toDoubleOrNull()?.takeIf { it.isFinite() } ?: return null // A second number after a range separator is not a decimal or a separate release. if (numberRange.containsMatchIn(name.substring(number.range.last + 1))) return null fun label(regex: Regex): Int? = regex.find(name)?.groupValues?.get(1)?.toIntOrNull() return ChapterReleaseIdentity(value, label(seasonLabel), label(volumeLabel), number.groupValues[2], (languageLabel.findAll(name).map { it.groupValues[1] } + namedLanguage.findAll(name).map { it.value }) .distinct().sorted().joinToString("/"), editionLabel.findAll(name).map { it.value.replace(whitespace, " ") }.distinct().sorted().joinToString("/")) } /** Transient ingestion/read-state key; uncertain names retain their independent URL identity. */ fun chapterReleaseKey( mangaTitle: String?, chapterName: String?, scanlator: String? = null, number: Double? = null, season: Int? = null, numberingName: String? = null, ): String? = chapterReleaseIdentity(mangaTitle.orEmpty(), chapterName.orEmpty(), number, season, numberingName) ?.let { "$it::${normalizeScanlator(scanlator.orEmpty())}" } private fun Chapter.releaseIdentity(title: String): ChapterReleaseIdentity? = chapterReleaseIdentity(title, name, number, season, numberingName) /** * Select without deleting releases. Read/bookmark state belongs to an equivalence group while * file locations and page positions always belong to the actual winning release. */ fun selectChapterReleases( mangaTitle: String, chapters: List, preferences: ChapterReleasePreferences = ChapterReleasePreferences(), excludedScanlators: Set = emptySet(), downloadedIds: Set = emptySet(), offlineOnly: Boolean = false, showAllReleases: Boolean = false, ): List { val hidden = excludedScanlators.map(::normalizeScanlator).toSet() fun downloaded(chapter: Chapter) = chapter.id in downloadedIds || chapter.downloadSize != null || chapter.archivePath.isNotBlank() val eligible = chapters.filter { normalizeScanlator(it.scanlator) !in hidden && (!offlineOnly || downloaded(it)) } if (!preferences.skipDuplicates || showAllReleases) return eligible val identities = chapters.associate { it.id to it.releaseIdentity(mangaTitle) } val groups = chapters.groupBy { identities[it.id] ?: it.id } val ranks = preferences.scanlatorPriority.map(::normalizeScanlator).distinct().withIndex().associate { it.value to it.index } val comparator = compareBy { ranks[normalizeScanlator(it.scanlator)] ?: Int.MAX_VALUE } .thenBy { !downloaded(it) }.thenBy { normalizeScanlator(it.scanlator) } .thenBy { it.url }.thenBy { it.id } return eligible.groupBy { identities[it.id] ?: it.id }.map { (key, releases) -> val winner = releases.minWith(comparator) val equivalents = groups.getValue(key) winner.copy(isRead = equivalents.any { it.isRead }, isBookmarked = equivalents.any { it.isBookmarked }) } } /** Explicit group actions can clear aggregated state as well as set it. Uncertain rows stay local. */ fun equivalentReleaseIds(mangaTitle: String, chapters: List, selectedIds: Set): Set { val identities = chapters.associate { it.id to it.releaseIdentity(mangaTitle) } val selectedKeys = selectedIds.mapNotNull { identities[it] }.toSet() return chapters.filter { it.id in selectedIds || identities[it.id]?.let(selectedKeys::contains) == true }.mapTo(HashSet()) { it.id } } fun chapterReadingOrder(mangaTitle: String, chapters: List): List { val identities = chapters.associate { it.id to it.releaseIdentity(mangaTitle) } return chapters.sortedWith(compareBy { identities[it.id]?.season ?: 0 } .thenBy { identities[it.id]?.volume ?: 0 }.thenBy { identities[it.id]?.number ?: 0.0 } .thenBy { identities[it.id]?.part.orEmpty() }.thenBy { it.id }) }