Design a macOS app called "StudioROI" for tracking ROI on a Mac Studio M3 Ultra investment.

## User Requirements:
- **Investment**: R$ 45,000 in Mac Studio M3 Ultra (96GB/1TB)
- **Focus**: Hardware depreciation + Service revenue tracking
- **Revenue sources**: LM Studio API, Render/Conversion, CI/CD Builds, Consulting/Projects
- **Automation level**: Dashboard only (manual entry, visualization, projections)
- **Goal**: Daily clarity on progress toward payback

## Existing Patterns to Follow (from ~/Apps/macOS/ apps):

### Architecture:
- SwiftUI only, macOS 14.0+ target
- @MainActor Singleton for state (DataManager)
- 3-layer backup system for UserDefaults persistence
- Actor for async operations
- NavigationSplitView for macOS layout
- MenuBarExtra for menu bar quick status
- Native frameworks only (no external dependencies)
- CLAUDE.md documentation

### UI Patterns:
- Left sidebar with categories
- Right side: Charts + metrics cards
- Swift Charts for visualizations
- Progress bars, status indicators
- Keyboard shortcuts (⌘1, ⌘2, etc.)
- Native macOS notifications

### Existing CC ROI System (port 9001):
- Already tracks Claude Code automation costs/value
- SQLite database at ~/logs.db
- API endpoints for runs, ROI summary, daily stats
- Could potentially integrate but NOT required

## Design Requirements:

1. **Dashboard View** - Daily clarity with:
   - Investment remaining (R$ 45k - total revenue)
   - Payback progress (% complete)
   - Monthly/weekly revenue trends
   - Projected payback date
   - Today's revenue

2. **Revenue Entry** - Simple manual input:
   - Amount (R$)
   - Category (LM Studio, Render, CI/CD, Consulting)
   - Date
   - Optional description

3. **Analytics View**:
   - Revenue by category (pie chart)
   - Monthly revenue trend (line chart)
   - Payback projection curve
   - ROI percentage

4. **Settings**:
   - Initial investment amount (default R$ 45,000)
   - Monthly depreciation rate
   - Revenue categories (customizable)

5. **Menu Bar Widget**:
   - Quick payback % status
   - Today's revenue
   - Quick add revenue button

Please provide:
1. Complete project structure
2. Data models (Revenue, Investment, Category)
3. DataManager implementation approach
4. View hierarchy and navigation
5. Menu bar implementation
6. Key SwiftUI views code structure
7. Keyboard shortcuts
8. File list with descriptions


<tool_use_error>File does not exist.</tool_use_error>


No files found


Bash

List Apps directory structure


total 16
drwxr-xr-x@   5 neog  staff   160 Dec 21 21:47 .
drwxr-x---+ 150 neog  staff  4800 Dec 28 22:38 ..
-rw-r--r--@   1 neog  staff  6148 Dec 21 21:47 .DS_Store
drwxr-xr-x@  40 neog  staff  1280 Dec 27 00:00 iOS
drwxr-xr-x@  31 neog  staff   992 Dec 28 20:50 macOS


/Users/neog/Apps/iOS/EMAIL-EmailAnalyzer/CLAUDE.md
/Users/neog/Apps/iOS/PROD-ProductivityHub/CLAUDE.md
/Users/neog/Apps/iOS/FIN-MeusFIIs/CLAUDE.md
/Users/neog/Apps/iOS/SOC-XNEOG/CLAUDE.md
/Users/neog/Apps/iOS/PROD-96Blocks/CLAUDE.md
/Users/neog/Apps/iOS/AI-KeywordMonitor/CLAUDE.md
/Users/neog/Apps/iOS/EDU-17Licoes/CLAUDE.md
/Users/neog/Apps/iOS/SOC-NEOGListen/CLAUDE.md
/Users/neog/Apps/iOS/TOOL-WorkspaceGuide/CLAUDE.md
/Users/neog/Apps/iOS/TOOL-PaymentGateway/CLAUDE.md
/Users/neog/Apps/iOS/TOOL-WorkspaceManager/CLAUDE.md
/Users/neog/Apps/iOS/EMAIL-GmailAI/CLAUDE.md
/Users/neog/Apps/iOS/BIZ-RevenueFlow30D/CLAUDE.md
/Users/neog/Apps/iOS/LOC-AroundMe/CLAUDE.md
/Users/neog/Apps/iOS/MEDIA-ObsidianViewer/CLAUDE.md
/Users/neog/Apps/iOS/MEDIA-YouTubeAudio/CLAUDE.md
/Users/neog/Apps/iOS/EDU-DailyVirtue/CLAUDE.md
/Users/neog/Apps/iOS/LOC-CityExplorer/CLAUDE.md
/Users/neog/Apps/iOS/TOOL-CleanShield/CLAUDE.md
/Users/neog/Apps/iOS/PROD-HabitTracker2026/CLAUDE.md
/Users/neog/Apps/iOS/EDU-BibliaEstudo/CLAUDE.md
/Users/neog/Apps/iOS/BIZ-BusinessPlan/CLAUDE.md
/Users/neog/Apps/iOS/PROD-Planner2026/CLAUDE.md
/Users/neog/Apps/iOS/VectorCRM-iOS/CLAUDE.md
/Users/neog/Apps/iOS/PROD-LuizPlan/CLAUDE.md
/Users/neog/Apps/iOS/PROD-ThomApp/CLAUDE.md
/Users/neog/Apps/iOS/PROD-ActionPlans/CLAUDE.md
/Users/neog/Apps/iOS/PROD-MoLove/CLAUDE.md
/Users/neog/Apps/iOS/LoanTracker-iOS/CLAUDE.md
/Users/neog/Apps/iOS/HEALTH-MassGainer2026/CLAUDE.md
/Users/neog/Apps/iOS/TOOL-ProxyMonitor/CLAUDE.md


