import SwiftUI
import SwiftData

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

    var sharedModelContainer: ModelContainer = {
        destroyAllStoresAndRecreate()
        do {
            return try createModelContainer()
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()

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

    // Completely wipes all SwiftData stores and recreates fresh directory structure.
    // This prevents schema corruption from legacy data by starting completely clean.
    private static func destroyAllStoresAndRecreate() {
        let appSupportURL = URL.applicationSupportDirectory

        // Remove the entire Application Support directory
        try? FileManager.default.removeItem(at: appSupportURL)

        // Recreate it fresh
        try? FileManager.default.createDirectory(at: appSupportURL, withIntermediateDirectories: true)
    }

    // Two separate ModelConfiguration instances:
    //   cloudKitConfig — CloudKit-enabled for audit data; OperationLog intentionally excluded
    //   localConfig    — local-only for OperationLog audit trail; never synced
    //
    // ⚠️ DeviceProfile is kept local-only (not synced to CloudKit) since it's device-specific
    //    cosmetic data (name, color tag) that should not cross devices.
    private static func createModelContainer() throws -> ModelContainer {
        // TEMPORARY: Use in-memory storage to debug SwiftData schema issues
        // Once working, switch to disk-based storage below
        let fullSchema = Schema([
            HealthSnapshot.self, TypeCount.self, YearlyCount.self,
            SnapshotDelta.self, TypeDelta.self, AnomalyRecord.self,
            OperationLog.self, DeviceProfile.self,
        ])

        #if DEBUG
        // In-memory for development/testing (no persistence, clears on app relaunch)
        return try ModelContainer(for: fullSchema, configurations: [
            ModelConfiguration(schema: fullSchema, isStoredInMemoryOnly: true)
        ])
        #else
        // Disk-based for production
        let appSupportURL = URL.applicationSupportDirectory
        try FileManager.default.createDirectory(at: appSupportURL, withIntermediateDirectories: true)

        let cloudKitModels = Schema([
            HealthSnapshot.self, TypeCount.self, YearlyCount.self,
            SnapshotDelta.self, TypeDelta.self, AnomalyRecord.self,
        ])
        let localModels = Schema([OperationLog.self, DeviceProfile.self])

        let cloudConfig = ModelConfiguration(
            "cloud",
            schema: cloudKitModels,
            url: appSupportURL.appending(path: "HealthProbeCloud.store"),
            cloudKitDatabase: .none
        )
        let localConfig = ModelConfiguration(
            "local",
            schema: localModels,
            url: appSupportURL.appending(path: "HealthProbeLocal.store"),
            cloudKitDatabase: .none
        )

        do {
            return try ModelContainer(for: fullSchema, configurations: [cloudConfig, localConfig])
        } catch {
            let candidates: [URL] = [
                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: [cloudConfig, localConfig])
        }
        #endif
    }
}
