// zip 文件下载器
package com.example.myapplication.network

import android.content.Context
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.ResponseBody
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream

object FileDownloader {

    /**
     * 下载 zip 文件并保存到 app 专属目录
     * @param context 用来获取文件目录
     * @param remoteFileName 服务器上的文件名或完整URL，比如 "test.zip" 或 "https://example.com/files/test.zip"
     * @param localFileName 本地保存名字，比如 "test_local.zip"
     * @return 保存成功后返回 File，失败返回 null
     */
    suspend fun downloadZipFile(
        context: Context,
        remoteFileName: String,
        localFileName: String = remoteFileName
    ): File? = withContext(Dispatchers.IO) {
        val api = RetrofitClient.apiService
        try {
            val response = if (remoteFileName.startsWith("http")) {
                // 完整 URL 下载 - 使用 @Url 注解，Retrofit 会忽略 base URL
                api.downloadZipFromUrl(remoteFileName)
            } else {
                // 文件名下载
                api.downloadZip(remoteFileName)
            }
            if (!response.isSuccessful) {
                Log.e("Downloader", "download failed: code=${response.code()}")
                return@withContext null
            }

            val body = response.body() ?: run {
                Log.e("Downloader", "response body is null")
                return@withContext null
            }

            val dir = File(context.getExternalFilesDir(null), "Downloads")
            if (!dir.exists()) dir.mkdirs()

            val outFile = File(dir, localFileName)

            saveResponseBodyToFile(body, outFile)

            Log.d("Downloader", "file saved to: ${outFile.absolutePath}")
            return@withContext outFile

        } catch (e: Exception) {
            Log.e("Downloader", "download exception: ${e.message}", e)
            return@withContext null
        }
    }

    /**
     * 把 ResponseBody 写入文件
     */
    private fun saveResponseBodyToFile(body: ResponseBody, outFile: File) {
        var inputStream: InputStream? = null
        var outputStream: OutputStream? = null
        try {
            val buffer = ByteArray(8 * 1024)
            var downloadedBytes: Long = 0
            val totalBytes = body.contentLength()

            inputStream = body.byteStream()
            outputStream = FileOutputStream(outFile)

            while (true) {
                val read = inputStream.read(buffer)
                if (read == -1) break
                outputStream.write(buffer, 0, read)
                downloadedBytes += read

                // 需要的话可以在这里回调进度
                val progress = downloadedBytes * 100 / totalBytes
            }
            outputStream.flush()
        } finally {
            inputStream?.close()
            outputStream?.close()
        }
    }
}
