//
// WatchAppDelegate.swift
// Workouts Watch App
//
// Copyright 2025 Rouslan Zenetl. All Rights Reserved.
//

import SwiftUI
import WatchKit
import HealthKit

/// Bridges watchOS lifecycle into the workout session. When the phone starts a workout
/// it calls `startWatchApp(toHandle:)`; watchOS launches (or foregrounds) this app and
/// delivers the configuration to `handle(_:)`, where we start a session to claim
/// foreground runtime. The session manager is shared with the view tree via the
/// environment (see `WorkoutsWatchApp`).
@MainActor
final class WatchAppDelegate: NSObject, WKApplicationDelegate {
    let sessionManager = WorkoutSessionManager()

    func applicationDidFinishLaunching() {
        #if DEBUG
        // The screenshot harness renders fixed screens — don't pop the Health auth
        // dialog over them (it would also leak into App Store captures).
        if ScreenshotSeed.isActive { return }
        #endif
        sessionManager.requestAuthorization()
        // Re-adopt a session that outlived a crash or reboot — watchOS relaunches us
        // expecting this call; without it the session is orphaned and its workout lost.
        sessionManager.recover()
    }

    func handle(_ workoutConfiguration: HKWorkoutConfiguration) {
        sessionManager.start(with: workoutConfiguration)
    }
}
