//
//  TSDBManager.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2025/6/10.
//


import RealmSwift
import ObjectMapper

// 1. 定义历史记录类型枚举
enum TSDBHistoryType: String,CaseIterable {
    case aiList = "kDBAIList"
}


//MARK: TSDBAIChatList - 用于存储会话及消息列表
class TSDBHistory: Object {
    @Persisted(primaryKey: true) var primaryKey: String = ""
    @Persisted var listModels = List<TSDBActionInfoModel>()
    
    var type: TSDBHistoryType {
        get { TSDBHistoryType(rawValue: primaryKey) ?? .aiList }
        set { primaryKey = newValue.rawValue }
    }
    
    convenience init(type: TSDBHistoryType) {
        self.init()
        self.primaryKey = type.rawValue
    }
    

    func getModelList() -> [TSActionInfoModel] {
        var msgModel:[TSActionInfoModel] = []
        for msgDBModel in listModels {
            msgModel.append(msgDBModel.getModel())
        }
        return msgModel
    }
    
    
    func getModelList(completion:@escaping ([TSActionInfoModel])->Void){
        let frozenList = self.listModels.freeze()
        DispatchQueue.global(qos: .userInitiated).async {
            var msgModel:[TSActionInfoModel] = []
            for msgDBModel in frozenList {
                msgModel.append(msgDBModel.getModel())
            }
            DispatchQueue.main.async {
                completion(msgModel)
            }
        }
    }
    
    func getModelList(count:Int) -> [TSActionInfoModel] {
        let listModels = Array(listModels.prefix(count))
        var msgModel:[TSActionInfoModel] = []
        for msgDBModel in listModels {
            msgModel.append(msgDBModel.getModel())
        }
        return msgModel
    }
    
    func deleteAll() {

        for index in listModels.indices {
            deleteResources(index: index)
        }

        TSRMShared.writeThread { realm in
            listModels.removeAll()
            realm.delete(listModels)
        }
    }
    
    func deleteListModel(id:Int) {
        if let index = listModels.firstIndex(where: { $0.id == id }) {
            deleteListModel(index: index)
        }
    }
    
    func deleteListModel(uuid:String) {
        if let index = listModels.firstIndex(where: { $0.uuid == uuid }) {
            deleteListModel(index: index)
        }
    }
    
    func deleteListModel(index:Int) {
        TSRMShared.writeThread { realm in
            let model = listModels[safe: index]
            deleteResources(index:index)
            listModels.remove(at: index)
            if let model = model {
                realm.delete(model)
            }
            
            debugPrint("listModels.remove(at: \(index))")
        }
    }

    func deleteResources(index:Int) {
        if let model = listModels[safe: index] {
            model.deleteResources()
        }
    }
    
    func updateData(_ actionInfoModel:TSActionInfoModel,uuid:String? = nil){
        let dbModel = TSDBActionInfoModel.createDBModel(actionInfoModel: actionInfoModel)
            let replaceUUID = uuid ?? dbModel.uuid
            let frozenList = self.listModels.freeze()
            if let index = frozenList.firstIndex(where: { $0.uuid == replaceUUID }) {
                dePrint("updateData 替换 \(dbModel)")
                TSRMShared.writeThread { realm in
                    listModels[index] = dbModel// 如果找到，替换该元素
                }
            } else {
                TSRMShared.writeThread { realm in
                    dePrint("updateData 插入 \(dbModel)")
                    listModels.insert(dbModel, at: 0)// 如果没有找到，添加到末尾
                }
            }
    }
    
    func updateDatas(_ actionInfoModels:[TSActionInfoModel]){
        for actionInfoModel in actionInfoModels {
            updateData(actionInfoModel)
        }
    }

    
    func addDatas(_ actionInfoModels:[TSActionInfoModel]){
        for actionInfoModel in actionInfoModels {
            let dbModel = TSDBActionInfoModel.createDBModel(actionInfoModel: actionInfoModel)
            TSRMShared.writeThread { realm in
                listModels.append(dbModel)
            }
        }
    }
}
extension TSDBHistory {
    
