import Foundation import Observation import WatchConnectivity @MainActor @Observable final class WatchConnectivityService: NSObject, WCSessionDelegate { static let shared = WatchConnectivityService() private(set) var profile: UserProfile? private(set) var statusMessage: String = "" private override init() { super.init() activateIfSupported() loadCurrentContext() } private func activateIfSupported() { guard WCSession.isSupported() else { statusMessage = "WatchConnectivity not supported" return } let session = WCSession.default session.delegate = self session.activate() } private func loadCurrentContext() { guard WCSession.isSupported() else { return } updateProfile(from: WCSession.default.applicationContext) } private func updateProfile(from context: [String: Any]) { guard let data = context[UserProfile.storageKeyName] as? Data else { statusMessage = "No profile received" return } do { profile = try JSONDecoder().decode(UserProfile.self, from: data) statusMessage = "Profile synced" } catch { statusMessage = "Failed to decode profile" } } func session( _ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error? ) { loadCurrentContext() } func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) { updateProfile(from: applicationContext) } }