List macOS apps directory


     1→# CLAUDE.md - EmailAnalyzer-iOS
     2→
     3→**Guia para Claude Code trabalhar neste projeto**
     4→
     5→## 🎯 Project Overview
     6→
     7→EmailAnalyzer-iOS é um app iOS nativo para análise de grandes volumes de emails (420k+) com foco em:
     8→- Categorização por domínios (.com, .br, .com.br)
     9→- Analytics e estatísticas de distribuição
    10→- Conformidade total com LGPD (Lei Geral de Proteção de Dados)
    11→- 100% local, sem backend, sem telemetria
    12→
    13→## 🏗 Architecture Summary
    14→
    15→### Tech Stack
    16→
    17→```
    18→SwiftUI 100%          - UI framework (iOS 17.0+)
    19→CoreData              - Persistence (SQLite) com índices
    20→@Observable           - State management (iOS 17+)
    21→async/await           - Concurrency
    22→0 dependencies        - Apenas Apple frameworks
    23→```
    24→
    25→### Project Structure
    26→
    27→```
    28→EmailAnalyzer-iOS/
    29→├── EmailAnalyzerApp.swift          # @main entry
    30→├── MainTabView.swift               # 4 tabs navigation
    31→├── Models/
    32→│   ├── EmailRecord.swift          # CoreData entity
    33→│   └── DomainStats.swift          # Analytics structs
    34→├── Services/
    35→│   └── DataManager.swift          # Singleton - CRUD, import, export
    36→├── Features/
    37→│   ├── Import/ImportView.swift    # File picker + progress
    38→│   ├── Overview/OverviewView.swift # Stats dashboard
    39→│   ├── Domains/DomainsView.swift  # Searchable list
    40→│   └── Privacy/PrivacyView.swift  # LGPD compliance
    41→├── Components/
    42→│   └── StatsCard.swift            # Reusable UI
    43→├── Extensions/
    44→│   └── Color+Hex.swift            # Helpers
    45→└── Resources/
    46→    └── EmailAnalyzer.xcdatamodeld # CoreData schema
    47→```
    48→
    49→### Key Services
    50→
    51→**DataManager.swift** (Singleton, @MainActor)
    52→- Import emails from .txt (batch processing)
    53→- Calculate statistics (total, unique, by TLD)
    54→- Search and filter domains
    55→- Export to JSON (LGPD portability)
    56→- Delete all data (LGPD erasure)
    57→
    58→**EmailRecord.swift** (CoreData NSManagedObject)
    59→- Unique constraint on `email` field
    60→- Indexed: `email`, `domain`, `tld`
    61→- TLD extraction logic: .com.br → .br → .com → others
    62→
    63→## 🔧 Common Tasks
    64→
    65→### Working on Data Models
    66→
    67→**Files:**
    68→- `EmailAnalyzer-iOS/Models/EmailRecord.swift`
    69→- `EmailAnalyzer-iOS/Resources/EmailAnalyzer.xcdatamodeld/EmailAnalyzer.xcdatamodel/contents`
    70→
    71→**Rules:**
    72→- If adding CoreData field, update BOTH files above
    73→- Always maintain unique constraint on `email`
    74→- Add index for any field used in WHERE clauses
    75→
    76→**Example: Add new field**
    77→```swift
    78→// 1. EmailRecord.swift
    79→@NSManaged public var newField: String
    80→
    81→// 2. contents (XML)
    82→<attribute name="newField" attributeType="String"/>
    83→
    84→// 3. Update create() method to populate newField
    85→```
    86→
    87→### Working on Analytics
    88→
    89→**File:** `EmailAnalyzer-iOS/Services/DataManager.swift`
    90→
    91→**Common operations:**
    92→```swift
    93→// Aggregate query example (COUNT, GROUP BY)
    94→let fetchRequest: NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: "EmailRecord")
    95→fetchRequest.resultType = .dictionaryResultType
    96→fetchRequest.propertiesToGroupBy = ["domain"]
    97→
    98→// Performance rules:
    99→// - Always use background context for heavy queries
   100→// - Use batch operations (1000 records per save)
   101→// - Return to @MainActor only for UI updates
   102→```
   103→
   104→### Working on UI
   105→
   106→**Files:** `EmailAnalyzer-iOS/Features/*/`
   107→
   108→**Patterns:**
   109→- All views use `@EnvironmentObject var dataManager: DataManager`
   110→- Async operations use `Task { await dataManager.method() }`
   111→- SwiftUI `#Preview` for every view
   112→- Pull-to-refresh: `.refreshable { await ... }`
   113→
   114→**Example: Add new stat card**
   115→```swift
   116→// 1. Add to DomainStats.swift
   117→struct NewStat { ... }
   118→
   119→// 2. Add calculation to DataManager.swift
   120→func calculateNewStat() async -> NewStat { ... }
   121→
   122→// 3. Add UI to OverviewView.swift
   123→StatsCard(title: "New Stat", value: "\(stat)", icon: "...", color: .blue)
   124→```
   125→
   126→### Working on LGPD Features
   127→
   128→**File:** `EmailAnalyzer-iOS/Features/Privacy/PrivacyView.swift`
   129→
   130→**Requirements:**
   131→- Any new data field must be added to `LGPDReport.dataFields`
   132→- Export must include all fields
   133→- Delete must remove all data (no orphans)
   134→
   135→**Testing LGPD:**
   136→```bash
   137→# 1. Import data
   138→# 2. Export → verify JSON has all fields
   139→# 3. Delete → verify stats go to 0
   140→# 4. Reimport → verify data restored
   141→```
   142→
   143→## 🚀 Development Workflow
   144→
   145→### Build and Run
   146→
   147→```bash
   148→# Open project
   149→cd /Users/neog/EmailAnalyzer-iOS
   150→open EmailAnalyzer-iOS.xcodeproj
   151→
   152→# In Xcode:
   153→# 1. Select simulator (iPhone 15 Pro recommended)
   154→# 2. Cmd+R to build and run
   155→```
   156→
   157→### Testing with Data
   158→
   159→```bash
   160→# Generate test files
   161→./generate-test-emails.sh
   162→
   163→# This creates:
   164→# - test-emails-small.txt (100)
   165→# - test-emails-medium.txt (1k)
   166→# - test-emails-large.txt (10k)
   167→```
   168→
   169→### Regenerate Xcode Project
   170→
   171→```bash
   172→# If you add/remove files:
   173→ruby create-xcode-project.rb
   174→
   175→# Then reopen in Xcode
   176→```
   177→
   178→## 🐛 Debugging
   179→
   180→### CoreData Issues
   181→
   182→**Symptom:** "Entity not found" or crashes
   183→**Fix:**
   184→```bash
   185→# Delete app from simulator
   186→xcrun simctl uninstall booted com.yourname.EmailAnalyzer-iOS
   187→
   188→# Clean build
   189→# Xcode: Product → Clean Build Folder (Cmd+Shift+K)
   190→
   191→# Rebuild
   192→# Xcode: Product → Build (Cmd+B)
   193→```
   194→
   195→### Performance Issues
   196→
   197→**Symptom:** Import is slow or UI freezes
   198→
   199→**Check:**
   200→1. Background processing: All heavy operations must use `backgroundContext`
   201→2. Batch size: Currently 1000 records/batch (adjustable in DataManager:91)
   202→3. Indices: Verify CoreData model has indices on `email`, `domain`, `tld`
   203→
   204→**Profile:**
   205→```bash
   206→# Xcode: Product → Profile (Cmd+I)
   207→# Select "Time Profiler" or "Leaks"
   208→```
   209→
   210→### Memory Issues
   211→
   212→**Symptom:** App crashes with large datasets
   213→
   214→**Check:**
   215→1. Queries use fetch limits (currently 500 for search)
   216→2. No retained references to large arrays
   217→3. Aggregate queries don't fetch all records
   218→
   219→**Monitor:**
   220→```bash
   221→# Xcode: Debug Navigator (Cmd+7) → Memory
   222→# Should stay < 300MB even with 420k records
   223→```
   224→
   225→## 📝 Code Style
   226→
   227→### Swift Conventions
   228→
   229→```swift
   230→// ✅ Good
   231→func fetchTopDomains(limit: Int = 10) async -> [DomainStats]
   232→
   233→// ❌ Bad
   234→func fetchTopDomains(_ limit: Int) async -> [DomainStats]
   235→
   236→// ✅ Good
   237→@MainActor
   238→class DataManager: ObservableObject
   239→
   240→// ❌ Bad
   241→class DataManager: ObservableObject // missing @MainActor
   242→```
   243→
   244→### Comments
   245→
   246→```swift
   247→// ✅ Good: Brief explanation of why
   248→// Use batch insert for performance with large datasets
   249→for batchStart in stride(from: 0, to: totalLines, by: batchSize) { ... }
   250→
   251→// ❌ Bad: Stating the obvious
   252→// Loop through batch
   253→for batchStart in stride(from: 0, to: totalLines, by: batchSize) { ... }
   254→```
   255→
   256→### SwiftUI Views
   257→
   258→```swift
   259→// ✅ Good: Extract subviews
   260→struct DomainRow: View { ... }
   261→
   262→// ❌ Bad: 300 lines in one body
   263→var body: some View {
   264→    VStack {
   265→        // ... 300 lines
   266→    }
   267→}
   268→```
   269→
   270→## 🔒 LGPD Compliance Rules
   271→
   272→### When Adding Features
   273→
   274→**Checklist:**
   275→- [ ] Does it collect new data? → Update `LGPDReport.dataFields`
   276→- [ ] Does it share data? → NO - reject feature
   277→- [ ] Does it store data externally? → NO - reject feature
   278→- [ ] Does it add telemetry? → NO - reject feature
   279→
   280→### Mandatory for All Features
   281→
   282→1. **Local-first:** No network calls (except user-initiated export)
   283→2. **Transparency:** Document in PrivacyView
   284→3. **Portability:** Include in export JSON
   285→4. **Deletion:** Remove in deleteAllData()
   286→
   287→## 🧪 Testing Protocol
   288→
   289→### Before Committing
   290→
   291→```bash
   292→# 1. Test all 4 tabs
   293→# - Overview: Stats display correctly
   294→# - Domains: Search and filters work
   295→# - Import: Progress updates in real-time
   296→# - Privacy: Export and delete work
   297→
   298→# 2. Test LGPD workflow
   299→# - Import → Export → Verify JSON → Delete → Verify stats = 0
   300→
   301→# 3. Test with different data sizes
   302→# - 100 emails: < 1s
   303→# - 1k emails: < 5s
   304→# - 10k emails: < 60s
   305→
   306→# 4. Check memory usage (Xcode Debug Navigator)
   307→# - Should stay < 300MB with 10k records
   308→```
   309→
   310→### Performance Benchmarks
   311→
   312→| Operation | 1k | 10k | Expected |
   313→|-----------|-----|-----|----------|
   314→| Import | 1s | 30s | < 1min |
   315→| Search | 0.1s | 0.5s | < 1s |
   316→| Export | 1s | 10s | < 30s |
   317→| Delete | 1s | 3s | < 10s |
   318→
   319→## 📚 Reference Documentation
   320→
   321→### Internal Docs
   322→- `README.md` - Complete project documentation
   323→- `LGPD-COMPLIANCE.md` - Legal compliance details
   324→- `QUICK-START.md` - User-facing quick start
   325→
   326→### External Docs
   327→- **SwiftUI:** https://developer.apple.com/documentation/swiftui
   328→- **CoreData:** https://developer.apple.com/documentation/coredata
   329→- **LGPD (Portuguese):** https://www.gov.br/anpd
   330→
   331→## 🚫 Don't Do This
   332→
   333→❌ Add external dependencies (Firebase, Alamofire, etc)
   334→❌ Add telemetry or analytics
   335→❌ Make network calls without user consent
   336→❌ Store data outside iOS sandbox
   337→❌ Add login/authentication system
   338→❌ Integrate with cloud services (unless CloudKit + opt-in)
   339→❌ Add ads or tracking
   340→❌ Collect more data than necessary
   341→
   342→## ✅ Do This
   343→
   344→✅ Keep 100% local processing
   345→✅ Use CoreData for persistence
   346→✅ Document LGPD compliance for new features
   347→✅ Add unit tests for new analytics logic
   348→✅ Keep memory usage < 300MB
   349→✅ Maintain sub-1s search response time
   350→✅ Update README when adding features
   351→✅ Test on real device (not just simulator)
   352→
   353→## 🔄 Git Workflow (If Applicable)
   354→
   355→```bash
   356→# Create feature branch
   357→git checkout -b feature/new-analytics
   358→
   359→# Make changes
   360→# Test thoroughly
   361→
   362→# Commit with descriptive message
   363→git commit -m "Add email prefix analysis to analytics engine
   364→
   365→- New method: analyzeEmailPrefixes() in DataManager
   366→- UI: PrefixesView in Features/Analytics/
   367→- LGPD: Added to export JSON
   368→- Performance: <1s for 10k emails"
   369→
   370→# Push
   371→git push origin feature/new-analytics
   372→```
   373→
   374→## 🆘 Getting Help
   375→
   376→1. Check inline comments in code
   377→2. Read README.md → Troubleshooting section
   378→3. Read QUICK-START.md for user-facing issues
   379→4. Profile with Xcode Instruments for performance
   380→5. Check Console.app for OSLog messages
   381→
   382→## 📊 Metrics to Maintain
   383→
   384→- **Build time:** < 60s (first build)
   385→- **App size:** < 5MB (release build)
   386→- **Memory usage:** < 300MB (with 420k records)
   387→- **Import speed:** ~2min for 420k emails (iPhone 15 Pro)
   388→- **Search latency:** < 1s (any query)
   389→- **Export time:** < 40s for 420k emails
   390→- **Code coverage:** N/A (no unit tests yet - future)
   391→
   392→---
   393→
   394→**Last Updated:** 2025-01-24
   395→**Project Status:** Complete, production-ready
   396→**iOS Target:** 17.0+
   397→**Swift Version:** 5.9+
   398→
   399→---
   400→
   401→*This file is for AI assistants (Claude Code) to understand the project structure and conventions.*
   402→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