    //按照日期分类数据
//    static func getGroupedModelsLazily(completion:@escaping ([(date: Date, models: Results<TSDBActionInfoModel>)])->Void){
//
//        let calendar = Calendar.current
//        
//        DispatchQueue.global(qos: .userInitiated).async {
//            let realm = TSRMShared.realm
//            // 1. 先获取所有不重复的日期
//            let uniqueDates = getUniqueDatesForTypeZero(in: realm)
//            
//            // 2. 为每个日期创建惰性查询
//            let results = uniqueDates.map { date in
//                let start = calendar.startOfDay(for: date)
//                let end = calendar.date(byAdding: .day, value: 1, to: start)!
//                
//                let models = realm.objects(TSDBActionInfoModel.self)
//                    .filter("modelType == 0 AND createdAt >= %@ AND createdAt < %@", start, end)
//                    .sorted(byKeyPath: "createdAt", ascending: false)
//                    .freeze()
//                return (date, models)
//            }
//            
//            kMainAsync {
//                completion(results)
//            }
//            
//        }
//    }
    
    //按照日期分类数据
    static func getGroupedModelsLazily() -> [(date: Date, models: Results<TSDBActionInfoModel>)] {
        let realm = TSRMShared.realm
        let calendar = Calendar.current
        
        // 1. 先获取所有不重复的日期
        let uniqueDates = getUniqueDatesForTypeZero(in: realm)
        
        // 2. 为每个日期创建惰性查询
        return uniqueDates.map { date in
              let start = calendar.startOfDay(for: date)
              let end = calendar.date(byAdding: .day, value: 1, to: start)!
              
              let models = realm.objects(TSDBActionInfoModel.self)
                  .filter("modelType == 0 AND createdAt >= %@ AND createdAt < %@", start, end)
                  .sorted(byKeyPath: "createdAt", ascending: false)
            return (date, models)
          }
    }

    private static func getUniqueDatesForTypeZero(in realm: Realm) -> [Date] {
        let calendar = Calendar.current
        var dates = Set<Date>()
        
        realm.objects(TSDBActionInfoModel.self)
            .filter("modelType == 0")
            .forEach { model in
                dates.insert(calendar.startOfDay(for: model.createdAt))
            }
        
        return Array(dates).sorted(by: >)
    }
    
    //获取按照时间所有成功的历史记录
    static func getAllSunccessData() -> Results<TSDBActionInfoModel> {
        let realm = TSRMShared.realm
        let models = realm.objects(TSDBActionInfoModel.self)
              .filter("status == 'success'")
              .sorted(byKeyPath: "createdAt", ascending: false)
        return  models
          
    }
    
}
extension TSRealmManager {
    func getDBHistory(type:TSDBHistoryType) -> TSDBHistory {
        let predicate = NSPredicate(format: "primaryKey == %@",type.rawValue)
        let historys = TSRMShared.realm.objects(TSDBHistory.self).filter(predicate)
        if let history = historys.first {
            return history
        }else {
            let dbHistory = TSDBHistory(type: type)
            TSRMShared.update(dbHistory)
            return dbHistory
        }
    }
    
    func createExampleModel(id:Int,oldImageName:String,newImageName:String,generateStyle:TSGeneratorStyle)->TSActionInfoModel{
        let model = TSActionInfoModel()
        model.id = id
        model.modelType = .example
        model.request.prompt = "Example"
        model.request.inputText = "Example"
        model.request.width = 330
        model.request.height = 440
        model.request.imageUrl = oldImageName
        model.response.resultUrl = newImageName
        model.status = "success"
        model.request.generatorStyle = generateStyle
        return model
    }
    

    var aiListDB:TSDBHistory {
        let history = getDBHistory(type: TSDBHistoryType.aiList)
//        if history.listModels.count == 0,UserDefaults.standard.string(forKey: "insertAIListExampleData") == nil {
//            let id = Date.timestampInt
//            history.updateDatas([
//                createExampleModel(id:id+1, oldImageName: "ailist_example_image_old_1", newImageName: "ailist_example_image_new_1",generateStyle:.ptp),
//                createExampleModel(id:id+2, oldImageName: "ailist_example_image_old_0", newImageName: "ailist_example_image_new_0",generateStyle:.ptp)
//            ])
//            UserDefaults.standard.set("1", forKey: "insertAIListExampleData")
//            UserDefaults.standard.synchronize()
//        }
        return history
    }
    
}
