package mg.dot.feufaro.data

import feufaro.composeapp.generated.resources.Res
import org.jetbrains.compose.resources.ExperimentalResourceApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import mg.dot.feufaro.FileRepository
import java.io.File

data class DrawerItem(
    val id: Int,
    val title: String,
    val contentTitle: String,
    val path: String
)

@Serializable
data class FeuIndex(
    val internalFeu: List<FeuItem>
)

@Serializable
data class FeuItem(
    val id: Int,
    val fileName: String,
    val title: String,
    val path: String
)

@OptIn(ExperimentalResourceApi::class)
suspend fun getCombinedList(fileRepository: FileRepository): List<DrawerItem> {
    val finalList = mutableListOf<DrawerItem>()

    try {
        val bytes = Res.readBytes("files/feuList.json")
        val index = Json.decodeFromString<FeuIndex>(bytes.decodeToString())
        finalList.addAll(index.internalFeu.map {
            DrawerItem(it.id, it.fileName.removeSuffix(".txt"), it.title, it.path)
        })
    } catch (e: Exception) {
        e.printStackTrace()
    }

    try {
        val folderPath = fileRepository.getAppPublicFolder()
        val directory = File(folderPath.absolutePath)

        if (directory.exists() && directory.isDirectory) {
            directory.listFiles { f -> f.extension == "txt" }?.forEachIndexed { i, file ->
                finalList.add(DrawerItem(
                    id = 50000 + i,
                    title = file.name.removeSuffix(".txt"),
                    contentTitle = extractTitle(file),
                    path = file.absolutePath
                ))
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

    return finalList
}

private fun extractTitle(content: String): String? {
    val regex = Regex("""\|t:([^|]+)""")
    return regex.find(content)?.groupValues?.get(1)?.trim()
}
private fun extractTitle(file: File): String {
    return try {
        file.useLines { lines ->
            val titleLine = lines.find { it.contains("|t:") }

            if (titleLine != null) {
                titleLine.substringAfter("|t:")
                    .substringBefore("|")
                    .trim()
            } else {
                file.nameWithoutExtension
            }
        }
    } catch (e: Exception) {
        file.nameWithoutExtension
    }
}