# CLAUDE.md - EmailAnalyzer-iOS

**Guia para Claude Code trabalhar neste projeto**

## 🎯 Project Overview

EmailAnalyzer-iOS é um app iOS nativo para análise de grandes volumes de emails (420k+) com foco em:
- Categorização por domínios (.com, .br, .com.br)
- Analytics e estatísticas de distribuição
- Conformidade total com LGPD (Lei Geral de Proteção de Dados)
- 100% local, sem backend, sem telemetria

## 🏗 Architecture Summary

### Tech Stack

```
SwiftUI 100%          - UI framework (iOS 17.0+)
CoreData              - Persistence (SQLite) com índices
@Observable           - State management (iOS 17+)
async/await           - Concurrency
0 dependencies        - Apenas Apple frameworks
```

### Project Structure

```
EmailAnalyzer-iOS/
├── EmailAnalyzerApp.swift          # @main entry
├── MainTabView.swift               # 4 tabs navigation
├── Models/
│   ├── EmailRecord.swift          # CoreData entity
│   └── DomainStats.swift          # Analytics structs
├── Services/
│   └── DataManager.swift          # Singleton - CRUD, import, export
├── Features/
│   ├── Import/ImportView.swift    # File picker + progress
│   ├── Overview/OverviewView.swift # Stats dashboard
│   ├── Domains/DomainsView.swift  # Searchable list
│   └── Privacy/PrivacyView.swift  # LGPD compliance
├── Components/
│   └── StatsCard.swift            # Reusable UI
├── Extensions/
│   └── Color+Hex.swift            # Helpers
└── Resources/
    └── EmailAnalyzer.xcdatamodeld # CoreData schema
```

