//
//  TSAIChatVM.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/9.
//


import Alamofire
let kAIErrorString = "Server is busy, please try again later".localized
class TSAIChatVM {

    enum UIStype {
        case chat
        case history
    }
        
    lazy var dbAIChatList: TSDBAIChatList = {
        let dbAIChatList = TSDBAIChatList.getOneDB()
        return dbAIChatList
    }()

    var uiStyle:UIStype = UIStype.chat
    var streamRequest:Request?
    
    let kAIUser = TSChatUser(senderId: "000", displayName: "AI",idType: .aiRobot)
    let kUserSender = TSChatUser(senderId: "001", displayName: "001",idType: .user)
    
    
    //ai markDown 回答的string
    var AiMDString:String = ""
    // ai 思考的内容
    var AiThinkingString:String = ""
    
    
    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(handleAIStopRespondNotification(_:)), name: .kAIStopRespondNotification, object: nil)
    }
    
    @objc func handleAIStopRespondNotification(_ notification: Notification) {
//        if let userInfo = notification.userInfo, let boolValue = userInfo[kIsAIAnswering] as? Bool {
//        }
        stopAiGenerate()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}


//MARK: AI 聊天请求
extension TSAIChatVM {
    
    func sendChatMessage(
        message:String,
        streamHandler:@escaping (String) -> Void,
        completion: @escaping (Any?, Error?) -> Void
    ) {
        let parameters: [String: String] = [
            "sessionId": dbAIChatList.sessionId,
            "message": message
        ]

        AiMDString = ""
        streamRequest = TSNetworkShared.postStream(urlType: .chat,parameters: parameters) {[weak self] string in
            guard let self = self else { return }
            
            if AiMDString.count == 0 {
                //{"code":500,"message":"Server Error"}
                //如果错误,基本都是第一条就返回结果了,这里需要做下 code 判断,来确定接口
                if let dataDict = string.jsonDict() , let code = dataDict["code"] {
                    completion(nil,NSError(domain: dataDict.safeString(forKey: "message"), code: 0))
                    return
                }
            }
            
            AiMDString = AiMDString + string
            streamHandler(string)
        } completion: { result in
            switch result {
            case .success(let data):
                completion(data,nil)
            case .failure(let error):
                if case Alamofire.AFError.explicitlyCancelled = error {//主动取消的
                    completion("",nil)
                } else {
                    completion(nil,error)
                }
            }
        }
    }
    func stopAiGenerate () {
        streamRequest?.cancel()
    }
}

extension TSAIChatVM {
    
    func sendChatThinkingMessage(
        message:String,
        streamHandler:@escaping (String,String) -> Void,
        completion: @escaping (Any?, Error?) -> Void
    ) {
        let parameters: [String: String] = [
            "sessionId": dbAIChatList.sessionId,
            "message": message
        ]

        AiMDString = ""
        AiThinkingString = ""
        streamRequest = TSNetworkShared.postStream(urlType: .chatV2,parameters: parameters) {[weak self] string in
            guard let self = self else { return }

//            if AiMDString.count == 0 {
//                //{"code":500,"message":"Server Error"}
//                //如果错误,基本都是第一条就返回结果了,这里需要做下 code 判断,来确定接口
//                if let dataDict = string.jsonDict() , let code = dataDict["code"] {
//                    completion(nil,NSError(domain: dataDict.safeString(forKey: "message"), code: 0))
//                    return
//                }
//            }
            
            //{"type": "reason", "content": "思考"}\n{"type": "content", "content": "内容"}
            let jsonLines = string.components(separatedBy: "\n")
            for line in jsonLines {
                if !line.isEmpty, let jsonData = line.data(using: .utf8) {
                    do {
                        let json = try JSONSerialization.jsonObject(with: jsonData, options: [])
                        dePrint("Stream Received JSON:\(json)")
                        
                        guard let jsonDict = json as? [String:String] else {
                            return
                        }

                        let type = jsonDict.safeString(forKey: "type")
                        let content = jsonDict.safeString(forKey: "content")
                        if type == "reason"{
                            AiThinkingString = AiThinkingString + content
                        }else if type == "content"{
                            AiMDString = AiMDString + content
                        }
                        dePrint("streamHandler viewModel.AiThinkingString=\(AiThinkingString)")
                        dePrint("streamHandler viewModel.AiMDString=\(AiMDString)")
                        streamHandler(AiThinkingString,AiMDString)

                    } catch {
                        print("Stream Received JSON parsing error:", error)
                    }
                }
            }

        } completion: { result in
            switch result {
            case .success(let data):
                completion(data,nil)
            case .failure(let error):
                if case Alamofire.AFError.explicitlyCancelled = error {//主动取消的
                    completion("",nil)
                } else {
                    completion(nil,error)
                }
            }
        }
    }
    
}

//MARK: 数据存储
extension TSAIChatVM {
    
    func getHistoryChatMessage() -> [TSChatMessage] {
        if uiStyle == .history {
            return self.dbAIChatList.getMessageList()
        }else {
            let aiString = "I can tackle your questions, my skillset includes, but is not limited to:\n`📧 Composing high-quality emails`\n`🇺🇸 Facilitating language learning`\n`📑 Assisting in your studies`\n`💡Brainstorming ideas`\n`and much more!`"
            let msg = TSChatMessage(kind: .attributedText(kMDAttributedString(text: aiString)), user: kAIUser, messageId: "", date: Date())
            msg.messageType = .aiRobotWelcome
            msg.appendUIDict = [.topView:TSChatMessageUIBaseModel.creat(viewClass: "TSMSGAIDefaultHeaderView", msgModel: msg)]
            return [msg]
        }
    }
    
    func updateMessages(msgModels:[TSChatMessage]){
        kExecuteOnMainThread {
            //保存数据库
            self.dbAIChatList.updateMessages(msgModels: msgModels)
            //保存服务器
        }
    }
}
