package com.stand.standapp.ui.chat.repo

import com.stand.standapp.AppConfig
import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import timber.log.Timber
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.concurrent.TimeUnit

class AiChatRepository {
    private val client = OkHttpClient.Builder()
        .readTimeout(0, TimeUnit.MILLISECONDS) // 禁用读取超时以适配 SSE 流
        .build()

    fun streamChat(context: Context, message: String, token: String, historyJson: String): Flow<String> = callbackFlow {
        // 1. 从 AppConfig 中动态读取当前服务器基准地址，完美适配真实网关
        val serverUrl = AppConfig.getServerUrl(context)
        val requestUrl = "$serverUrl/api/chat/stream"

        val jsonRequestBody = if (historyJson.isNotBlank()) {
            """{"message": "$message", "history": $historyJson}"""
        } else {
            """{"message": "$message"}"""
        }

        val request = Request.Builder()
            .url(requestUrl)
            .post(jsonRequestBody.toRequestBody("application/json".toMediaType()))
            .header("Authorization", "Bearer $token")
            .header("Accept", "text/event-stream")
            .build()

        val call = client.newCall(request)

        // 2. 在 IO 线程池中执行网络流式读取，杜绝 EventSource 找不到依赖的编译期痛点
        val job = CoroutineScope(Dispatchers.IO).launch {
            try {
                call.execute().use { response ->
                    if (!response.isSuccessful) {
                        trySend("[请求失败: 状态码 ${response.code}]")
                        close()
                        return@launch
                    }

                    val body = response.body
                    if (body == null) {
                        trySend("[空响应]")
                        close()
                        return@launch
                    }

                    // 3. 逐行读取后端流式推送字符，手动解析 data 属性
                    // 👈 添加行缓冲，确保完整的markdown行被发送
                    BufferedReader(InputStreamReader(body.byteStream(), Charsets.UTF_8)).use { reader ->
                        var line: String?
                        var lastcontent =  "";
                        while (reader.readLine().also { line = it } != null) {
                            val curLine = line ?: continue
                            if (curLine.startsWith("data:")) {
                                val content = curLine.substring(5)
//                                Timber.d("内容111111111："+content)
                                if (content.contains("|") && lastcontent.contains("|")){
                                    trySend("\n")
//                                    Timber.d("1发送11111111111：换行")
                                    trySend(content)
//                                    Timber.d("2发送11111111111："+content)
                                }else if (content.length==0) {
                                    // 空data行表示换行
                                    trySend("\n")
//                                    Timber.d("3发送11111111111：换行")
                                }else {
                                    trySend(content)
//                                    Timber.d("4发送11111111111："+content)
                                }
                                lastcontent = content;
                            }
                        }
                    }
                }
                close()
            } catch (e: Exception) {
                Timber.e(e, "SSE Stream error")
                trySend("\n[连接异常: ${e.message}]")
                close(e)
            }
        }

        awaitClose {
            call.cancel()
            job.cancel()
        }
    }
}