### Key Services

**DataManager.swift** (Singleton, @MainActor)
- Import emails from .txt (batch processing)
- Calculate statistics (total, unique, by TLD)
- Search and filter domains
- Export to JSON (LGPD portability)
- Delete all data (LGPD erasure)

**EmailRecord.swift** (CoreData NSManagedObject)
- Unique constraint on `email` field
- Indexed: `email`, `domain`, `tld`
- TLD extraction logic: .com.br → .br → .com → others

## 🔧 Common Tasks

### Working on Data Models

**Files:**
- `EmailAnalyzer-iOS/Models/EmailRecord.swift`
- `EmailAnalyzer-iOS/Resources/EmailAnalyzer.xcdatamodeld/EmailAnalyzer.xcdatamodel/contents`

**Rules:**
- If adding CoreData field, update BOTH files above
- Always maintain unique constraint on `email`
- Add index for any field used in WHERE clauses

**Example: Add new field**
```swift
// 1. EmailRecord.swift
@NSManaged public var newField: String

// 2. contents (XML)
<attribute name="newField" attributeType="String"/>

// 3. Update create() method to populate newField
```

### Working on Analytics

**File:** `EmailAnalyzer-iOS/Services/DataManager.swift`

**Common operations:**
```swift
// Aggregate query example (COUNT, GROUP BY)
let fetchRequest: NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: "EmailRecord")
fetchRequest.resultType = .dictionaryResultType
fetchRequest.propertiesToGroupBy = ["domain"]

// Performance rules:
// - Always use background context for heavy queries
// - Use batch operations (1000 records per save)
// - Return to @MainActor only for UI updates
```

