Now I have a complete understanding. Let me provide a comprehensive analysis report.

---

# PROD-Planner2026 iOS App - Data Models & Business Logic Analysis

## Executive Summary

**Planner2026-iOS** is a comprehensive task/project management app with AI integration, location tracking, and gamification. The architecture is well-organized with **100% shareable models and 85% shareable business logic** between iOS and macOS versions.

**Total Code**: 46 Swift files | **Models**: 11 files | **Services**: 9 files | **Views**: 18 files

---

## 1. DATA MODELS (All Portable to macOS)

### A. Core Planning Models

#### **PlannerTask** (`/Services/Data/PlannerTask.swift`)
```swift
struct PlannerTask: Identifiable, Codable, Hashable
├── Task Properties
│   ├── id: UUID
│   ├── title, notes, priority (enum: low/medium/high/urgent)
│   ├── status: TaskStatus (pending/inProgress/completed/archived)
│   ├── dueDate, scheduledDate, scheduledTime
│   ├── estimatedMinutes, actualMinutes (time tracking)
│   └── subtasks: [Subtask] (nested checklist items)
├── Project Relations
│   └── projectId: UUID? (parent project)
├── Location Features
│   ├── locationId: UUID? (associated location)
│   ├── hasGeofenceReminder: Bool
│   ├── geofenceRadius, triggerOnEntry
├── AI Metadata
│   ├── isAISuggested: Bool
│   ├── aiConfidenceScore: Double (0-1)
│   └── patternNotes: String
└── Timestamps: createdAt, completedAt, modifiedAt

Computed Properties:
├── progress: Double (based on subtask completion)
├── isOverdue, isDueToday, isDueTomorrow, isDueThisWeek: Bool
└── estimatedDuration: String (formatted)
```
**Subtask**: Simple nested structure with completion tracking

**macOS Compatibility**: ✅ 100% - Zero iOS-specific dependencies

---

#### **Project** (`/Models/Project.swift`)
```swift
struct Project: Identifiable, Codable, Hashable
├── id: UUID
├── name, projectDescription
├── status: ProjectStatus (active/onHold/completed/archived)
├── deadline: Date?
├── colorHex, icon (customizable UI)
├── taskIds: [UUID] (FK references)
├── tags: [UUID] (relationship)
├── defaultLocationId: UUID?
├── isAISuggested: Bool
└── Timestamps: createdAt, completedAt, modifiedAt

Computed Properties:
├── isActive, isCompleted, taskCount
└── isOverdue: Bool
```

**macOS Compatibility**: ✅ 100%

---

#### **Tag** (`/Models/Tag.swift`)
```swift
struct Tag: Identifiable, Codable, Hashable
├── id: UUID
├── name: String
├── colorHex: String (hex color code)
├── icon: String? (SF Symbols compatible)
├── createdAt: Date
└── systemTags: [Tag] static property
    ├── Important, Urgent, Personal, Work, Health
    ├── Finance, Learning, Creative
```

**macOS Compatibility**: ✅ 100%

---

### B. Location & GPS Models

#### **TaskLocation** (`/Models/TaskLocation.swift`)
```swift
struct TaskLocation: Identifiable, Codable, Hashable
├── id: UUID
├── name: String (e.g., "Office", "Home", "Gym")
├── address: String
├── latitude, longitude: Double
├── radius: Double (geofence radius in meters, default: 100m)
├── icon: String (SF Symbols)
├── colorHex: String
├── isFavorite: Bool
├── createdAt: Date
├── Computed
│   ├── coordinate: CLLocationCoordinate2D
│   └── clLocation: CLLocation
└── Factory Methods
    ├── home(lat, lon) → TaskLocation
    ├── work(lat, lon) → TaskLocation
    └── gym(lat, lon) → TaskLocation
```

**LocationHistoryEntry**: Track where tasks completed
```swift
struct LocationHistoryEntry: Identifiable, Codable
├── id, latitude, longitude, accuracy
├── timestamp: Date
├── associatedTaskId: UUID?
└── associatedLocationId: UUID?
```

**macOS Compatibility**: ⚠ Partial
- Models: ✅ 100% portable
- CoreLocation: ⚠ macOS has different frameworks (still available, but different usage)
- Geofence logic: ✅ Portable (identical API on macOS)

