import Foundation public struct UsageCache { public static let cacheURL: URL = { let dir = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".config/usage-tray", isDirectory: true) try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) return dir.appendingPathComponent("cache.json") }() private static var inMemoryCache: [String: ProviderUsage]? = nil public static func load() -> [String: ProviderUsage] { if let cached = inMemoryCache { return cached } guard let data = try? Data(contentsOf: cacheURL), let dict = try? JSONDecoder().decode([String: ProviderUsage].self, from: data) else { inMemoryCache = [:] return [:] } inMemoryCache = dict return dict } public static func save(providers: [ProviderUsage]) { var dict = load() var changed = false for p in providers where !p.windows.isEmpty || p.balance != nil { if dict[p.id] != p { dict[p.id] = p changed = true } } guard changed else { return } inMemoryCache = dict if let data = try? JSONEncoder().encode(dict) { try? data.write(to: cacheURL, options: .atomic) } } }