### Working on UI

**Files:** `EmailAnalyzer-iOS/Features/*/`

**Patterns:**
- All views use `@EnvironmentObject var dataManager: DataManager`
- Async operations use `Task { await dataManager.method() }`
- SwiftUI `#Preview` for every view
- Pull-to-refresh: `.refreshable { await ... }`

**Example: Add new stat card**
```swift
// 1. Add to DomainStats.swift
struct NewStat { ... }

// 2. Add calculation to DataManager.swift
func calculateNewStat() async -> NewStat { ... }

// 3. Add UI to OverviewView.swift
StatsCard(title: "New Stat", value: "\(stat)", icon: "...", color: .blue)
```

### Working on LGPD Features

**File:** `EmailAnalyzer-iOS/Features/Privacy/PrivacyView.swift`

**Requirements:**
- Any new data field must be added to `LGPDReport.dataFields`
- Export must include all fields
- Delete must remove all data (no orphans)

**Testing LGPD:**
```bash
# 1. Import data
# 2. Export → verify JSON has all fields
# 3. Delete → verify stats go to 0
# 4. Reimport → verify data restored
```

## 🚀 Development Workflow

### Build and Run

```bash
# Open project
cd /Users/neog/EmailAnalyzer-iOS
open EmailAnalyzer-iOS.xcodeproj

# In Xcode:
# 1. Select simulator (iPhone 15 Pro recommended)
# 2. Cmd+R to build and run
```

### Testing with Data

```bash
# Generate test files
./generate-test-emails.sh

# This creates:
# - test-emails-small.txt (100)
# - test-emails-medium.txt (1k)
# - test-emails-large.txt (10k)
```

### Regenerate Xcode Project

```bash
# If you add/remove files:
ruby create-xcode-project.rb

# Then reopen in Xcode
```

## 🐛 Debugging

### CoreData Issues

**Symptom:** "Entity not found" or crashes
**Fix:**
```bash
# Delete app from simulator
xcrun simctl uninstall booted com.yourname.EmailAnalyzer-iOS

# Clean build
# Xcode: Product → Clean Build Folder (Cmd+Shift+K)

# Rebuild
# Xcode: Product → Build (Cmd+B)
```

### Performance Issues

**Symptom:** Import is slow or UI freezes

**Check:**
1. Background processing: All heavy operations must use `backgroundContext`
2. Batch size: Currently 1000 records/batch (adjustable in DataManager:91)
3. Indices: Verify CoreData model has indices on `email`, `domain`, `tld`

**Profile:**
```bash
# Xcode: Product → Profile (Cmd+I)
# Select "Time Profiler" or "Leaks"
```

### Memory Issues

**Symptom:** App crashes with large datasets

**Check:**
1. Queries use fetch limits (currently 500 for search)
2. No retained references to large arrays
3. Aggregate queries don't fetch all records

**Monitor:**
```bash
# Xcode: Debug Navigator (Cmd+7) → Memory
# Should stay < 300MB even with 420k records
```

## 📝 Code Style

### Swift Conventions

```swift
// ✅ Good
func fetchTopDomains(limit: Int = 10) async -> [DomainStats]

// ❌ Bad
func fetchTopDomains(_ limit: Int) async -> [DomainStats]

// ✅ Good
@MainActor
class DataManager: ObservableObject

// ❌ Bad
class DataManager: ObservableObject // missing @MainActor
```

### Comments

```swift
// ✅ Good: Brief explanation of why
// Use batch insert for performance with large datasets
for batchStart in stride(from: 0, to: totalLines, by: batchSize) { ... }

// ❌ Bad: Stating the obvious
// Loop through batch
for batchStart in stride(from: 0, to: totalLines, by: batchSize) { ... }
```

### SwiftUI Views

```swift
// ✅ Good: Extract subviews
struct DomainRow: View { ... }

// ❌ Bad: 300 lines in one body
var body: some View {
    VStack {
        // ... 300 lines
    }
}
```

## 🔒 LGPD Compliance Rules

### When Adding Features

**Checklist:**
- [ ] Does it collect new data? → Update `LGPDReport.dataFields`
- [ ] Does it share data? → NO - reject feature
- [ ] Does it store data externally? → NO - reject feature
- [ ] Does it add telemetry? → NO - reject feature

### Mandatory for All Features

1. **Local-first:** No network calls (except user-initiated export)
2. **Transparency:** Document in PrivacyView
3. **Portability:** Include in export JSON
4. **Deletion:** Remove in deleteAllData()

## 🧪 Testing Protocol

### Before Committing

```bash
# 1. Test all 4 tabs
# - Overview: Stats display correctly
# - Domains: Search and filters work
# - Import: Progress updates in real-time
# - Privacy: Export and delete work

# 2. Test LGPD workflow
# - Import → Export → Verify JSON → Delete → Verify stats = 0

# 3. Test with different data sizes
# - 100 emails: < 1s
# - 1k emails: < 5s
# - 10k emails: < 60s

# 4. Check memory usage (Xcode Debug Navigator)
# - Should stay < 300MB with 10k records
```