---

### C. Gamification Models

#### **Gamification.swift** (`/Models/Gamification.swift`)
```swift
struct UserProgress: Codable
├── totalXP: Int
├── level: Int (calculated from XP)
├── streaks: StreakData
├── badges: [Badge]
├── achievements: [Achievement]
├── lastUpdated: Date
├── Computed
│   ├── xpForCurrentLevel, xpToNextLevel: Int
│   ├── levelProgress: Double (0-1)
│   └── Methods: addXP(_ amount)

struct StreakData: Codable
├── morningRitual, walking, routine, goalsProgress: Int
├── lastMorningRitualDate, lastWalkingDate, etc.: Date?
├── bestMorningRitualStreak, bestWalkingStreak, etc.: Int
└── Methods
    ├── updateMorningRitualStreak()
    ├── updateWalkingStreak()
    └── updateRoutineStreak()

enum XPRewards
├── saversElement = 10
├── morningRitualComplete = 50
├── walkingSession = 30
├── newLocation = 20
├── routineComplete = 25
├── goalProgress = 15
├── milestoneReached = 100
├── streakBonus = 5 (per day)
├── taskCompleted = 10
└── projectCompleted = 50

struct Badge: Identifiable, Codable, Equatable
├── id: UUID, type: BadgeType, earnedAt: Date
├── name, description, icon: String
└── 19 badge types: firstMorning, weekMorning, monthMorning,
    saversMaster, firstWalk, weekWalking, explorer, marathoner,
    firstGoal, tenApps, fiftyApps, hundredApps, streakStarter,
    streakWarrior, streakLegend, level5-50

struct Achievement: Identifiable, Codable
├── id: UUID, title, description, icon
├── progress: Double (0-1), targetValue, currentValue
├── isComplete, completedAt: Date?
└── Methods: updateProgress(_ newValue)

struct XPEvent: Identifiable, Codable, Equatable
├── id: UUID, amount: Int, reason: String
├── timestamp: Date, category: XPCategory
└── Categories: morningRitual, walking, routine, goals, tasks,
    streak, achievement
```

**macOS Compatibility**: ✅ 100%

---

### D. Daily Quest Models

#### **MorningRitual.swift** (`/Models/MorningRitual.swift`)
```swift
enum SAVERSElement: String, Codable, CaseIterable
├── silence (10 min) - brain.head.profile
├── affirmations (5 min) - quote.bubble.fill
├── visualization (5 min) - eye.fill
├── exercise (20 min) - figure.walk
├── reading (20 min) - book.fill
└── scribing (10 min) - pencil.line
└── Computed: duration, icon, description, order

struct SAVERSCompletion: Identifiable, Codable
├── id: UUID, element: SAVERSElement
├── isCompleted: Bool, completedAt: Date?
├── duration: Int (actual minutes spent)
├── notes: String
└── Methods: complete(duration?, notes)

struct MorningRitualDay: Identifiable, Codable
├── id: UUID, date: Date
├── wakeTime: Date?, targetWakeTime: Date
├── elements: [SAVERSCompletion] (all 6 elements)
├── isComplete: Bool, xpEarned: Int
├── Computed
│   ├── completedCount, totalCount, progress: Double
│   ├── wokeOnTime: Bool (within 15 min grace)
│   └── totalDuration: Int
└── Methods
    ├── recordWakeTime()
    └── completeElement(_ element, duration?, notes)

struct MorningRitualSettings: Codable
├── targetWakeHour, targetWakeMinute
├── enabledElements: [SAVERSElement]
├── customDurations: [SAVERSElement: Int]
├── wakeReminderEnabled, reminderMinutesBefore
```

**macOS Compatibility**: ✅ 100%

---

