import Foundation
import KeychainSwift

class DeviceIDManager {
    static let shared = DeviceIDManager()
    private let keychain = KeychainSwift()
    private let deviceIDKey = "com.speakeasy.ai.ap.device_unique_id"
    
    private init() {}
    
    var deviceID: String {
        // 尝试从 Keychain 获取已存储的 UUID
        if let savedID = keychain.get(deviceIDKey),savedID.count > 0{
            return savedID
        }
        // 如果没有存储过，生成新的 UUID 并保存
        let newID = UUID().uuidString
        keychain.set(newID, forKey: deviceIDKey)
        return newID
    }
}

extension Dictionary where Key == String {
    func toJSONString() -> String? {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: [])
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                return jsonString
            }
        } catch {
            print("JSON转换错误: \(error)")
        }
        return nil
    }
}