### Performance Benchmarks

| Operation | 1k | 10k | Expected |
|-----------|-----|-----|----------|
| Import | 1s | 30s | < 1min |
| Search | 0.1s | 0.5s | < 1s |
| Export | 1s | 10s | < 30s |
| Delete | 1s | 3s | < 10s |

## 📚 Reference Documentation

### Internal Docs
- `README.md` - Complete project documentation
- `LGPD-COMPLIANCE.md` - Legal compliance details
- `QUICK-START.md` - User-facing quick start

### External Docs
- **SwiftUI:** https://developer.apple.com/documentation/swiftui
- **CoreData:** https://developer.apple.com/documentation/coredata
- **LGPD (Portuguese):** https://www.gov.br/anpd

## 🚫 Don't Do This

❌ Add external dependencies (Firebase, Alamofire, etc)
❌ Add telemetry or analytics
❌ Make network calls without user consent
❌ Store data outside iOS sandbox
❌ Add login/authentication system
❌ Integrate with cloud services (unless CloudKit + opt-in)
❌ Add ads or tracking
❌ Collect more data than necessary

## ✅ Do This

✅ Keep 100% local processing
✅ Use CoreData for persistence
✅ Document LGPD compliance for new features
✅ Add unit tests for new analytics logic
✅ Keep memory usage < 300MB
✅ Maintain sub-1s search response time
✅ Update README when adding features
✅ Test on real device (not just simulator)

## 🔄 Git Workflow (If Applicable)

```bash
# Create feature branch
git checkout -b feature/new-analytics

# Make changes
# Test thoroughly

# Commit with descriptive message
git commit -m "Add email prefix analysis to analytics engine

- New method: analyzeEmailPrefixes() in DataManager
- UI: PrefixesView in Features/Analytics/
- LGPD: Added to export JSON
- Performance: <1s for 10k emails"

# Push
git push origin feature/new-analytics
```

## 🆘 Getting Help

1. Check inline comments in code
2. Read README.md → Troubleshooting section
3. Read QUICK-START.md for user-facing issues
4. Profile with Xcode Instruments for performance
5. Check Console.app for OSLog messages

## 📊 Metrics to Maintain

- **Build time:** < 60s (first build)
- **App size:** < 5MB (release build)
- **Memory usage:** < 300MB (with 420k records)
- **Import speed:** ~2min for 420k emails (iPhone 15 Pro)
- **Search latency:** < 1s (any query)
- **Export time:** < 40s for 420k emails
- **Code coverage:** N/A (no unit tests yet - future)

---

**Last Updated:** 2025-01-24
**Project Status:** Complete, production-ready
**iOS Target:** 17.0+
**Swift Version:** 5.9+

---

*This file is for AI assistants (Claude Code) to understand the project structure and conventions.*


