package mg.dot.feufaro

import android.content.Context
import android.net.Uri
import feufaro.composeapp.generated.resources.Res
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream

class AndroidFileRepository(private val context: Context) : FileRepository {

    override suspend fun getOutputStream(filePath: String): OutputStream {
        // On utilise getExternalFilesDir pour le debug (accessible via ADB/Vim)
        val folder = context.getExternalFilesDir(null)
        val outputFile = File(folder, filePath)

        // On s'assure que le dossier existe
        outputFile.parentFile?.mkdirs()

        return FileOutputStream(outputFile)
    }

    override suspend fun saveFile(filePath: String, data: ByteArray) {
        val folder = context.getExternalFilesDir(null)
        println("Save to xx27 $folder $filePath")
        File(folder, filePath).writeBytes(data)
    }
    override suspend fun readFileLines(filePath: String): List<String> = withContext(Dispatchers.IO) {
        try {
            when {
                filePath.startsWith("content://") -> {
                    val uri = Uri.parse(filePath)
                    val inputStream = context.contentResolver.openInputStream(uri)
                        ?: throw IOException("Impossible d'ouvrir : $filePath")
                    inputStream.bufferedReader(Charsets.UTF_8).readLines()
                }
                filePath.startsWith("assets://") -> {
                    readAssetFileLines(filePath)
                }

                else -> {
                    File(filePath).readLines()
                }
            }
        } catch (e: IOException) {
            throw IOException("Failed to read file or asset '$filePath'")
        }
    }
    override suspend fun readFileContent(filePath: String): String = withContext(Dispatchers.IO) {
        val lines = readFileLines(filePath)
        lines.joinToString("\n") { it }
    }
    private suspend fun readAssetFileLines(assetFileName: String): List<String> {
        return try {
            Res.readBytes("files/"+assetFileName.removePrefix("assets://")).decodeToString().split("\n")
        } catch (e: IOException) {
            println("Could not read /"+assetFileName.removePrefix("assets://"))
            throw IOException("Could not read asset file: $assetFileName", e)
        }
    }

    override fun getFileName(shortName: String): String {
        val folder = context.getExternalFilesDir(null)
        return "$folder/$shortName"
    }
    // Dans androidMain / AndroidFileRepository.kt
    /*override suspend fun readFileBytes(filePath: String): ByteArray = withContext(Dispatchers.IO) {
        val folder = context.getExternalFilesDir(null)
        val file = File(folder, filePath)
        if (!file.exists()) throw IOException("File not found: ${file.absolutePath}")
        file.readBytes()
    }*/

}