//
//  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")
    
    
    //ai markDown 回答的string
    var AiMDString:String = ""

}


//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 }
            AiMDString = AiMDString + string
            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: .attributedText(kMDAttributedString(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)
            //保存服务器
        }
        
        
    }
}



import SwiftyMarkdown
private var md: SwiftyMarkdown = {
    let md = SwiftyMarkdown(string: "")
    md.setFontColorForAllStyles(with: .white)
    md.code.color = .red
    
    return md
}()

//字符串转成 markdown NSAttributedString
func kMDAttributedString(text:String) -> NSAttributedString{
    return md.attributedString(from: text)
}