#### **DailyRoutine.swift** (`/Models/DailyRoutine.swift`)
```swift
struct RoutineItem: Identifiable, Codable, Hashable
├── id: UUID, title, icon
├── isCompleted: Bool, completedAt: Date?
├── order: Int
└── Methods: toggle()

struct DailyRoutine: Identifiable, Codable
├── id: UUID, date: Date
├── wakeTime, sleepTime: Date?
├── morningChecklist, eveningChecklist: [RoutineItem]
├── isComplete: Bool, xpEarned: Int
├── Default Checklists
│   ├── Morning: Acordar, Escovar dentes, Lavar rosto, etc.
│   └── Evening: Revisar tarefas, Preparar roupa, Desligar telas, etc.
├── Computed
│   ├── morningProgress, eveningProgress, totalProgress: Double
│   ├── isMorningComplete, isEveningComplete: Bool
│   └── totalProgress: Double
└── Methods
    ├── recordWakeTime()
    ├── toggleMorningItem(at:), toggleEveningItem(at:)

struct SleepSchedule: Codable
├── targetBedtimeHour/Minute, targetWakeHour/Minute
├── windDownMinutes: Int (time before bed)
├── Computed: targetBedtime, targetWakeTime, targetSleepDuration

struct RoutineSettings: Codable
├── morningItems, eveningItems: [RoutineItemTemplate]
├── sleepSchedule: SleepSchedule
├── morningReminderEnabled, eveningReminderEnabled
```

**macOS Compatibility**: ✅ 100%

---

#### **YearlyGoals.swift** (`/Models/YearlyGoals.swift`)
```swift
struct YearlyGoal: Identifiable, Codable
├── id: UUID, year: Int, title, description
├── icon: String, colorHex: String
├── targetValue, currentValue: Int, unit: String
├── milestones: [Milestone], entries: [GoalEntry]
├── createdAt: Date, isArchived: Bool
├── Computed
│   ├── progress: Double, percentComplete: Int
│   ├── remaining, isComplete: Bool
│   ├── nextMilestone, reachedMilestones
│   ├── weeksRemaining, targetPerWeek
│   └── monthsRemaining, targetPerMonth
├── Factory: iOSAppsGoal() → YearlyGoal (100 apps goal)
└── Methods: addProgress(_ amount, notes)

struct Milestone: Identifiable, Codable
├── id, value (target), title, icon, colorHex
├── isReached: Bool, reachedAt: Date?
├── xpReward: Int (XPRewards.milestoneReached)
└── Methods: reach()

struct GoalEntry: Identifiable, Codable
├── id: UUID, amount: Int
├── notes: String, timestamp: Date
└── Tracks incremental progress

struct GoalsStatistics: Codable
├── totalGoals, completedGoals, totalMilestonesReached
├── totalXPFromGoals
└── Computed: completionRate: Double

enum GoalCategory: String, Codable, CaseIterable
├── development, learning, fitness, finance
├── personal, career, creative, other
└── icon, colorHex properties for each
```

**macOS Compatibility**: ✅ 100%

---

#### **WalkingQuest.swift** (`/Models/WalkingQuest.swift`)
```swift
struct WalkingSession: Identifiable, Codable
├── id: UUID, date: Date
├── startTime, endTime: Date?, duration: TimeInterval (seconds)
├── distance: Double (meters), route: [RoutePoint]
├── exploredLocations: [ExploredLocation]
├── xpEarned: Int, isActive: Bool
├── Computed
│   ├── durationMinutes: Int, distanceKilometers: Double
│   ├── averagePace: Double (min/km)
│   ├── meetsMinimumDuration, meetsTargetDuration: Bool
├── Methods
│   ├── addRoutePoint(_ point)
│   ├── addExploredLocation(_ location)
│   └── end() → calculates XP

struct RoutePoint: Codable, Identifiable
├── id: UUID, latitude, longitude
├── altitude: Double?, timestamp: Date
├── accuracy: Double?
├── Init from CLLocation
└── Computed: coordinate, clLocation

struct ExploredLocation: Identifiable, Codable, Hashable
├── id: UUID, name: String, category: LocationCategory
├── latitude, longitude, discoveredAt: Date
├── visitCount: Int, lastVisitedAt: Date
├── notes: String
├── Methods: recordVisit()

enum LocationCategory: String, Codable, CaseIterable
├── park, trail, cafe, plaza, viewpoint, beach, landmark, other
└── icon property for each

struct NearbySuggestion: Identifiable
├── Suggestions for new locations to explore
└── distance (meters), isVisited

struct WalkingStatistics: Codable
├── totalSessions, totalDistance (meters), totalDuration (TimeInterval)
├── locationsDiscovered, longestSession, longestDistance
├── Computed
│   ├── totalDistanceKm, totalDurationHours
│   ├── averageSessionDuration, averageSessionDistance
│   └── Methods: updateWith(session)

struct WalkingSettings: Codable
├── targetMinutesPerDay, enableBackgroundTracking
├── distanceFilter: Double (5.0m default)
├── enableNearbyNotifications, nearbyRadius
```

