import Foundation
import WatchKit

// `@WKApplicationDelegateAdaptor`-friendly delegate. SwiftUI watchOS
// apps don't get a built-in hook for `WKApplicationRefreshBackgroundTask`
// — that lives on `WKApplicationDelegate.handle(_:)`. Phase C of the
// watch plan needs this hook to fire `BackgroundRefresh.runOnce()`
// when the OS wakes the watch app for a scheduled refresh.
//
// Each task instance must be marked completed within the time budget
// the OS gave us (otherwise the task is killed and the watch app's
// future budget shrinks). `setTaskCompletedWithSnapshot(false)`
// declines the optional UI snapshot — the complication's reload is
// the user-visible signal we care about, not the watch app's UI
// (which is almost never on screen during a background refresh).

final class WatchAppDelegate: NSObject, WKApplicationDelegate {
    func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
        for task in backgroundTasks {
            switch task {
            case let refresh as WKApplicationRefreshBackgroundTask:
                Task {
                    await BackgroundRefresh.runOnce()
                    await MainActor.run { BackgroundRefresh.scheduleNext() }
                    refresh.setTaskCompletedWithSnapshot(false)
                }
            default:
                // Other refresh types (URLSession, snapshot, etc.) aren't
                // produced by this app today; complete them immediately
                // so the OS doesn't think the app stalled.
                task.setTaskCompletedWithSnapshot(false)
            }
        }
    }

    /// Legacy delivery path for `widgetURL` taps on watchOS — the
    /// SwiftUI `.onContinueUserActivity` modifier in
    /// `HalflightWatchApp` is the primary handler, but Apple's
    /// documentation across watchOS revisions ambiguously routes
    /// widget activations through `WKApplicationDelegate` instead.
    /// Posting through `NotificationCenter` lets `RootView` react
    /// regardless of which hook fires.
    func handle(_ userActivity: NSUserActivity) {
        if let url = userActivity.webpageURL {
            DeepLink.route(url)
        }
    }
}
