/*
 * Book's Story — free and open-source Material You eBook reader.
 * Copyright (C) 2024-2026 Acclorite
 * SPDX-License-Identifier: GPL-3.0-only
 */

package org.dueattendant149.bookshelf.data.repository

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.dueattendant149.bookshelf.core.CoverImage
import org.dueattendant149.bookshelf.core.data.ExtensionsData
import org.dueattendant149.bookshelf.data.local.room.BookDatabase
import org.dueattendant149.bookshelf.data.mapper.file.FileMapper
import org.dueattendant149.bookshelf.data.model.file.CachedFile
import org.dueattendant149.bookshelf.data.parser.cover.CoverParser
import org.dueattendant149.bookshelf.data.parser.file.FileParser
import org.dueattendant149.bookshelf.domain.model.file.File
import org.dueattendant149.bookshelf.domain.model.library.Book
import org.dueattendant149.bookshelf.domain.repository.FileSystemRepository
import org.dueattendant149.bookshelf.domain.service.FileProvider
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class FileSystemRepositoryImpl @Inject constructor(
    private val database: BookDatabase,
    private val fileMapper: FileMapper,
    private val fileParser: FileParser,
    private val coverParser: CoverParser,
    private val fileProvider: FileProvider
) : FileSystemRepository {

    override suspend fun searchFiles(query: String): Result<List<File>> {
        return withContext(Dispatchers.IO) {
            fileProvider.getStorageFiles().mapCatching { storages ->
                val existingFiles = database.bookDao.searchBooks("").map { it.filePath }

                storages.map { storage ->
                    storage.getFilesFromStorage(
                        query = query,
                        existingFiles = existingFiles
                    )
                }.flatten()
            }
        }
    }

    private fun CachedFile.isValid(
        query: String,
        existingFiles: List<String>
    ): Boolean {
        if (
            ExtensionsData.fileExtensions.none {
                name.endsWith(
                    it,
                    ignoreCase = true
                )
            }
        ) return false
        if (query.isNotBlank() && !name.contains(query.trim(), ignoreCase = true)) return false
        if (existingFiles.any { it.equals(path, ignoreCase = true) }) return false
        return true
    }

    private fun CachedFile.getFilesFromStorage(
        query: String,
        existingFiles: List<String>
    ): List<File> {
        val files = mutableListOf<File>()
        walk { cachedFile ->
            if (cachedFile.isValid(query, existingFiles)) {
                files.add(fileMapper.toFile(cachedFile))
            }
        }
        return files
    }

    override suspend fun getBookFromFile(file: File): Result<Pair<Book, CoverImage?>> =
        runCatching {
            withContext(Dispatchers.IO) {
                val cachedFile = fileMapper.toCachedFile(file)

                val book = fileParser.parse(
                    cachedFile = cachedFile
                ) ?: throw Exception("Could not parse ${file.name}.")
                val coverImage = coverParser.parse(cachedFile = cachedFile)

                return@withContext book to coverImage
            }
        }
}