**macOS Compatibility**: ⚠ Partial
- Models: ✅ 100% portable
- CLLocation integration: ⚠ Works on macOS but different usage patterns

---

### E. AI Models

#### **AIModels.swift** (`/Models/AIModels.swift`)
```swift
enum ChatRole: String, Codable
├── user, assistant, system

struct ChatMessage: Identifiable, Codable, Hashable
├── id: UUID, role: ChatRole, content: String
├── timestamp: Date, isLoading: Bool
└── Non-codable isLoading property

struct AIConversation: Identifiable, Codable, Hashable
├── id: UUID, title: String = "New Chat"
├── messages: [ChatMessage]
├── createdAt, modifiedAt: Date
├── Computed: preview: String, messageCount: Int

enum InsightType: String, Codable
├── productivity, scheduling, completion, location, recommendation

struct AIInsight: Identifiable, Codable, Hashable
├── id: UUID, type: InsightType
├── title, content: String
├── confidence: Double (0-1), createdAt: Date
├── expiresAt: Date?, isRead: Bool
├── Computed
│   ├── isExpired: Bool, confidenceLabel: String
│   └── icon: String (based on type)

struct ScheduledBlock: Identifiable, Codable, Hashable
├── id: UUID, taskId: UUID?
├── title: String, startTime, endTime: Date
├── confidence: Double, isBreak: Bool
├── Computed
│   ├── duration: TimeInterval, durationMinutes: Int
│   └── timeRange: String (formatted)

struct DaySchedule: Identifiable, Codable, Hashable
├── id: UUID, date: Date
├── blocks: [ScheduledBlock]
├── generatedAt: Date, isAccepted: Bool
├── Computed: totalWorkMinutes, totalBreakMinutes
```

**macOS Compatibility**: ✅ 100%

---

### F. User Model

#### **User.swift** (`/Models/User.swift`)
```swift
struct User: Identifiable, Codable, Hashable
├── id: String (Apple User ID)
├── email: String?, fullName: String?
├── Computed
│   ├── displayName: String (name → email → "User")
│   └── initials: String (derived from name)
```

**macOS Compatibility**: ✅ 100%

---

## 2. DATA PERSISTENCE MECHANISMS

### DataManager (Primary State Manager) (`/Services/Data/DataManager.swift`)

**Type**: `@MainActor` ObservableObject (singleton)

#### Published Collections
```swift
@Published var tasks: [PlannerTask] = []
@Published var projects: [Project] = []
@Published var locations: [TaskLocation] = []
@Published var locationHistory: [LocationHistoryEntry] = []
@Published var conversations: [AIConversation] = []
@Published var insights: [AIInsight] = []
@Published var tags: [Tag] = []
@Published var schedules: [DaySchedule] = []

// Daily Quests
@Published var morningRituals: [MorningRitualDay] = []
@Published var dailyRoutines: [DailyRoutine] = []
@Published var yearlyGoals: [YearlyGoal] = []
```

#### Storage Architecture: 3-Layer Backup System
```
Primary:  Planner2026_Tasks
Backup1:  Planner2026_Tasks_backup1
Backup2:  Planner2026_Tasks_backup2

Cascade Strategy:
  Save cycle: backup1 ← primary ← new_data
              backup2 ← old_backup1

Load strategy:
  1. Try primary
  2. Fallback to backup1
  3. Fallback to backup2
```

**Debounce System**: 500ms debounce on saves (prevents excessive UserDefaults writes)

