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



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:StreamPostRequest?
    
    let kAIUser = TSChatUser(senderId: "000", displayName: "AI")
    let kUserSender = TSChatUser(senderId: "001", displayName: "001")
}


//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
        ]
        streamRequest = TSNetworkShared.postStream(urlType: .chat,parameters: parameters) { string in
            streamHandler(string)
        } completion: { result in
            switch result {
            case .success(let data):
                completion(data,nil)
            case .failure(let error):
                completion(nil,error)
            }
        }
    }
    
    func stopAiGenerate () {
        streamRequest?.stopRequest()
    }
}

//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\n📧 Composing high-quality emails  \n🇺🇸 Facilitating language learning  \n📑 Assisting in your studies  \n💡 Brainstorming ideas and much more!"
            let msg = TSChatMessage(kind: .text(aiString), user: kAIUser, messageId: "", date: Date())
            
            return [msg]
        }
    }
    
//    func updateMessage(msgModel:TSChatMessage){
//        kExecuteOnMainThread {
//            //保存数据库
//            self.dbAIChatList.updateMessage(msgModel: msgModel)
//            //保存服务器
//        }
//    }
   
    
    func updateMessages(msgModels:[TSChatMessage]){
        kExecuteOnMainThread {
            //保存数据库
            self.dbAIChatList.updateMessages(msgModels: msgModels)
            //保存服务器
        }
        
        
    }
}
