import SwiftUI
import SwiftData

@main
struct HealthProbeApp: App {
    @State private var appSettings = AppSettings()

    var sharedModelContainer: ModelContainer = {
        do {
            let container = try createModelContainer()
            LegacySwiftDataBridge.configure(container: container)
            return container
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(appSettings)
        }
        .modelContainer(sharedModelContainer)
    }

    // SwiftData is not the forensic source of truth. Complete HealthKit samples
    // belong in the local archive store; these rows must remain rebuildable.
    private static func createModelContainer() throws -> ModelContainer {
        _ = try PrototypeStoreResetPolicy.applyIfNeeded()

        let fullSchema = Schema([
            HealthSnapshot.self, TypeCount.self,
        ])

        let appSupportURL = URL.applicationSupportDirectory
        try FileManager.default.createDirectory(at: appSupportURL, withIntermediateDirectories: true)
        let uiCacheStoreURL = appSupportURL.appending(path: "HealthProbeRecords.store")

        let uiCacheModels = Schema([
            HealthSnapshot.self, TypeCount.self,
        ])

        let uiCacheConfig = ModelConfiguration(
            "ui-cache",
            schema: uiCacheModels,
            url: uiCacheStoreURL,
            cloudKitDatabase: .none
        )

        do {
            return try ModelContainer(for: fullSchema, configurations: [uiCacheConfig])
        } catch {
            let candidates: [URL] = [
                uiCacheStoreURL,
                appSupportURL.appending(path: "HealthProbeRecords.store.shm"),
                appSupportURL.appending(path: "HealthProbeRecords.store.wal"),
                appSupportURL.appending(path: "HealthProbeCloud.store"),
                appSupportURL.appending(path: "HealthProbeCloud.store.shm"),
                appSupportURL.appending(path: "HealthProbeCloud.store.wal"),
                appSupportURL.appending(path: "HealthProbeLocal.store"),
                appSupportURL.appending(path: "HealthProbeLocal.store.shm"),
                appSupportURL.appending(path: "HealthProbeLocal.store.wal"),
            ]
            for url in candidates { try? FileManager.default.removeItem(at: url) }
            return try ModelContainer(for: fullSchema, configurations: [uiCacheConfig])
        }
    }
}