#### CRUD Operations
```swift
// Tasks
func addTask(_ task: PlannerTask)
func updateTask(_ task: PlannerTask)
func deleteTask(_ task: PlannerTask)
func toggleTaskCompletion(_ task: PlannerTask)

// Projects
func addProject(_ project: Project)
func updateProject(_ project: Project)
func deleteProject(_ project: Project) // cascades to tasks

// Locations
func addLocation(_ location: TaskLocation)
func updateLocation(_ location: TaskLocation)
func deleteLocation(_ location: TaskLocation) // cascades to tasks
func addLocationHistoryEntry(_ entry: LocationHistoryEntry)

// AI Data
func saveConversation(_ conversation: AIConversation)
func deleteConversation(_ conversation: AIConversation)
func addInsight(_ insight: AIInsight)
func markInsightAsRead(_ insight: AIInsight)
func saveSchedule(_ schedule: DaySchedule)

// Daily Quests
func saveMorningRitual(_ ritual: MorningRitualDay)
func getTodayRitual() → MorningRitualDay?
func getMorningRitualStreak() → Int
func saveDailyRoutine(_ routine: DailyRoutine)
func getTodayRoutine() → DailyRoutine?

// Goals
func addYearlyGoal(_ goal: YearlyGoal)
func updateYearlyGoal(_ goal: YearlyGoal)
func deleteYearlyGoal(_ goal: YearlyGoal)
func getActiveYearlyGoals() → [YearlyGoal]
```

#### Data Access Helpers
```swift
var tasksForToday: [PlannerTask]
func tasksForProject(_ projectId: UUID) → [PlannerTask]
func tasksForLocation(_ locationId: UUID) → [PlannerTask]
func projectProgress(_ project: Project) → Double
func getTaskStatistics() → TaskStatistics
func getUnreadInsightsCount() → Int
```

#### Data Limits
```swift
enum DataLimits {
    static let maxLocationHistory = 1000
    static let maxConversations = 50
    static let maxInsights = 100
    static let maxRecentXPEvents = 50
    static let schedulesRetentionDays = 30
    static let morningRitualsRetentionDays = 90
    static let dailyRoutinesRetentionDays = 90
}
```

**macOS Compatibility**: ✅ 95%
- Core logic: 100% portable
- Debounce + cascade backup: 100% portable
- @MainActor: 100% portable on macOS 13.0+

---

### GamificationService (`/Services/Data/GamificationService.swift`)

**Type**: Separate ObservableObject (singleton)

#### Published State
```swift
@Published var userProgress: UserProgress
@Published var recentXPEvents: [XPEvent] = []
@Published var unlockedBadge: Badge?
@Published var levelUpNotification: Int?
@Published var lastXPEvent: XPEvent?
```

#### XP Award Methods (Thematic)
```swift
func awardXP(_ amount: Int, reason: String, category: XPCategory)

// Morning Ritual
func awardSAVERSElement(_ element: SAVERSElement)
func awardMorningRitualComplete(allSAVERSCompleted: Bool)

// Walking
func awardWalkingSession(duration: Int, newLocations: Int,
                         totalDistance: Double, totalExploredLocations: Int)

// Routine
func awardRoutineComplete()

// Goals
func awardGoalProgress(goal: YearlyGoal, amount: Int)
func awardMilestoneReached(milestone: Milestone, goal: YearlyGoal)

// Tasks
func awardTaskCompleted()
func awardProjectCompleted(name: String)
```

#### Badge Unlock Logic
```swift
// Automatic badge checks:
├── Morning Ritual: firstMorning (1 day), weekMorning (7 days),
│                   monthMorning (30 days), saversMaster (all SAVERS done)
├── Walking: firstWalk, weekWalking, explorer (10 locations),
│            marathoner (42km total)
├── Goals: firstGoal, tenApps, fiftyApps, hundredApps
├── Streaks: streakStarter (3 days), streakWarrior (14 days),
│            streakLegend (30 days)
└── Levels: level5, level10, level25, level50

// Notification System
├── unlockedBadge: Published badge (triggers UI animation)
├── levelUpNotification: Published level (triggers UI notification)
└── lastXPEvent: Published event (shows floating XP label)
```

#### Statistics
```swift
func getTodayXP() → Int
func getWeekXP() → Int
func getXPByCategory(_ category: XPCategory) → Int
```

