-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReczipes2App.swift
More file actions
864 lines (754 loc) · 35.5 KB
/
Reczipes2App.swift
File metadata and controls
864 lines (754 loc) · 35.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
//
// Reczipes2App.swift
// Reczipes2
//
// Created by Zahirudeen Premji on 12/4/25.
//
import SwiftUI
import SwiftData
import Combine
@main
struct Reczipes2App: App {
// State management
@StateObject private var appState = AppStateManager.shared
@StateObject private var taskRestoration = TaskRestorationCoordinator.shared
@StateObject private var containerManager = ModelContainerManager.shared
@StateObject private var onboarding = CloudKitOnboardingService.shared
@AppStorage("hasCompletedCloudKitOnboarding") private var hasCompletedOnboarding = false
@State private var showOnboardingSheet = false
// Startup state tracking
@State private var isInitializing = true
@State private var initializationComplete = false
// Document handling
@StateObject private var documentHandler = RecipeBookDocumentHandler.shared
init() {
// Suppress Auto Layout constraint warnings from UIKit internals
UserDefaults.standard.set(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable")
// Handle UI testing mode
if ProcessInfo.processInfo.arguments.contains("UI_TESTING") {
// Accept license and set up API key for testing
LicenseHelper.acceptLicense()
// Set a dummy API key for testing (won't actually work but allows UI to load)
_ = APIKeyHelper.setAPIKey("sk-ant-test-key-for-ui-testing")
// Skip first launch screens
UserDefaults.standard.set(false, forKey: "shouldShowLaunchScreen")
logInfo("🧪 UI Testing mode enabled - bypassing onboarding", category: "testing")
}
// Log CloudKit configuration for debugging (synchronous, no blocking)
logCloudKitConfiguration()
// NOTE: CloudKit checks are now deferred to background tasks after UI appears
// See .task modifier in MainTabView for background initialization
}
// Use the shared container from the manager instead of creating our own
var sharedModelContainer: ModelContainer {
containerManager.container
}
// Keep the old static initializer for reference, but don't use it
// NOTE: This is no longer used - ModelContainerManager handles container creation
private static var _legacySharedModelContainer: ModelContainer = {
logInfo("🚀 Legacy container initializer called (should not be used)", category: "storage")
fatalError("Legacy container initializer should not be called - use ModelContainerManager.shared instead")
}()
@State private var showLicenseAgreement = !LicenseHelper.hasAcceptedLicense
@State private var showAPIKeySetup = false
@State private var showLaunchScreen = false
@State private var showAppClipImportBanner = false
@State private var importedRecipeName = ""
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
ZStack {
// Show loading overlay when container is being recreated
if containerManager.isRecreating {
containerRecreationOverlay
} else {
MainTabView()
.modelContainer(sharedModelContainer)
.environmentObject(appState)
.environmentObject(taskRestoration)
.environmentObject(documentHandler)
.fullScreenCover(isPresented: $showLicenseAgreement) {
LicenseAgreementView(isPresented: $showLicenseAgreement)
.onDisappear {
// After license is accepted, check if API key setup is needed
if LicenseHelper.hasAcceptedLicense {
showAPIKeySetup = !APIKeyHelper.isConfigured
}
}
}
.fullScreenCover(isPresented: $showAPIKeySetup) {
APIKeySetupView(isPresented: $showAPIKeySetup)
}
.diagnosticsCapable()
.shakeToShowDiagnostics()
.onAppear {
// Only perform non-critical UI setup on appear
// Defer async work until we're sure the app is active
showLicenseAgreement = !LicenseHelper.hasAcceptedLicense
if LicenseHelper.hasAcceptedLicense {
showAPIKeySetup = !APIKeyHelper.isConfigured
}
// Show launch screen every launch (only if onboarding is complete)
if LicenseHelper.hasAcceptedLicense && APIKeyHelper.isConfigured {
showLaunchScreen = appState.shouldShowLaunchScreen()
}
}
.task {
// Guard against backgrounding during startup
guard scenePhase != .background else {
logWarning("⚠️ Skipping startup tasks - app is in background", category: "state")
return
}
// Perform startup initialization in a structured way
await performStartupInitialization()
}
.sheet(isPresented: $showOnboardingSheet) {
CloudKitOnboardingView()
.environmentObject(onboarding)
.onDisappear {
// Mark as completed when they dismiss
// (even if not fully set up, don't nag them)
hasCompletedOnboarding = true
}
}
.sheet(isPresented: $documentHandler.showImportSheet) {
RecipeBookImportSheet(handler: documentHandler)
.modelContainer(sharedModelContainer)
}
// Launch screen overlay - shows briefly on every launch (after onboarding)
if showLaunchScreen && LicenseHelper.hasAcceptedLicense && APIKeyHelper.isConfigured {
LaunchScreenView {
// Dismiss launch screen
withAnimation {
showLaunchScreen = false
}
}
.transition(.opacity)
.zIndex(1)
}
// App Clip import banner
if showAppClipImportBanner {
VStack {
AppClipImportBanner(
recipeName: importedRecipeName,
isPresented: $showAppClipImportBanner
)
.padding()
Spacer()
}
.zIndex(2)
}
// Task restoration prompt
if taskRestoration.showRestorationPrompt {
Color.black.opacity(0.4)
.ignoresSafeArea()
.zIndex(2)
TaskRestorationPromptView(
coordinator: taskRestoration,
modelContainer: sharedModelContainer
)
.zIndex(3)
}
}
}
.onChange(of: scenePhase) { oldPhase, newPhase in
logInfo("Scene phase changing: \(String(describing: oldPhase)) -> \(String(describing: newPhase))", category: "state")
handleScenePhaseChange(oldPhase: oldPhase, newPhase: newPhase)
}
.onOpenURL { url in
logInfo("Received URL: \(url)", category: "document")
// Check if this is a .recipebook file
if url.pathExtension == RecipeBookPackageType.fileExtension {
documentHandler.handleIncomingDocument(url)
}
}
}
.handlesExternalEvents(matching: [])
}
// MARK: - Container Recreation Overlay
private var containerRecreationOverlay: some View {
ZStack {
Color(.systemBackground)
.ignoresSafeArea()
VStack(spacing: 20) {
ProgressView()
.scaleEffect(1.5)
Text("Updating iCloud Connection")
.font(.headline)
Text("Please wait while we reconnect to iCloud...")
.font(.subheadline)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal)
}
}
}
// // MARK: - Image Restoration
//
// @MainActor
// private func checkAndRestoreImages() async {
// let modelContext = sharedModelContainer.mainContext
//
// // Check if any images need restoration
// let needsRestoration = RecipeImageMigrationService.needsImageRestoration(modelContext: modelContext)
//
// if needsRestoration {
// logInfo("Detected missing image files - attempting automatic restoration", category: "image")
//
// logUserDiagnostic(
// .info,
// category: .image,
// title: "Restoring Images",
// message: "Restoring recipe images from backup...",
// technicalDetails: "Detected missing image files on disk"
// )
//
// do {
// try await RecipeImageMigrationService.restoreAllRecipeImages(modelContext: modelContext)
// logInfo("Successfully restored images from SwiftData", category: "image")
//
// logUserDiagnostic(
// .info,
// category: .image,
// title: "Images Restored",
// message: "Successfully restored all recipe images.",
// technicalDetails: "Images restored from SwiftData backup"
// )
// } catch {
// logError("Failed to restore images: \(error)", category: "image")
//
// logUserDiagnostic(
// .error,
// category: .image,
// title: "Image Restoration Failed",
// message: "Couldn't restore some recipe images. They may appear blank.",
// technicalDetails: error.localizedDescription,
// suggestedActions: [
// DiagnosticAction(
// title: "Try Image Migration",
// description: "Go to Settings > Data & Sync > Image Migration",
// actionType: .openSettings(.general)
// ),
// DiagnosticAction(
// title: "Contact Support",
// description: "If images remain missing, contact support",
// actionType: .contactSupport
// )
// ]
// )
// }
// }
// }
// // MARK: - Book Cover Image Migration
//
// @MainActor
// private func migrateBookCoverImages() async {
// let modelContext = sharedModelContainer.mainContext
//
// // Check if migration is needed
// let service = RecipeBookImageMigrationService(modelContext: modelContext)
//
// guard service.needsMigration else {
// logInfo("Book cover image migration not needed (already completed)", category: "migration")
// return
// }
//
// logInfo("📚 Starting book cover image migration to SwiftData...", category: "migration")
//
// logUserDiagnostic(
// .info,
// category: .storage,
// title: "Migrating Book Covers",
// message: "Updating book cover images for iCloud sync...",
// technicalDetails: "Migrating from file-based storage to SwiftData"
// )
//
// do {
// let result = try await service.performMigration()
//
// if result.migratedCount > 0 {
// logInfo("✅ Successfully migrated \(result.migratedCount) book cover(s)", category: "migration")
//
// logUserDiagnostic(
// .info,
// category: .storage,
// title: "Book Covers Migrated",
// message: "Successfully updated \(result.migratedCount) book cover image(s). They will now sync with iCloud.",
// technicalDetails: result.summary
// )
// }
//
// // Log any errors
// if !result.errors.isEmpty {
// logWarning("Migration completed with \(result.errors.count) error(s)", category: "migration")
//
// for (bookName, error) in result.errors {
// logError("Failed to migrate '\(bookName)': \(error)", category: "migration")
// }
//
// logUserDiagnostic(
// .warning,
// category: .storage,
// title: "Some Book Covers Not Migrated",
// message: "\(result.errors.count) book cover(s) could not be migrated. They may appear blank.",
// technicalDetails: "Errors: \(result.errors.map { $0.bookName }.joined(separator: ", "))",
// suggestedActions: [
// DiagnosticAction(
// title: "Edit Book",
// description: "Try re-adding the cover image in the book editor",
// actionType: .openSettings(.general)
// )
// ]
// )
// }
//
// } catch {
// logError("Book cover image migration failed: \(error)", category: "migration")
//
// logUserDiagnostic(
// .error,
// category: .storage,
// title: "Book Cover Migration Failed",
// message: "Couldn't migrate book cover images. Covers may not sync to iCloud.",
// technicalDetails: error.localizedDescription,
// suggestedActions: [
// DiagnosticAction(
// title: "Contact Support",
// description: "If this persists, contact support",
// actionType: .contactSupport
// )
// ]
// )
// }
// }
//
// // MARK: - Legacy Model Migration
//
// @MainActor
// private func checkLegacyMigration() async {
// let modelContext = sharedModelContainer.mainContext
// let manager = LegacyToNewMigrationManager(modelContext: modelContext)
//
// // Check if migration is needed
// let needsMigration = await manager.needsMigration()
//
// if needsMigration {
// let stats = await manager.getMigrationStats()
// logInfo("📦 Legacy data detected: \(stats.legacyRecipeCount) recipes, \(stats.legacyBookCount) books", category: "migration")
//
// logUserDiagnostic(
// .info,
// category: .storage,
// title: "New Models Available",
// message: "Upgrade to new RecipeX and Book models for automatic iCloud sync.",
// technicalDetails: "Legacy items: \(stats.totalLegacyItems)",
// suggestedActions: [
// DiagnosticAction(
// title: "Migrate Now",
// description: "Tap the migration badge in the Recipes tab",
// actionType: .retryOperation
// ),
// DiagnosticAction(
// title: "Learn More",
// description: "See LEGACY_MIGRATION_GUIDE.md for details",
// actionType: .openSettings(.general)
// )
// ]
// )
// } else {
// logInfo("No legacy migration needed", category: "migration")
// }
// }
// MARK: - App Clip Data Import
private func checkForAppClipData() {
let modelContext = sharedModelContainer.mainContext
Task { @MainActor in
let didImport = AppClipDataHandler.checkForPendingRecipe(modelContext: modelContext)
if didImport {
// Show success banner
withAnimation {
importedRecipeName = "Recipe imported successfully"
showAppClipImportBanner = true
}
// Auto-dismiss after 5 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
withAnimation {
showAppClipImportBanner = false
}
}
// Share API key with App Clip if available
if let apiKey = APIKeyHelper.getAPIKey() {
AppClipDataHandler.shareAPIKeyWithAppClip(apiKey)
}
}
}
}
// MARK: - Version History Initialization
@MainActor
private func initializeVersionHistory() async {
let modelContext = sharedModelContainer.mainContext
// Initialize the service
VersionHistoryService.shared.initialize(modelContext: modelContext)
// Import historical data (one-time migration)
// This checks for duplicates, so it's safe to call every time
do {
try await VersionHistoryMigration.importHistoricalData(into: modelContext)
} catch {
logError("Failed to import version history: \(error)", category: "version-history")
}
// Add/update current version entry
await addCurrentVersionToHistory(modelContext: modelContext)
}
// MARK: - Startup Initialization
@MainActor
private func performStartupInitialization() async {
isInitializing = true
logInfo("🚀 Starting app initialization...", category: "state")
// Check scene phase before each async operation
guard scenePhase != .background else {
logWarning("⚠️ Initialization cancelled - app moved to background", category: "state")
isInitializing = false
return
}
// Step 1: Check for App Clip data (quick, non-blocking)
checkForAppClipData()
// Step 2: Initialize version history (async but safe to defer)
await initializeVersionHistory()
// Check scene phase again
guard scenePhase != .background else {
logWarning("⚠️ Initialization cancelled - app moved to background", category: "state")
isInitializing = false
return
}
// Step 3: Run CloudKit diagnostics if needed
if !hasCompletedOnboarding {
await onboarding.runComprehensiveDiagnostics()
// Check scene phase after diagnostics
guard scenePhase != .background else {
logWarning("⚠️ Initialization cancelled - app moved to background", category: "state")
isInitializing = false
return
}
// Show onboarding if not ready
if case .ready = onboarding.onboardingState {
hasCompletedOnboarding = true
} else {
showOnboardingSheet = true
}
}
isInitializing = false
initializationComplete = true
logInfo("✅ App initialization complete", category: "state")
}
// MARK: - Scene Phase Handling
private func handleScenePhaseChange(oldPhase: ScenePhase, newPhase: ScenePhase) {
// Notify app state manager
appState.handleScenePhaseChange(newPhase)
switch newPhase {
case .active:
logInfo("App became active", category: "state")
// If we were interrupted during initialization, retry it
if isInitializing && !initializationComplete {
logInfo(" Resuming interrupted initialization...", category: "state")
Task { @MainActor in
await performStartupInitialization()
}
} else if oldPhase == .background && initializationComplete {
logInfo(" App returning from background", category: "state")
// Ensure we're on main actor for all UI and state operations
Task { @MainActor in
taskRestoration.checkForTaskRestoration()
// Notify background manager on main actor
BackgroundProcessingManager.shared.handleAppWillEnterForeground()
}
}
case .inactive:
// App is becoming inactive (e.g., phone call, control center)
// This is our last chance to save before potential force-kill
logInfo("App becoming inactive - saving data", category: "state")
savePendingChanges()
case .background:
// App is going to background - state is automatically saved by AppStateManager
logInfo("App entering background", category: "state")
// If we're still initializing, mark it as cancelled
if isInitializing {
logWarning(" App backgrounded during initialization", category: "state")
isInitializing = false
}
// Save data synchronously to avoid race conditions
savePendingChanges()
// Handle background processing - this is now non-blocking
BackgroundProcessingManager.shared.handleAppDidEnterBackground()
@unknown default:
break
}
}
// MARK: - Data Persistence
/// Saves pending changes synchronously to ensure no data loss during state transitions
@MainActor
private func savePendingChanges() {
let modelContext = sharedModelContainer.mainContext
guard modelContext.hasChanges else {
logDebug("No pending changes to save", category: "state")
return
}
do {
try modelContext.save()
logInfo("✅ Successfully saved pending changes to SwiftData", category: "state")
} catch {
logError("❌ Failed to save pending changes: \(error)", category: "state")
logUserDiagnostic(
.error,
category: .storage,
title: "Save Failed",
message: "Could not save your recent changes. They may be lost.",
technicalDetails: error.localizedDescription,
suggestedActions: [
DiagnosticAction(
title: "Check Storage Space",
description: "Make sure your device has enough storage space",
actionType: .openSettings(.general)
)
]
)
}
}
// MARK: - CloudKit Diagnostics
private func logCloudKitConfiguration() {
logInfo("📱 CLOUDKIT CONFIGURATION", category: "storage")
logInfo(" Container ID: iCloud.com.headydiscy.reczipes", category: "storage")
logInfo(" Configuration: Private Database", category: "storage")
logInfo(" Framework: SwiftData (not Core Data)", category: "storage")
// Log user-facing diagnostic
logUserDiagnostic(
.info,
category: .storage,
title: "App Configuration",
message: "Using iCloud container: iCloud.com.headydiscy.reczipes",
technicalDetails: "Private Database with SwiftData framework"
)
// Check for multiple database files
checkForMultipleDatabases()
}
private func checkForMultipleDatabases() {
logInfo("🔍 DATABASE FILE DIAGNOSTICS", category: "storage")
let appSupport = URL.applicationSupportDirectory
let fileManager = FileManager.default
// Check for different database files
let possibleDatabases = [
"CloudKitModel.sqlite",
"default.store",
"Model.sqlite",
"Reczipes2.sqlite"
]
var foundDatabases: [(name: String, size: Int64, modified: Date)] = []
for dbName in possibleDatabases {
let dbURL = appSupport.appendingPathComponent(dbName)
if fileManager.fileExists(atPath: dbURL.path) {
do {
let attributes = try fileManager.attributesOfItem(atPath: dbURL.path)
let fileSize = attributes[.size] as? Int64 ?? 0
let modDate = attributes[.modificationDate] as? Date ?? Date.distantPast
foundDatabases.append((name: dbName, size: fileSize, modified: modDate))
let sizeString = ByteCountFormatter.string(fromByteCount: fileSize, countStyle: .file)
logInfo("✅ Found database: \(dbName) (\(sizeString))", category: "storage")
} catch {
logWarning("⚠️ Found \(dbName) but couldn't read attributes: \(error)", category: "storage")
}
}
}
if foundDatabases.isEmpty {
logInfo("Fresh install - no existing database files", category: "storage")
logUserDiagnostic(
.info,
category: .storage,
title: "Fresh Installation",
message: "This is a new installation with no existing data.",
technicalDetails: "No database files found in app support directory"
)
} else if foundDatabases.count > 1 {
logWarning("🚨 CRITICAL: Multiple database files detected!", category: "storage")
logWarning(" This may explain missing recipes after update", category: "storage")
if let largest = foundDatabases.max(by: { $0.size < $1.size }) {
let sizeString = ByteCountFormatter.string(fromByteCount: largest.size, countStyle: .file)
logInfo(" Largest file (active): \(largest.name) - \(sizeString)", category: "storage")
// Log user-facing diagnostic about multiple databases
logUserDiagnostic(
.warning,
category: .storage,
title: "Multiple Database Files Detected",
message: "Found \(foundDatabases.count) database files. Using: \(largest.name)",
technicalDetails: "Files: \(foundDatabases.map { $0.name }.joined(separator: ", "))",
suggestedActions: [
DiagnosticAction(
title: "Check Data",
description: "Verify all your recipes are showing correctly",
actionType: .retryOperation
),
DiagnosticAction(
title: "Database Maintenance",
description: "Go to Settings > Developer Tools > Database Maintenance",
actionType: .openSettings(.general)
)
]
)
}
} else {
// Single database found - this is normal
if let db = foundDatabases.first {
let sizeString = ByteCountFormatter.string(fromByteCount: db.size, countStyle: .file)
logInfo("Using database: \(db.name) (\(sizeString))", category: "storage")
}
}
}
}
// MARK: - Main Tab View
struct MainTabView: View {
@EnvironmentObject private var appState: AppStateManager
@StateObject private var sharingService = CloudKitSharingService.shared
@Environment(\.modelContext) private var modelContext
@Environment(\.scenePhase) private var scenePhase
var body: some View {
TabView(selection: $appState.currentTab) {
// Existing recipes tab
ContentView()
.tabItem {
Label("Recipes", systemImage: "book.fill")
}
.tag(AppTab.recipes)
// Recipe Books tab
RecipeBooksView()
.tabItem {
Label("Books", systemImage: "books.vertical.fill")
}
.tag(AppTab.books)
// NEW: Cooking Mode tab
CookingView()
.tabItem {
Label("Cooking", systemImage: "flame.fill")
}
.tag(AppTab.cooking)
// Extraction tab - always visible
RecipeExtractorTabWrapper()
.tabItem {
Label("Extract", systemImage: "camera.fill")
}
.tag(AppTab.extract)
// Settings tab
SettingsView()
.tabItem {
Label("Settings", systemImage: "gear")
}
.tag(AppTab.settings)
}
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
DiagnosticButton()
}
}
.task {
// Perform background initialization tasks after UI has appeared
// This prevents blocking the UI during app launch
await performBackgroundInitialization()
}
.onChange(of: scenePhase) { oldPhase, newPhase in
handleScenePhaseChange(oldPhase: oldPhase, newPhase: newPhase)
}
}
// MARK: - Background Initialization
/// Performs non-critical initialization tasks in the background after UI appears
private func performBackgroundInitialization() async {
// Check CloudKit status (non-blocking)
// The ModelContainerManager will automatically upgrade to CloudKit if available
await CloudKitSyncMonitor.shared.checkAccountStatus()
// Start auto-sync if enabled
if sharingService.autoSyncEnabled {
await sharingService.startAutoSync(modelContext: modelContext)
logInfo("🔄 Auto-sync started during app initialization", category: "sharing")
}
// Note: ModelContainerManager already handles CloudKit upgrade asynchronously
// in its own init() with a 1-second delay, so we don't need to trigger it here
// Run image optimization migration if needed
await runImageMigrationIfNeeded()
}
/// Run image optimization migration in background
private func runImageMigrationIfNeeded() async {
let migrationManager = ImageMigrationManager.shared
// Check if migration is needed
guard migrationManager.needsMigration() else {
logInfo("Image optimization migration not needed", category: "image")
return
}
logInfo("🖼️ Starting background image optimization migration...", category: "image")
// Run migration in background
await migrationManager.runFullMigration(modelContext: modelContext)
// Migration completed - automatic CloudKit sync will handle the rest
// (recipes marked with needsCloudSync will be synced by RecipeXCloudKitSyncService)
logInfo("✅ Image migration completed - modified recipes will sync to CloudKit automatically", category: "image")
}
// MARK: - Scene Phase Handling
private func handleScenePhaseChange(oldPhase: ScenePhase, newPhase: ScenePhase) {
Task { @MainActor in
switch newPhase {
case .active:
// App became active - restart auto-sync if enabled
if sharingService.autoSyncEnabled {
await sharingService.startAutoSync(modelContext: modelContext)
logInfo("🔄 Auto-sync restarted (app became active)", category: "sharing")
}
case .background, .inactive:
// App going to background/inactive - stop auto-sync to save battery
sharingService.stopAutoSync()
logInfo("🔄 Auto-sync stopped (app entering background/inactive)", category: "sharing")
@unknown default:
break
}
}
}
}
// MARK: - Recipe Extractor Tab Wrapper
struct RecipeExtractorTabWrapper: View {
@State private var isAPIKeyConfigured = APIKeyHelper.isConfigured
var body: some View {
if isAPIKeyConfigured, let apiKey = APIKeyHelper.getAPIKey() {
RecipeExtractorView(apiKey: apiKey)
.onAppear {
// Refresh API key status when tab appears
isAPIKeyConfigured = APIKeyHelper.isConfigured
}
} else {
// Show a helpful message when API key isn't configured
NavigationView {
VStack(spacing: 20) {
Image(systemName: "key.slash")
.font(.system(size: 60))
.foregroundColor(.secondary)
Text("API Key Required")
.font(.title2)
.bold()
Text("To extract recipes from images, you need to configure your Claude API key.")
.multilineTextAlignment(.center)
.foregroundColor(.secondary)
.padding(.horizontal)
NavigationLink(destination: APIKeyManagerView()) {
Label("Set Up API Key", systemImage: "key.fill")
.font(.headline)
.padding()
.background(Color.accentColor)
.foregroundColor(.white)
.cornerRadius(10)
}
Text("You can also set up your API key in Settings")
.font(.caption)
.foregroundColor(.secondary)
}
.padding()
.navigationTitle("Extract Recipe")
.onAppear {
// Refresh API key status when tab appears
isAPIKeyConfigured = APIKeyHelper.isConfigured
}
}
}
}
}