total 32
drwxr-xr-x@ 31 neog  staff    992 Dec 28 20:50 .
drwxr-xr-x@  5 neog  staff    160 Dec 21 21:47 ..
-rw-r--r--@  1 neog  staff  14340 Dec 28 14:45 .DS_Store
drwx------@ 20 neog  staff    640 Dec  4 20:49 17Licoes-macOS
drwxr-xr-x@ 12 neog  staff    384 Dec 17 21:05 AnatoMed-macOS
drwxr-xr-x@  8 neog  staff    256 Dec  5 03:32 AroundMe-macOS
drwxr-xr-x@  9 neog  staff    288 Dec 28 20:07 BRDataMiner
drwxr-xr-x@  7 neog  staff    224 Dec 22 03:17 ClaudeCodeAI
drwxr-xr-x@  4 neog  staff    128 Dec 28 20:54 ContentCapture
drwxr-xr-x@  5 neog  staff    160 Dec 24 02:52 FlightFinder-macOS
drwxr-xr-x@ 29 neog  staff    928 Dec 28 14:04 GhostWriter
drwxr-xr-x@  9 neog  staff    288 Dec 23 21:02 InstagramDMAnalyzer
drwxr-xr-x@  5 neog  staff    160 Dec 23 19:39 InstagramLeadScraper
drwxr-xr-x@  6 neog  staff    192 Dec 23 18:31 InstagramUnfollower
drwxr-xr-x@  9 neog  staff    288 Dec 23 22:08 MentorMonitor-macOS
drwxr-xr-x@ 18 neog  staff    576 Dec 13 12:56 MetaScheduler
drwxr-xr-x@  7 neog  staff    224 Dec 24 00:42 NEOG-Awaken
drwxr-xr-x@  9 neog  staff    288 Dec 23 16:23 NEOG-Finance
drwxr-xr-x@  6 neog  staff    192 Dec 22 00:30 NEOG-Reflect
drwxr-xr-x@  9 neog  staff    288 Dec 25 03:32 NEOGHub
drwxr-xr-x@ 11 neog  staff    352 Dec 13 12:56 NEOGWorkspaceManager-macOS
drwxr-xr-x@  4 neog  staff    128 Dec 23 06:26 ProbabilitySimulator
drwxr-xr-x@  9 neog  staff    288 Dec 22 18:59 ReputacaoDigital-macOS
drwxr-xr-x@ 12 neog  staff    384 Dec 24 00:01 SobrietyGuard-macOS
drwxr-xr-x@  5 neog  staff    160 Dec 27 01:58 TypingMaster-macOS
drwxr-xr-x@  7 neog  staff    224 Dec 28 15:22 VPNMonitor-macOS
drwxr-xr-x@  6 neog  staff    192 Dec 23 04:14 WhatsAppAnalyzer-macOS
drwxr-xr-x@  9 neog  staff    288 Dec 20 22:38 WhatsAppValidator
drwxr-xr-x@ 23 neog  staff    736 Dec 25 19:10 YouTubeAudio-macOS
drwxr-xr-x@  4 neog  staff    128 Dec 26 14:56 YouTubeDownloader-macOS
drwxr-xr-x@ 16 neog  staff    512 Dec 27 00:52 YouTubeTranscripts-macOS


     1→# CLAUDE.md - 96Blocks-iOS
     2→
     3→## Project Overview
     4→
     5→**96Blocks-iOS** is a B2B SaaS iOS application for day planning with ROI tracking. The core concept divides each day into 96 blocks of 15 minutes each, allowing users to plan, track, and measure the monetary value of their time.
     6→
     7→### Key Features
     8→
     9→- **96-Block Timeline**: Vertical timeline showing all 96 blocks of the day
    10→- **ROI Tracking**: Estimated and actual monetary value (R$) per block
    11→- **Task Backlog**: Task management with priority, category, and time estimates
    12→- **Goals**: High-level objectives with progress tracking
    13→- **Templates**: Pre-defined day schedules (Workday, Weekend, Focus Day)
    14→- **Analytics**: Productivity score, ROI efficiency, category breakdown
    15→
    16→## Tech Stack
    17→
    18→- **UI**: SwiftUI (iOS 17+)
    19→- **Data**: SwiftData
    20→- **Architecture**: MVVM with @MainActor
    21→- **Platforms**: iPhone, iPad, Mac Catalyst
    22→- **Dependencies**: None (pure Apple frameworks)
    23→
    24→## Project Structure
    25→
    26→```
    27→96Blocks-iOS/
    28→├── App/
    29→│   ├── 96BlocksApp.swift         # @main entry point
    30→│   └── MainTabView.swift         # Adaptive navigation
    31→├── Models/
    32→│   ├── Block.swift               # 15-min block model
    33→│   ├── Task.swift                # Backlog task model
    34→│   ├── Goal.swift                # Goal tracking
    35→│   ├── Template.swift            # Day templates
    36→│   └── DailySummary.swift        # Analytics summary
    37→├── Services/
    38→│   └── DataManager.swift         # SwiftData manager
    39→├── Views/
    40→│   ├── DayPlanner/
    41→│   │   ├── DayPlannerView.swift  # Main timeline view
    42→│   │   └── BlockRow.swift        # Individual block cell
    43→│   ├── Backlog/
    44→│   │   └── BacklogView.swift     # Task management
    45→│   ├── Analytics/
    46→│   │   └── AnalyticsView.swift   # ROI dashboard
    47→│   └── Settings/
    48→│       └── SettingsView.swift    # Configuration
    49→├── Components/
    50→│   └── HapticManager.swift       # Haptic feedback
    51→└── Extensions/
    52→```
    53→
    54→## Data Models
    55→
    56→### Block (Core)
    57→- `blockIndex`: 0-95 (00:00 to 23:45)
    58→- `title`: Task description
    59→- `category`: work, personal, health, learning, meeting, focus, break, sleep
    60→- `estimatedValueBRL`: Expected ROI in R$
    61→- `actualValueBRL`: Real ROI achieved
    62→- `status`: planned, inProgress, completed, skipped
    63→
    64→### Task96 (Backlog)
    65→- `priority`: low, medium, high, urgent
    66→- `estimatedBlocks`: Number of 15-min blocks needed
    67→- `estimatedValueBRL`: Expected value
    68→- `goalId`: Link to parent goal
    69→
    70→### Goal
    71→- `targetValueBRL`: Target monetary value
    72→- `timeframe`: weekly, monthly, quarterly, yearly
    73→- `valueGeneratedBRL`: Progress tracking
    74→
    75→## Quick Commands
    76→
    77→```bash
    78→# Generate Xcode project
    79→cd ~/Apps/iOS/96Blocks-iOS
    80→ruby generate-xcode-project.rb
    81→
    82→# Open project
    83→open 96Blocks-iOS.xcodeproj
    84→
    85→# Build for simulator
    86→xcodebuild -project 96Blocks-iOS.xcodeproj \
    87→  -scheme 96Blocks-iOS \
    88→  -sdk iphonesimulator \
    89→  -destination 'platform=iOS Simulator,name=iPhone 17 Pro'
    90→```
    91→
    92→## Key Patterns
    93→
    94→### DataManager (Singleton)
    95→```swift
    96→@MainActor
    97→class DataManager: ObservableObject {
    98→    static let shared = DataManager()
    99→    let modelContainer: ModelContainer
   100→
   101→    func getBlocks(for date: Date) -> [Block]
   102→    func getTodayROI() -> (estimated: Decimal, actual: Decimal)
   103→    func getProductivityScore() -> Int
   104→}
   105→```
   106→
   107→### Block Time Calculation
   108→```swift
   109→// Block index to time
   110→let hour = blockIndex / 4        // 0-23
   111→let minute = (blockIndex % 4) * 15  // 0, 15, 30, 45
   112→
   113→// Current block
   114→let currentIndex = hour * 4 + minute / 15
   115→```
   116→
   117→### ROI Calculation
   118→```swift
   119→let efficiency = actual / estimated * 100  // Percentage
   120→let score = (completionRate * 0.4) + (roiEfficiency * 0.4) + (taskScore * 0.2)
   121→```
   122→
   123→## Future Enhancements (Phase 2+)
   124→
   125→1. **AI Integration**: Claude API for automatic day planning
   126→2. **Backend API**: FastAPI for multi-tenant B2B
   127→3. **Team Features**: Dashboard admin, team analytics
   128→4. **Web Dashboard**: Next.js for desktop access
   129→5. **Notifications**: Block reminders, daily summary
   130→6. **Widgets**: Home screen productivity widget
   131→
   132→## Related Documentation
   133→
   134→- **Business Plan**: `~/.claude/plans/buzzing-painting-hoare.md`
   135→- **ProductivityHub Reference**: `~/Apps/iOS/ProductivityHub-iOS/CLAUDE.md`
   136→- **MeusFIIs AI Pattern**: `~/Apps/iOS/MeusFIIs-iOS/Services/AI/`
   137→
   138→---
   139→
   140→**Created**: 2025-12-08
   141→**Version**: 1.0.0 (MVP)
   142→**Status**: Ready for Development
   143→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

