import SwiftUI
import SwiftData
import Bedrock

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

    init() {
        let schema = Schema([BusinessCard.self, Contact.self, ContactField.self])

        // Register app theme for Bedrock semantic text/surface colors.
        Theme.register(
            text: AppThemeText.self,
            surface: AppSurface.self,
            accent: AppThemeAccent.self,
            status: AppStatus.self
        )
        Theme.register(border: AppBorder.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: AppIdentifiers.appGroupIdentifier
        ) {
            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 {
                Design.debugLog("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 {
                Design.debugLog("Failed to create container in Application Support: \(error)")
            }
        }
        
        // Last resort: In-memory (data won't persist but app will work)
        if container == nil {
            Design.debugLog("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))
        
        // Activate WatchConnectivity session
        _ = WatchConnectivityService.shared
    }

    var body: some Scene {
        WindowGroup {
            ZStack {
                // Base background matching launch screen - prevents white flash
                Color.Branding.primary
                    .ignoresSafeArea()
                
                AppLaunchView(config: .businessCard) {
                    RootTabView()
                        .environment(appState)
                        .preferredColorScheme(appState.preferredColorScheme)
                }
            }
        }
        .modelContainer(modelContainer)
    }
}
