import SwiftUI
import SwiftData

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

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

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

    // Removes all SwiftData stores to ensure clean schema.
    // Called on every app launch to prevent schema corruption from old models.
    private static func destroyLegacyStoreIfNeeded() {
        let appSupportURL = URL.applicationSupportDirectory
        let legacyFiles = [
            "HealthProbe.store",
            "HealthProbeCloud.store",
            "HealthProbeLocal.store",
            "HealthProbe.store-journal", // SQLite journal
            "default.store",
        ]
        for fileName in legacyFiles {
            let storeURL = appSupportURL.appending(path: fileName)
            let candidates = [
                storeURL,
                storeURL.appendingPathExtension("shm"),
                storeURL.appendingPathExtension("wal"),
                storeURL.appendingPathExtension("journal"),
            ]
            for url in candidates {
                try? FileManager.default.removeItem(at: url)
            }
        }
        // Also try to remove the entire Application Support directory metadata
        if let metadataURL = try? FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
            let storeDescriptionURL = metadataURL.appending(path: ".com.apple.mobile_container_manager.metadata.plist")
            try? FileManager.default.removeItem(at: storeDescriptionURL)
        }
    }

    // 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 {
        let cloudKitModels = Schema([
            HealthSnapshot.self,
            TypeCount.self,
            YearlyCount.self,
            SnapshotDelta.self,
            TypeDelta.self,
            AnomalyRecord.self,
        ])
        let localModels = Schema([
            OperationLog.self,
            DeviceProfile.self,
        ])

        let appSupportURL = URL.applicationSupportDirectory
        try FileManager.default.createDirectory(at: appSupportURL, withIntermediateDirectories: true)

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

        // Use local storage for now. CloudKit sync requires the container to be
        // set up in Apple Developer Portal first. To enable CloudKit:
        // 1. Create a CloudKit container "iCloud.ro.xdev.HealthProbe" in Developer Portal
        // 2. Enable iCloud capability for this app
        // 3. Replace .none with .private("iCloud.ro.xdev.HealthProbe")
        cloudConfig = ModelConfiguration(
            "cloud",
            schema: cloudKitModels,
            url: appSupportURL.appending(path: "HealthProbeCloud.store"),
            cloudKitDatabase: .none
        )

        let fullSchema = Schema([
            HealthSnapshot.self, TypeCount.self, YearlyCount.self,
            SnapshotDelta.self, TypeDelta.self, AnomalyRecord.self,
            OperationLog.self, DeviceProfile.self,
        ])
        do {
            return try ModelContainer(for: fullSchema, configurations: [cloudConfig, localConfig])
        } catch {
            // Recover from schema migration failures by removing the stores and retrying once
            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])
        }
    }
}