# CLAUDE.md - 96Blocks-iOS

## Project Overview

**96Blocks-iOS** is a B2B SaaS iOS application for day planning with ROI tracking. The core concept divides each day into 96 blocks of 15 minutes each, allowing users to plan, track, and measure the monetary value of their time.

### Key Features

- **96-Block Timeline**: Vertical timeline showing all 96 blocks of the day
- **ROI Tracking**: Estimated and actual monetary value (R$) per block
- **Task Backlog**: Task management with priority, category, and time estimates
- **Goals**: High-level objectives with progress tracking
- **Templates**: Pre-defined day schedules (Workday, Weekend, Focus Day)
- **Analytics**: Productivity score, ROI efficiency, category breakdown

## Tech Stack

- **UI**: SwiftUI (iOS 17+)
- **Data**: SwiftData
- **Architecture**: MVVM with @MainActor
- **Platforms**: iPhone, iPad, Mac Catalyst
- **Dependencies**: None (pure Apple frameworks)

## Project Structure

```
96Blocks-iOS/
├── App/
│   ├── 96BlocksApp.swift         # @main entry point
│   └── MainTabView.swift         # Adaptive navigation
├── Models/
│   ├── Block.swift               # 15-min block model
│   ├── Task.swift                # Backlog task model
│   ├── Goal.swift                # Goal tracking
│   ├── Template.swift            # Day templates
│   └── DailySummary.swift        # Analytics summary
├── Services/
│   └── DataManager.swift         # SwiftData manager
├── Views/
│   ├── DayPlanner/
│   │   ├── DayPlannerView.swift  # Main timeline view
│   │   └── BlockRow.swift        # Individual block cell
│   ├── Backlog/
│   │   └── BacklogView.swift     # Task management
│   ├── Analytics/
│   │   └── AnalyticsView.swift   # ROI dashboard
│   └── Settings/
│       └── SettingsView.swift    # Configuration
├── Components/
│   └── HapticManager.swift       # Haptic feedback
└── Extensions/
```

## Data Models

### Block (Core)
- `blockIndex`: 0-95 (00:00 to 23:45)
- `title`: Task description
- `category`: work, personal, health, learning, meeting, focus, break, sleep
- `estimatedValueBRL`: Expected ROI in R$
- `actualValueBRL`: Real ROI achieved
- `status`: planned, inProgress, completed, skipped

### Task96 (Backlog)
- `priority`: low, medium, high, urgent
- `estimatedBlocks`: Number of 15-min blocks needed
- `estimatedValueBRL`: Expected value
- `goalId`: Link to parent goal

### Goal
- `targetValueBRL`: Target monetary value
- `timeframe`: weekly, monthly, quarterly, yearly
- `valueGeneratedBRL`: Progress tracking

## Quick Commands

```bash
# Generate Xcode project
cd ~/Apps/iOS/96Blocks-iOS
ruby generate-xcode-project.rb

# Open project
open 96Blocks-iOS.xcodeproj

# Build for simulator
xcodebuild -project 96Blocks-iOS.xcodeproj \
  -scheme 96Blocks-iOS \
  -sdk iphonesimulator \
  -destination 'platform=iOS Simulator,name=iPhone 17 Pro'
```

## Key Patterns

### DataManager (Singleton)
```swift
@MainActor
class DataManager: ObservableObject {
    static let shared = DataManager()
    let modelContainer: ModelContainer

    func getBlocks(for date: Date) -> [Block]
    func getTodayROI() -> (estimated: Decimal, actual: Decimal)
    func getProductivityScore() -> Int
}
```

### Block Time Calculation
```swift
// Block index to time
let hour = blockIndex / 4        // 0-23
let minute = (blockIndex % 4) * 15  // 0, 15, 30, 45

// Current block
let currentIndex = hour * 4 + minute / 15
```

### ROI Calculation
```swift
let efficiency = actual / estimated * 100  // Percentage
let score = (completionRate * 0.4) + (roiEfficiency * 0.4) + (taskScore * 0.2)
```

## Future Enhancements (Phase 2+)

1. **AI Integration**: Claude API for automatic day planning
2. **Backend API**: FastAPI for multi-tenant B2B
3. **Team Features**: Dashboard admin, team analytics
4. **Web Dashboard**: Next.js for desktop access
5. **Notifications**: Block reminders, daily summary
6. **Widgets**: Home screen productivity widget

## Related Documentation

- **Business Plan**: `~/.claude/plans/buzzing-painting-hoare.md`
- **ProductivityHub Reference**: `~/Apps/iOS/ProductivityHub-iOS/CLAUDE.md`
- **MeusFIIs AI Pattern**: `~/Apps/iOS/MeusFIIs-iOS/Services/AI/`

---

**Created**: 2025-12-08
**Version**: 1.0.0 (MVP)
**Status**: Ready for Development