**Storage**: UserDefaults with 2 keys
- `Planner2026_UserProgress` (entire progress object)
- `Planner2026_XPEvents` (recent events array)

**macOS Compatibility**: ✅ 100%

---

### Authentication & Security

#### KeychainService (`/Services/Auth/KeychainService.swift`)
```swift
// Stores securely:
├── appleUserID: String (from Sign in with Apple)
├── appleUserEmail: String?
├── appleUserName: String?
└── claudeAPIKey: String? (Claude API key for AI)

// Methods
├── isAppleSignedIn: Bool computed
├── clearAppleCredentials()
└── clearAll()

// Storage: iOS Keychain (kSecClassGenericPassword)
// Accessibility: kSecAttrAccessibleAfterFirstUnlock
```

**macOS Compatibility**: ⚠ 85%
- Keychain exists on macOS, but different API (SecureEnclave vs iOS Keychain)
- KeychainService pattern: 100% portable
- Implementation details: Needs macOS-specific code

---

## 3. VIEW MODELS & STATE MANAGEMENT PATTERNS

**Architecture Pattern**: MVVM with ObservableObject singletons (no separate ViewModels - data flows directly from services)

### State Flow
```
Service (ObservableObject)
    ↓ @Published properties
View (SwiftUI)
    ↓ User interaction
Service method called
    ↓
Data persisted to UserDefaults
    ↓
@Published updated (triggers view redraw)
```

### Services Acting as ViewModels

1. **DataManager** - Central data access (CRUD on all task/project/location data)
2. **GamificationService** - Gamification state (XP, badges, levels)
3. **ClaudeService** - AI interactions (chat, scheduling)
4. **LocationService** - GPS access
5. **GeofenceService** - Geofence monitoring
6. **WalkingTrackingService** - Walking session tracking

**macOS Compatibility**: ✅ 100%
- ObservableObject is cross-platform
- @MainActor works on macOS 13.0+
- Same reactive pattern works identically on macOS

---

## 4. SERVICES & MANAGERS

### Location Services

#### LocationService (`/Services/Location/LocationService.swift`)
- Manages CoreLocation requests
- Handles location permissions
- Tracks current user location
- Updates location history

#### GeofenceService (`/Services/Location/GeofenceService.swift`)
- Monitors geofences (max 20 per iOS limit)
- Triggers notifications on entry/exit
- Cross-platform compatible (same geofence API on macOS)

#### WalkingTrackingService (`/Services/Location/WalkingTrackingService.swift`)
- Records walking sessions in real-time
- Calculates distance and pace
- Detects new locations
- Updates statistics

**macOS Compatibility**: ⚠ 80% (Geofencing works, but user interaction patterns differ)

---

### AI Service

#### ClaudeService (`/Services/AI/ClaudeService.swift`)
```swift
class ClaudeService: ObservableObject
├── @Published var isLoading: Bool
├── @Published var error: String?
├── API: https://api.anthropic.com/v1/messages
├── Models
│   ├── claude-sonnet-4-20250514 (default/fast)
│   └── claude-opus-4-20250514 (powerful)
├── Methods
│   ├── sendMessage(_ message: String) → String
│   ├── sendConversation(_ messages: [ChatMessage]) → String
│   └── hasAPIKey(), setAPIKey(_ key: String)
├── Session timeout: 60 sec request / 120 sec total
└── Max tokens: 4096
```

**macOS Compatibility**: ✅ 100%

---

### Authentication Service

#### AuthenticationService (`/Services/Auth/AuthenticationService.swift`)
- Handles Sign in with Apple
- Manages authentication state
- Integrates with Keychain storage

**macOS Compatibility**: ⚠ 80%
- Sign in with Apple available on macOS 10.15+
- Different UI patterns (macOS uses sheet vs iOS modal)

---

### Utility Services

#### HapticManager (`/Services/Utilities/HapticManager.swift`)
- Haptic feedback for user actions
- Task complete, task add, task delete vibrations
- XP award haptic

**macOS Compatibility**: ❌ Not applicable (macOS has no haptics)

