//
//  AppDictManager.swift

//
//  Created by Leon on 2025/7/29.
//

import Foundation

class AppDictManager{
    static let shared = AppDictManager()
    
    // 缓存键
    private enum CacheKey: String {
        case aiDict = "aiDict"
        case giftDict = "giftDict"
    }
    
    var aiDict: AIDictInfo?
    var aiDictApiLoading: Bool = false
    
    var gifts: [GiftDictModel]?
    var giftDictApiLoading: Bool = false
    
    var chatModels : [AIChatModel]?
    
    init() {
        // 请求最新数据
        loadAIDict(block: nil)
        loadGiftDict(block: nil)
        loadChatModelDict(block: nil)
        // 🔥加载缓存数据
        loadCachedData()
  
        NotificationCenter.default.addObserver(self, selector: #selector(receiveNetStatusChanged(_:)), name: AppNotificationName.networkChanged.notificationName, object: nil)
    }
    
    func loadRequiredDict(){
        // init() called load
    }
    
    // MARK: - Public
    
    func getGiftModelBy(giftId: Int, completion: ((GiftDictModel?) -> Void)?){
        if let giftsObjs = gifts, giftsObjs.count > 0 {
            // return where giftId =  GiftDictModel.id
            for gift in giftsObjs {
                if gift.id == giftId {
                    completion?(gift)
                    return
                }
            }
        }
        loadGiftDict { ok in
            if ok {
                self.getGiftModelBy(giftId: giftId, completion: completion)
            }else{
                completion?(nil)
            }
        }
    }
    
    // MARK: - 缓存相关方法
    
    /// 加载缓存数据
    private func loadCachedData() {
        // 加载AI字典缓存
        if let cachedAIDict = AppCache.fetchCache(key: CacheKey.aiDict.rawValue, type: AIDictInfo.self) {
            aiDict = cachedAIDict
            dlog("✅ 从缓存加载AI字典成功")
        }
        
        // 加载礼物字典缓存
        if let cachedGiftDict = AppCache.fetchCache(key: CacheKey.giftDict.rawValue, type: [GiftDictModel].self) {
            gifts = cachedGiftDict
            dlog("✅ 从缓存加载礼物字典成功")
        }
    }
    
    /// 缓存AI字典
    private func cacheAIDict(_ dict: AIDictInfo) {
        AppCache.cache(key: CacheKey.aiDict.rawValue, value: dict)
    }
    
    /// 缓存礼物字典
    private func cacheGiftDict(_ dict: [GiftDictModel]) {
        AppCache.cache(key: CacheKey.giftDict.rawValue, value: dict)
    }
    
    // MARK: - 网络请求方法
    
    func loadAIDict(block: ((_ ok: Bool) -> Void)?){
        if aiDictApiLoading{
            block?(false)
            return
        }
        
        // 如果已有数据，直接返回成功
        if aiDict != nil {
            block?(true)
            return
        }
        
        aiDictApiLoading = true
        CommonProvider.request(.getAIDict, modelType: AIDictInfo.self) {[weak self] result in
            self?.aiDictApiLoading = false
            switch result {
            case .success(let success):
                self?.aiDict = success
                // 缓存数据
                if let dict = success {
                    self?.cacheAIDict(dict)
                }
                if APIConfig.environment == .test {
                    dlog("AI Dict: \(CodableHelper.encode(success ?? AIDictInfo()) ?? Data())")
                }
                block?(true)
            case .failure(_):
                block?(false)
            }
        }
    }
    
    func loadGiftDict(block: ((_ ok: Bool) -> Void)?){
        if giftDictApiLoading {
            block?(false)
            return
        }
        
        // 如果已有数据，直接返回成功
        if gifts != nil {
            block?(true)
            return
        }
        
        giftDictApiLoading = true
        var params = [String:Any]()
        var pages = [String:Any]()
        pages.updateValue(1, forKey: "pn")
        pages.updateValue(200, forKey: "ps")
        params.updateValue(pages, forKey: "page")
        CommonProvider.request(.getGiftDict(params: params), modelType: ResponseContentPageData<GiftDictModel>.self) {[weak self] result in
            self?.giftDictApiLoading = false
            switch result {
            case .success(let model):
                if let datas = model?.datas{
                    // dlog("所有的gift: \(datas)")
                    self?.gifts = datas
                    // 缓存数据
                    self?.cacheGiftDict(datas)
                }
                block?(true)
            case .failure:
                block?(false)
            }
        }
    }
    
    func loadChatModelDict(block: ((_ ok: Bool) -> Void)?){
        CommonProvider.request(.getChatModelDict, modelType: [AIChatModel].self) {[weak self] result in
            switch result {
            case .success(let model):
                self?.chatModels = model
                block?(true)
            case .failure:
                block?(false)
            }
        }
    }
    
    // MARK: - Noti
    
    @objc private func receiveNetStatusChanged(_ notification: Notification) {
        let status = LTNetworkManage.ltManage.status
        if status != .notReachable {
            if aiDict == nil {
                loadAIDict(block: nil)
            }
            if (gifts ?? []).count == 0 {
                loadGiftDict(block: nil)
            }
            if (chatModels ?? []).count == 0 {
                loadChatModelDict(block: nil)
            }
        }
    }
    
    // MARK: - 公共方法
    
    /// 清除所有字典缓存
    func clearCache() {
        AppCache.removeCache(key: CacheKey.aiDict.rawValue)
        AppCache.removeCache(key: CacheKey.giftDict.rawValue)
        aiDict = nil
        gifts = nil
        dlog("✅ 清除字典缓存成功")
    }
    
    /// 强制刷新所有字典数据
    func refreshAllDicts(completion: @escaping (Bool) -> Void) {
        clearCache()
        loadAIDict { aiSuccess in
            self.loadGiftDict { giftSuccess in
                completion(aiSuccess && giftSuccess)
            }
        }
    }
}
