import SwiftUI
import SwiftData

@main
struct BusinessCardApp: App {
    private let modelContainer: ModelContainer
    @State private var appState: AppState

    init() {
        let schema = Schema([BusinessCard.self, Contact.self, ContactField.self])
        
        // Primary strategy: App Group for watch sync (without CloudKit for now)
        // CloudKit can be enabled once properly configured in Xcode
        var container: ModelContainer?
        
        if let appGroupURL = FileManager.default.containerURL(
            forSecurityApplicationGroupIdentifier: "group.com.mbrucedogs.BusinessCard"
        ) {
            let storeURL = appGroupURL.appending(path: "BusinessCard.store")
            let config = ModelConfiguration(
                schema: schema,
                url: storeURL,
                cloudKitDatabase: .none  // Disable CloudKit until properly configured
            )
            
            do {
                container = try ModelContainer(for: schema, configurations: [config])
            } catch {
                print("Failed to create container with App Group: \(error)")
            }
        }
        
        // Fallback: Default location (Application Support)
        if container == nil {
            let storeURL = URL.applicationSupportDirectory.appending(path: "BusinessCard.store")
            let config = ModelConfiguration(
                schema: schema,
                url: storeURL,
                cloudKitDatabase: .none
            )
            
            do {
                container = try ModelContainer(for: schema, configurations: [config])
            } catch {
                print("Failed to create container in Application Support: \(error)")
            }
        }
        
        // Last resort: In-memory (data won't persist but app will work)
        if container == nil {
            print("WARNING: Using in-memory store - data will not persist!")
            let config = ModelConfiguration(
                schema: schema,
                isStoredInMemoryOnly: true,
                cloudKitDatabase: .none
            )
            container = try? ModelContainer(for: schema, configurations: [config])
        }
        
        guard let container else {
            fatalError("Failed to create ModelContainer with all strategies")
        }
        
        self.modelContainer = container
        let context = container.mainContext
        self._appState = State(initialValue: AppState(modelContext: context))
    }

    var body: some Scene {
        WindowGroup {
            RootTabView()
                .environment(appState)
                .preferredColorScheme(.light)
        }
        .modelContainer(modelContainer)
    }
}