#### NotificationService (`/Services/Utilities/NotificationService.swift`)
- Local push notifications
- Wake reminders (6:00 AM)
- Walking reminders (6:30 AM)
- Evening routine reminders (9:00 PM)
- Streak warnings

**macOS Compatibility**: ✅ 100% (different framework: NSUserNotification)

#### Logger (`/Services/Utilities/Logger.swift`)
- App-wide structured logging

**macOS Compatibility**: ✅ 100%

---

## 5. DATA FLOW ARCHITECTURE

### Complete Flow Example: Adding a Task

```
User taps "Add Task" → NewTaskView
                         ↓
                   User fills form
                         ↓
                   Calls DataManager.addTask()
                         ↓
                   Tasks array updated (@Published)
                         ↓
                   HapticManager.taskAdded()
                         ↓
                   Debounce scheduled (500ms)
                         ↓
                   After 500ms, save to UserDefaults
                         ↓
                   Backup cascade: backup1 ← primary ← new_data
                         ↓
                   View automatically redraws (Combine)
```

### Flow: Completing a Task

```
User taps task checkbox
           ↓
toggleTaskCompletion(_ task)
           ↓
Update status (.completed)
Update completedAt timestamp
           ↓
HapticManager.taskCompleted()
           ↓
Schedule debounced save
           ↓
Check if part of goal → award XP
Check if part of project → update progress
           ↓
GamificationService.awardTaskCompleted()
           ↓
Update XP, check badges
Notify UI of badge unlock if earned
           ↓
Save to UserDefaults + backup
```

### Flow: Walking Session

```
User starts walking session
           ↓
WalkingTrackingService.startSession()
           ↓
LocationService provides real-time GPS updates
           ↓
WalkingTrackingService.addRoutePoint() every ~5 meters
           ↓
Calculate distance, check for nearby locations
           ↓
User ends session
           ↓
ExploredLocation list extracted
Determine new locations visited
           ↓
GamificationService.awardWalkingSession(
    duration: durationMinutes,
    newLocations: count,
    totalDistance: kilometers,
    totalExploredLocations: total
)
           ↓
Award base XP (30)
Award location XP (20 per new)
Check walking streak
Award streak bonus
Check explorer/marathoner badges
           ↓
WalkingSession persisted to DataManager
           ↓
UI shows XP awarded + badge notifications
```

---

## 6. SHAREABLE CODE FOR macOS VERSION

### 100% Portable (No Changes Needed)

```
Models/ (ALL FILES)
├── PlannerTask.swift ✅
├── Project.swift ✅
├── Tag.swift ✅
├── YearlyGoals.swift ✅
├── Gamification.swift ✅
├── MorningRitual.swift ✅
├── DailyRoutine.swift ✅
├── WalkingQuest.swift ✅
├── User.swift ✅
└── AIModels.swift ✅

Services/
├── Data/
│   ├── DataManager.swift ✅
│   └── GamificationService.swift ✅
├── AI/
│   └── ClaudeService.swift ✅
├── Auth/
│   ├── KeychainService.swift ⚠ (needs macOS keychain port)
│   └── AuthenticationService.swift ⚠ (different UI but same logic)
└── Utilities/
    ├── Logger.swift ✅
    └── Constants.swift ✅

```

### Shared Foundation: ~3200 lines of portable code

---

### 80-90% Portable (Minor Changes)

```
Services/Location/
├── LocationService.swift ⚠ (CoreLocation works on macOS)
├── GeofenceService.swift ⚠ (Same API on macOS)
└── WalkingTrackingService.swift ⚠ (Same logic, different tracking UI)
```

### Platform-Specific Only (Don't Share)

```
Services/Utilities/
├── HapticManager.swift ❌ (No haptics on macOS)
└── NotificationService.swift ⚠ (Different framework: UserNotification vs NSUserNotification)
```

---

## 7. RECOMMENDED SHARED CODE STRUCTURE FOR macOS

### Create a Shared Framework

