package win.taptap.musicmanager.api import io.ktor.http.HttpStatusCode import io.ktor.server.response.respond import io.ktor.server.routing.Route import io.ktor.server.routing.delete import io.ktor.server.routing.get import io.ktor.server.routing.patch import io.ktor.server.routing.post import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import win.taptap.musicmanager.api.AddSeedRequest import win.taptap.musicmanager.api.AddToMoodResponse import win.taptap.musicmanager.api.CreateMoodRequest import win.taptap.musicmanager.api.MoodDetailDto import win.taptap.musicmanager.api.MoodDto import win.taptap.musicmanager.api.DownloadDto import win.taptap.musicmanager.api.RecommendationDecisionDto import win.taptap.musicmanager.api.RecommendationDto import win.taptap.musicmanager.api.SearchResponse import win.taptap.musicmanager.api.UpdateMoodRequest import win.taptap.musicmanager.api.seedDto import win.taptap.musicmanager.api.toDto import win.taptap.musicmanager.config.LibraryConfig import win.taptap.musicmanager.config.UserAccount import win.taptap.musicmanager.config.UsersConfig import win.taptap.musicmanager.db.DownloadRepository import win.taptap.musicmanager.db.LibraryRepository import win.taptap.musicmanager.db.MoodRecord import win.taptap.musicmanager.db.MoodRepository import win.taptap.musicmanager.discovery.DiscoveryService import win.taptap.musicmanager.radio.RadioService @Serializable data class MoodsResponse(val moods: List) fun Route.moodRoutes( users: UsersConfig, library: LibraryConfig, radioService: RadioService, discoveryService: DiscoveryService, downloadsEnabled: Boolean, ) { get("/moods") { val user = call.requireApiUser(users) call.respond(MoodsResponse(MoodRepository.list(user.name).map { it.toDto() })) } post("/moods") { val user = call.requireApiUser(users) val request = call.receiveJson() val name = request.name.trim() if (name.isEmpty()) badRequest("Mood name is required") val folders = user.musicFolderIds(library) val seedIds = request.seedSongIds .distinct() .filter { LibraryRepository.song(it, folders, user.name) != null } val mood = MoodRepository.create( owner = user.name, name = name, description = request.description?.trim()?.takeIf { it.isNotEmpty() }, query = request.query?.trim()?.takeIf { it.isNotEmpty() }, genres = request.genres, targetSize = request.targetSize, refreshHours = request.refreshHours, ytEnabled = request.ytEnabled, seedSongIds = seedIds, seedPercent = request.seedPercent, ) call.respond(HttpStatusCode.Created, detail(mood, user, library)) } get("/moods/{id}") { val user = call.requireApiUser(users) val mood = ownedMood(call.parameters["id"], user) call.respond(detail(mood, user, library)) } patch("/moods/{id}") { val user = call.requireApiUser(users) val mood = ownedMood(call.parameters["id"], user) val request = call.receiveJson() val description = when { request.clearDescription -> null request.description != null -> request.description.trim().takeIf { it.isNotEmpty() } else -> mood.description } val query = when { request.clearQuery -> null request.query != null -> request.query.trim().takeIf { it.isNotEmpty() } else -> mood.query } val updated = MoodRepository.update( id = mood.id, owner = user.name, name = request.name?.trim()?.takeIf { it.isNotEmpty() } ?: mood.name, description = description, query = query, genres = request.genres ?: mood.genres, targetSize = request.targetSize ?: mood.targetSize, refreshHours = request.refreshHours ?: mood.refreshHours, ytEnabled = request.ytEnabled ?: mood.ytEnabled, seedPercent = request.seedPercent ?: mood.seedPercent, ) ?: notFound("Mood") call.respond(detail(updated, user, library)) } delete("/moods/{id}") { val user = call.requireApiUser(users) val mood = ownedMood(call.parameters["id"], user) MoodRepository.delete(mood.id, user.name) call.respond(HttpStatusCode.NoContent) } post("/moods/{id}/seeds") { val user = call.requireApiUser(users) val mood = ownedMood(call.parameters["id"], user) val request = call.receiveJson() val song = requireMusicSong(request.songId, user, library) val added = MoodRepository.addSeed( id = mood.id, owner = user.name, songId = song.id, origin = request.origin, ) val refreshed = MoodRepository.get(mood.id, user.name) ?: mood call.respond( HttpStatusCode.OK, AddToMoodResponse(mood = refreshed.toDto(), added = added), ) } delete("/moods/{id}/seeds/{songId}") { val user = call.requireApiUser(users) val mood = ownedMood(call.parameters["id"], user) val songId = call.parameters["songId"] ?: badRequest("Song id is required") MoodRepository.removeSeed(mood.id, user.name, songId) call.respond(HttpStatusCode.NoContent) } /** A short, unpersisted radio preview for the mood detail screen. */ get("/moods/{id}/preview") { val user = call.requireApiUser(users) val mood = ownedMood(call.parameters["id"], user) val limit = (call.request.queryParameters["limit"]?.toIntOrNull() ?: 20).coerceIn(1, 50) call.respond(SearchResponse(radioService.preview(mood, user, library, limit).map { it.toDto() })) } get("/moods/{id}/recommendations") { val user = call.requireApiUser(users) val mood = ownedMood(call.parameters["id"], user) call.respond(recommendations(mood, user, library)) } /** Runs a discovery pass now, bypassing the mood's refresh interval. */ post("/moods/{id}/recommendations/refresh") { val user = call.requireApiUser(users) val mood = ownedMood(call.parameters["id"], user) if (!mood.ytEnabled) conflict("YT discovery is disabled for this mood") val outcome = withContext(Dispatchers.IO) { discoveryService.refresh(mood, user, library, force = true) } outcome.error?.let { message -> throw ApiException(HttpStatusCode.BadGateway, "discovery_failed", message) } val refreshed = MoodRepository.get(mood.id, user.name) ?: mood call.respond(detail(refreshed, user, library)) } post("/moods/{id}/recommendations/{videoId}/accept") { val user = call.requireApiUser(users) val mood = ownedMood(call.parameters["id"], user) val videoId = call.parameters["videoId"] ?: badRequest("Video id is required") val recommendation = MoodRepository.recommendation(mood.id, videoId) ?: notFound("Recommendation") val matched = recommendation.matchedSongId?.let { songId -> LibraryRepository.song(songId, user.musicFolderIds(library), user.name) } val seedAdded = matched != null && MoodRepository.addSeed(mood.id, user.name, matched.id, "recommendation") val alreadyAccepted = recommendation.state == "accepted" MoodRepository.setRecommendationState(mood.id, videoId, "accepted") if (!alreadyAccepted) MoodRepository.incrementRecommendationAdds(mood.id, videoId) if (matched == null && downloadsEnabled) { DownloadRepository.enqueue( userName = user.name, moodId = mood.id, videoId = recommendation.videoId, title = recommendation.title, artist = recommendation.artist, ) } call.respond(decision(mood.id, videoId, user, library, seedAdded)) } post("/moods/{id}/recommendations/{videoId}/reject") { val user = call.requireApiUser(users) val mood = ownedMood(call.parameters["id"], user) val videoId = call.parameters["videoId"] ?: badRequest("Video id is required") MoodRepository.recommendation(mood.id, videoId) ?: notFound("Recommendation") MoodRepository.setRecommendationState(mood.id, videoId, "rejected") call.respond(decision(mood.id, videoId, user, library, seedAdded = false)) } } private fun ownedMood(id: String?, user: UserAccount): MoodRecord { if (id.isNullOrBlank()) badRequest("Mood id is required") return MoodRepository.get(id, user.name) ?: notFound("Mood") } private fun requireMusicSong(songId: String, user: UserAccount, library: LibraryConfig) = LibraryRepository.song(songId, user.musicFolderIds(library), user.name) ?: notFound("Song") private fun detail(mood: MoodRecord, user: UserAccount, library: LibraryConfig): MoodDetailDto { val folders = user.musicFolderIds(library) val seedRecords = MoodRepository.seeds(mood.id) val seedSongs = LibraryRepository .songsByIds(seedRecords.map { it.songId }, folders, user.name) .associateBy { it.id } val seeds = seedRecords.mapNotNull { seed -> seedSongs[seed.songId]?.let { seedDto(seed, it) } } return MoodDetailDto( mood = mood.toDto(), seeds = seeds, recommendations = recommendations(mood, user, library).recommendations, ) } private fun recommendations( mood: MoodRecord, user: UserAccount, library: LibraryConfig, ): RecommendationsResponse { val records = MoodRepository.recommendations(mood.id) val matchedIds = records.mapNotNull { it.matchedSongId } val matchedSongs = LibraryRepository .songsByIds(matchedIds, user.visibleFolderIds(library), user.name) .associateBy { it.id } val downloads = DownloadRepository.forMood(user.name, mood.id) return RecommendationsResponse( recommendations = records.map { record -> RecommendationDto( videoId = record.videoId, title = record.title, artist = record.artist, album = record.album, duration = record.duration, thumbnail = record.thumbnail, state = record.state, matchedSong = record.matchedSongId?.let { matchedSongs[it] }?.toDto(), timesAdded = record.timesAdded, firstSeen = record.firstSeen, lastSeen = record.lastSeen, download = downloads[record.videoId]?.let { job -> DownloadDto( state = job.state, attempts = job.attempts, error = job.error, updatedAt = job.updatedAt, ) }, ) }, ) } private fun decision( moodId: String, videoId: String, user: UserAccount, library: LibraryConfig, seedAdded: Boolean, ): RecommendationDecisionDto { val mood = MoodRepository.get(moodId, user.name) ?: notFound("Mood") val detail = detail(mood, user, library) val recommendation = detail.recommendations.firstOrNull { it.videoId == videoId } ?: notFound("Recommendation") return RecommendationDecisionDto( detail = detail, recommendation = recommendation, seedAdded = seedAdded, ) } @Serializable data class RecommendationsResponse(val recommendations: List)