import SwiftUI
import SwiftData

@main
struct FlightsApp: App {
    let database: AirportDatabase
    let loadService: AirlineLoadService
    let routeExplorer = RouteExplorerClient()
    let openSky = OpenSkyClient()
    let fr24 = FR24Client()
    let flightAware: FlightAwareScheduleClient

    /// SwiftData container for the personal flight log. Uses CloudKit
    /// private DB so the log syncs across the user's devices. Falls
    /// back to a local-only store if CloudKit isn't provisioned (which
    /// keeps the app functional during initial dev / first deploy).
    let modelContainer: ModelContainer

    init() {
        // Initialize the diagnostic logger eagerly so the session boot
        // header (device, OS, app version, locale, UA) lands in the log
        // file the instant the app launches — before any user action.
        // Makes shared dumps self-describing even when nothing else has
        // been touched.
        _ = DiagnosticLogger.shared

        let db = AirportDatabase()
        self.database = db
        self.loadService = AirlineLoadService(airportDatabase: db)
        self.flightAware = FlightAwareScheduleClient(database: db)

        // Pre-load the bundled airline + aircraft databases on a background
        // thread. Both are large enough (200KB and 1.5MB) to noticeably
        // jank the UI if we wait until first access on the Live tab.
        AircraftRegistry.shared.preload()
        AircraftDatabase.shared.preload()

        // SwiftData store. Local only — CloudKit sync is disabled
        // until the iCloud cap is provisioned for the bundle id. The
        // disk store may be incompatible if a prior build wrote with
        // a different schema; we fall back to in-memory in that case
        // so the app still launches (history won't persist across
        // restarts, but the user can fix it by deleting + reinstalling
        // once a stable schema is on disk).
        let schema = Schema([LoggedFlight.self, AirframeMetadata.self])
        let localConfig = ModelConfiguration(
            schema: schema,
            isStoredInMemoryOnly: false,
            cloudKitDatabase: .none
        )
        if let container = try? ModelContainer(for: schema, configurations: [localConfig]) {
            self.modelContainer = container
        } else {
            let memConfig = ModelConfiguration(
                schema: schema,
                isStoredInMemoryOnly: true,
                cloudKitDatabase: .none
            )
            self.modelContainer = try! ModelContainer(for: schema, configurations: [memConfig])
        }
    }

    var body: some Scene {
        WindowGroup {
            // Debug shortcut: launch the app with `-TurnstileDebug` to
            // skip RootView and open straight into ``TurnstileDebugView``.
            // Lets the harness drive the gate-sheet investigation without
            // navigating tabs. Production builds never pass this flag.
            if CommandLine.arguments.contains("-TurnstileDebug") {
                NavigationStack {
                    TurnstileDebugView()
                }
            } else {
                RootView(
                    database: database,
                    loadService: loadService,
                    routeExplorer: routeExplorer,
                    openSky: openSky,
                    fr24: fr24,
                    flightAware: flightAware
                )
            }
        }
        .modelContainer(modelContainer)
    }
}
