// data/repository/UploadRepository.kt
package com.example.initiateaphonecallapp.data.repository

import android.content.Context
import android.net.Uri
import com.example.initiateaphonecallapp.data.model.CallRecord
import com.example.initiateaphonecallapp.data.model.CallRecordUploadRequest
import com.example.initiateaphonecallapp.data.network.RetrofitClient
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

class UploadRepository(val context: Context) {

    private val apiService = RetrofitClient.uploadFileApiService

    suspend fun uploadAudioFile(fileUri: Uri, fileName: String): String? {
        return try {
            println("📤 UploadRepository: 开始上传音频文件: $fileName")

            // 将 Uri 转换为 File
            val file = uriToFile(fileUri) ?: throw IllegalArgumentException("无法读取文件")

            // 创建请求体
            val requestFile = RequestBody.create(
                "audio/mpeg".toMediaTypeOrNull(), // 根据实际文件类型调整
                file
            )

            // 创建 MultipartBody.Part
            val filePart = MultipartBody.Part.createFormData(
                "file",
                fileName,
                requestFile
            )

            // 执行上传
            val response = apiService.uploadFile(filePart)

            if (response.isSuccessful && response.body()?.code == 200) {
                val fileUrl = response.body()?.url
                println("✅ UploadRepository: 文件上传成功, URL: $fileUrl")
                fileUrl
            } else {
                println("❌ UploadRepository: 文件上传失败: $1")
                null
            }
        } catch (e: Exception) {
            println("❌ UploadRepository: 文件上传异常: ${e.message}")
            e.printStackTrace()
            null
        }
    }

    suspend fun uploadCallRecord(callRecord: CallRecord, audioFileUrl: String? = null): Boolean {
        return try {
            println("📤 UploadRepository: 开始上传通话记录: ${callRecord.phoneNumber}")

            // 使用新的请求格式
            val request = CallRecordUploadRequest.fromCallRecord(callRecord, audioFileUrl)

            println("📤 UploadRepository: 上传数据:")
            println("   - phone: ${request.phone}")
            println("   - duration: ${request.duration}")
            println("   - status: ${request.status}")
            println("   - fileUrl: ${request.fileUrl}")
            println("   - createTime: ${request.createTime}")

            val response = apiService.uploadCallRecord(request)

            if (response.isSuccessful) {
                val responseBody = response.body()
                if (responseBody?.code == 200) {
                    println("✅ UploadRepository: 通话记录上传成功")
                    true
                } else {
                    val errorMsg = responseBody?.message ?: "上传失败"
                    println("❌ UploadRepository: 通话记录上传失败: $errorMsg (code: ${responseBody?.code})")
                    false
                }
            } else {
                val errorMsg = response.message()
                println("❌ UploadRepository: 通话记录上传HTTP错误: $errorMsg (code: ${response.code()})")
                false
            }
        } catch (e: Exception) {
            println("❌ UploadRepository: 通话记录上传异常: ${e.message}")
            e.printStackTrace()
            false
        }
    }

    // 上传通话记录和关联的音频文件
    suspend fun uploadCallRecordWithAudio(callRecord: CallRecord): Boolean {
        return try {
            var audioFileUrl: String? = null

            // 如果有音频文件，先上传音频文件
            callRecord.audioFileUri?.let { audioUri ->
                callRecord.audioFileName?.let { fileName ->
                    println("🎵 UploadRepository: 开始上传关联的音频文件")
                    audioFileUrl = uploadAudioFile(Uri.parse(audioUri), fileName)
                    if (audioFileUrl == null) {
                        println("⚠️ UploadRepository: 音频文件上传失败，但仍继续上传通话记录")
                    }
                }
            }

            // 然后上传通话记录
            uploadCallRecord(callRecord, audioFileUrl)

        } catch (e: Exception) {
            println("❌ UploadRepository: 完整上传过程异常: ${e.message}")
            false
        }
    }

    // 上传通话记录和关联的音频文件
    suspend fun uploadCallRecordOnly(callRecord: CallRecord): Boolean {
        return try {
            // 上传通话记录
            uploadCallRecord(callRecord)

        } catch (e: Exception) {
            println("❌ UploadRepository: 完整上传过程异常: ${e.message}")
            false
        }
    }

    // 将 Uri 转换为 File
    private fun uriToFile(uri: Uri): File? {
        return try {
            when (uri.scheme) {
                "file" -> File(uri.path!!)
                "content" -> {
                    // 处理 content:// URI
                    val inputStream = context.contentResolver.openInputStream(uri)
                    val tempFile = File.createTempFile("upload_audio", ".tmp", context.cacheDir)
                    inputStream?.use { input ->
                        tempFile.outputStream().use { output ->
                            input.copyTo(output)
                        }
                    }
                    tempFile
                }
                else -> null
            }
        } catch (e: Exception) {
            println("❌ UploadRepository: URI 转换文件失败: ${e.message}")
            null
        }
    }
}