```
PROD-Planner2026-Shared/ (New)
├── Models/
│   ├── PlannerTask.swift (direct copy)
│   ├── Project.swift
│   ├── Tag.swift
│   ├── YearlyGoals.swift
│   ├── Gamification.swift
│   ├── MorningRitual.swift
│   ├── DailyRoutine.swift
│   ├── WalkingQuest.swift
│   ├── User.swift
│   └── AIModels.swift
├── Services/
│   ├── DataManager.swift (direct copy)
│   ├── GamificationService.swift (direct copy)
│   ├── ClaudeService.swift (direct copy)
│   ├── Constants.swift (direct copy)
│   └── Logger.swift (direct copy)
└── Extensions/ (if needed)

PROD-Planner2026-iOS/
└── Planner2026-iOS.xcodeproj
    └── Reference: PROD-Planner2026-Shared

PROD-Planner2026-macOS/ (New)
└── Planner2026-macOS.xcodeproj
    └── Reference: PROD-Planner2026-Shared
    └── Platform-specific: Views, Location services, Auth flow
```

---

## 8. KEY IMPLEMENTATION DETAILS

### UserDefaults Keys Structure
```swift
// Tasks (3-layer backup)
Planner2026_Tasks
Planner2026_Tasks_backup1
Planner2026_Tasks_backup2

// Projects (3-layer backup)
Planner2026_Projects
Planner2026_Projects_backup1
Planner2026_Projects_backup2

// Locations (3-layer backup)
Planner2026_Locations
Planner2026_Locations_backup1
Planner2026_Locations_backup2

// Other data (single save)
Planner2026_LocationHistory
Planner2026_Conversations
Planner2026_Insights
Planner2026_Tags
Planner2026_Schedules
Planner2026_MorningRituals
Planner2026_DailyRoutines
Planner2026_YearlyGoals
Planner2026_UserProgress
Planner2026_XPEvents
```

### JSON Codable Strategy
- All models use `Codable` protocol
- `JSONEncoder()` / `JSONDecoder()` for serialization
- Date encoding uses ISO 8601 format
- UUID uses default UUID string encoding

---

## 9. GAMIFICATION THRESHOLDS

```swift
enum GamificationThresholds {
    static let weeklyStreakDays = 7
    static let monthlyStreakDays = 30
    static let yearlyStreakDays = 365
    static let explorerLocations = 10        // locations for explorer badge
    static let marathonerDistance = 42000    // meters (42km)
}

enum WalkingThresholds {
    static let shortWalkMinutes = 15
    static let longWalkMinutes = 30
    static let defaultTargetMinutes = 30
    static let nearbyRadius = 500            // meters
    static let exploredRadius = 50           // meters
    static let minLocationAccuracy = 50      // meters
}
```

---

## 10. SUMMARY TABLE

| Component | Type | Lines | macOS Compat | Notes |
|-----------|------|-------|--------------|-------|
| **Models** | Codable structs | ~1000 | ✅ 100% | Zero iOS dependencies |
| **DataManager** | ObservableObject | 532 | ✅ 95% | @MainActor works on 13.0+ |
| **GamificationService** | ObservableObject | 347 | ✅ 100% | Pure logic, no platform deps |
| **ClaudeService** | ObservableObject | 227 | ✅ 100% | Standard URLSession |
| **Location Services** | Various | ~641 | ⚠ 80% | CoreLocation/Geofence available |
| **Auth Services** | Managers | ~334 | ⚠ 85% | Keychain differs, logic same |
| **Notification Service** | Manager | 264 | ✅ 100% | Different framework (UserNotification) |
| **Utilities** | Helpers | ~290 | ⚠ 50% | Haptics not applicable |
| **Total** | — | ~3635 | ✅ 87% | High code reuse potential |

---

## 11. IMMEDIATE ACTION ITEMS FOR macOS VERSION

1. **Create Shared Framework** with all models + core services
2. **Port DataManager** with @MainActor (no changes)
3. **Port GamificationService** (no changes)
4. **Port ClaudeService** (no changes)
5. **Adapt Location Services** (same APIs, different UI)
6. **Adapt Auth** (same Keychain concept, macOS-specific Sign in flow)
7. **Skip Haptics**, use standard notifications
8. **Create macOS-specific Views** (SwiftUI works, but layouts/navigation differ)

**Estimated Code Reuse**: 85-90% of all Swift code
**New Code Required**: UI layer + platform-specific services = ~20-30% of final iOS code size