# Firebase Analytics & Crashlytics Setup Guide

This guide explains how to integrate Firebase Analytics and Crashlytics into the BaoLife iOS app.

## Prerequisites

- Xcode 14.0 or later
- iOS 15.0+ deployment target
- Firebase account (free tier available)
- Bundle identifier registered in Apple Developer account

## Step 1: Create Firebase Project

1. Go to [Firebase Console](https://console.firebase.google.com/)
2. Click **Add project**
3. Enter project name (e.g., "BaoLife")
4. Enable/disable Google Analytics (recommended: enable)
5. Click **Create project**

## Step 2: Register iOS App in Firebase

1. In Firebase Console, click **Add app** → **iOS**
2. Enter your iOS bundle ID (found in Xcode project settings)
   - Example: `com.yourcompany.lichunWebsocket`
3. Enter app nickname (optional): "BaoLife iOS"
4. Enter App Store ID (optional, for later)
5. Click **Register app**

## Step 3: Download GoogleService-Info.plist

1. Download the `GoogleService-Info.plist` file from Firebase Console
2. **Important**: Do NOT rename this file
3. Add the file to your Xcode project:
   - Drag `GoogleService-Info.plist` into your Xcode project navigator
   - Check "Copy items if needed"
   - Select your main target (lichunWebsocket)
   - Verify it appears in the project root directory

**Security Note**: Add `GoogleService-Info.plist` to `.gitignore` to avoid committing sensitive API keys to version control.

## Step 4: Add Firebase SDK via Swift Package Manager

1. In Xcode, go to **File → Add Packages...**
2. Enter the Firebase SDK URL:
   ```
   https://github.com/firebase/firebase-ios-sdk
   ```
3. Select version: **10.20.0** or later
4. Click **Add Package**
5. Select the following products for your target:
   - ✅ **FirebaseAnalytics**
   - ✅ **FirebaseCrashlytics**
   - ✅ **FirebaseCore** (automatically included)
6. Click **Add Package**

### Troubleshooting Package Installation

If you encounter issues:
- Close and reopen Xcode
- Clean build folder: **Product → Clean Build Folder** (⇧⌘K)
- Reset package caches: **File → Packages → Reset Package Caches**

## Step 5: Configure Build Settings

### 5.1 Add Run Script for Crashlytics

1. In Xcode, select your project → **Targets** → **Build Phases**
2. Click **+** → **New Run Script Phase**
3. Drag the run script phase above "Compile Sources"
4. Name it: "Firebase Crashlytics"
5. Add the following script:

```bash
# Type a script or drag a script file from your workspace to insert its path.
"${BUILD_DIR%/Build/*}/SourcePackages/checkouts/firebase-ios-sdk/Crashlytics/run"
```

6. Add Input Files:
```
${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${TARGET_NAME}
${BUILT_PRODUCTS_DIR}/${INFOPLIST_PATH}
```

### 5.2 Enable Debug Information Format

1. Select your target → **Build Settings**
2. Search for "Debug Information Format"
3. Set **Debug** to: `DWARF with dSYM File`
4. Set **Release** to: `DWARF with dSYM File`

### 5.3 Verify Build Configuration

The `lichunWebsocketApp.swift` file already contains Firebase initialization code:

```swift
#if canImport(FirebaseCore)
FirebaseApp.configure()

// Analytics Configuration
#if canImport(FirebaseAnalytics)
Analytics.setAnalyticsCollectionEnabled(true)
Analytics.setSessionTimeoutInterval(1800) // 30 minutes
#endif

// Crashlytics Configuration
#if canImport(FirebaseCrashlytics)
#if DEBUG
Crashlytics.crashlytics().setCrashlyticsCollectionEnabled(false)
#else
Crashlytics.crashlytics().setCrashlyticsCollectionEnabled(true)
#endif
#endif
#endif
```

## Step 6: Testing Analytics in Debug Mode

### 6.1 Enable Debug Logging

Add launch arguments in your Xcode scheme:
1. **Product → Scheme → Edit Scheme...**
2. Select **Run → Arguments**
3. Add to **Arguments Passed On Launch**:
   ```
   -FIRDebugEnabled
   -FIRAnalyticsDebugEnabled
   ```

### 6.2 Verify Events in Console

Run your app and check Xcode console for analytics logs:
```
📊 Analytics: onboarding_complete
📊 Analytics: screen_viewed
   Parameters: ["screen_name": "home", "screen_class": "HomeView"]
```

### 6.3 DebugView in Firebase Console

1. Run app with debug arguments
2. Go to Firebase Console → **Analytics → DebugView**
3. Select your device from dropdown
4. View real-time events (up to 1-hour delay for standard view)

## Step 7: Testing Crashlytics

### 7.1 Force a Test Crash (Debug Mode)

Add a test button to trigger a crash:

```swift
Button("Test Crash") {
    fatalError("Test crash for Crashlytics")
}
```

### 7.2 Verify Crash Reports

1. Trigger the crash
2. Relaunch the app (crash reports are sent on next launch)
3. Check Firebase Console → **Crashlytics**
4. First crash may take 5-10 minutes to appear

### 7.3 Test Non-Fatal Errors

```swift
Button("Test Error") {
    let error = NSError(domain: "TestDomain", code: 123)
    AnalyticsManager.shared.recordError(error, additionalInfo: [
        "test": true
    ])
}
```

## Step 8: Production Configuration

### 8.1 Disable Analytics for Debug Builds

The app already disables Crashlytics in debug mode:
```swift
#if DEBUG
Crashlytics.crashlytics().setCrashlyticsCollectionEnabled(false)
#else
Crashlytics.crashlytics().setCrashlyticsCollectionEnabled(true)
#endif
```

### 8.2 Upload dSYM Files for Release Builds

For TestFlight and App Store builds:

1. Enable automatic dSYM upload in build settings
2. Or manually upload dSYMs:
   ```bash
   /path/to/pods/FirebaseCrashlytics/upload-symbols \
     -gsp /path/to/GoogleService-Info.plist \
     -p ios /path/to/dSYMs
   ```

### 8.3 Privacy Manifest (iOS 17+)

Add analytics usage to your Privacy Manifest:
1. Create `PrivacyInfo.xcprivacy` if not exists
2. Add tracking domains and data usage declarations

## Analytics Implementation Overview

### Events Tracked

The `AnalyticsManager` tracks the following event categories:

#### App Lifecycle
- `app_launched`
- `app_backgrounded`
- `app_foregrounded`

#### Onboarding
- `onboarding_step_complete` (with step number)
- `onboarding_complete`

#### Character
- `character_created` (age, gender)
- `character_death` (age, cause)

#### Purchases
- `purchase_initiated` (item_id, item_name, price)
- `purchase_completed` (item_id, item_name, price, currency)
- `purchase_failed` (item_id, reason)
- `iap_initiated` (product_id)
- `iap_completed` (product_id, revenue, currency)
- `iap_failed` (product_id, reason)

#### Activities
- `activity_enrolled` (activity_id, activity_type, activity_name)
- `activity_performed` (activity_id, energy_cost)
- `activity_quit` (activity_id, reason)
- `job_applied` (job_id, job_title)
- `job_quit` (job_id, job_title)

#### Dating
- `dating_swipe` (direction, character_id)
- `dating_match` (character_id)
- `date_started` (activity_name, energy_cost, money_cost)
- `gift_sent` (character_id, gift_type)
- `relationship_started` (character_id, status)
- `relationship_ended` (character_id, status, reason)

#### Navigation
- `tab_switched` (from_tab, to_tab)
- `screen_viewed` (screen_name, screen_class)

#### WebSocket
- `websocket_connected`
- `websocket_disconnected` (reason)
- `websocket_error` (error_type, message)
- `server_error` (error_code, message)

### Screen Views Tracked

The following screens automatically track views:
- Home (`home`)
- Activity Detail (`activity_detail`)
- Dating (`dating`)
- Messages (`messages`)
- Store (`store`)

### User Properties Set

- `character_name` - Character's first name
- `character_age` - Character's current age
- User ID - Character's unique ID

## Usage Examples

### Track a Custom Event

```swift
// Simple event
AnalyticsManager.shared.track(.appLaunched)

// Event with parameters
AnalyticsManager.shared.track(.purchaseCompleted(
    itemId: "item_123",
    itemName: "Golden Watch",
    price: 500
))
```

### Track Screen View

```swift
.onAppear {
    AnalyticsManager.shared.trackScreenView("profile", screenClass: "ProfileView")
}
```

### Record Error

```swift
do {
    try somethingRisky()
} catch {
    AnalyticsManager.shared.recordError(error, additionalInfo: [
        "context": "user_action",
        "user_id": userId
    ])
}
```

### Log Breadcrumb

```swift
AnalyticsManager.shared.log("User tapped purchase button")
```

## Viewing Data in Firebase Console

### Analytics Dashboard

1. Go to Firebase Console → **Analytics → Dashboard**
2. View metrics:
   - Active users (DAU, WAU, MAU)
   - User engagement
   - Event counts
   - Screen views

### Custom Reports

1. Go to **Analytics → Events**
2. Click on any event to see details
3. Create custom audiences based on events
4. Export data to BigQuery for advanced analysis

### Crashlytics Dashboard

1. Go to Firebase Console → **Crashlytics**
2. View crash-free users percentage
3. Click on individual crashes to see:
   - Stack traces
   - Device information
   - Custom keys and logs
   - Number of affected users

## Best Practices

### DO:
- ✅ Track meaningful user actions (purchases, completions)
- ✅ Use descriptive event names (snake_case)
- ✅ Include context in error logs
- ✅ Test analytics in debug mode before release
- ✅ Review analytics regularly to understand user behavior

### DON'T:
- ❌ Track PII (personally identifiable information)
- ❌ Log sensitive data (passwords, tokens)
- ❌ Track excessive events (> 500 distinct types)
- ❌ Send large parameter values (> 100 characters)
- ❌ Enable debug logging in production

## Privacy & Compliance

### GDPR Compliance

Users can disable analytics:
```swift
AnalyticsManager.shared.setAnalyticsEnabled(false)
```

### User Data Deletion

To delete user data from Firebase:
1. Firebase Console → **Project Settings → Users and Permissions**
2. Request user data deletion via Firebase CLI

### App Store Privacy Labels

Declare the following data types collected:
- **Analytics**: User interactions, app usage
- **Crash Data**: Crash logs, performance data
- **Device ID**: Used for analytics tracking

## Troubleshooting

### Events Not Appearing in Console

- Wait 1-4 hours for events to appear in standard view
- Use DebugView for real-time testing
- Verify `GoogleService-Info.plist` is in bundle
- Check Xcode console for error messages

### Crashlytics Not Receiving Crashes

- Verify dSYM files are uploaded
- Ensure app was relaunched after crash
- Check Firebase Console for processing status
- Verify run script is in Build Phases

### Build Errors

```
'FirebaseCore/FirebaseCore.h' file not found
```
**Solution**: Clean build folder and rebuild

```
Command PhaseScriptExecution failed
```
**Solution**: Check Crashlytics run script path

### Performance Issues

- Analytics batches events (sent every ~60 seconds)
- Excessive logging can impact performance
- Use `#if DEBUG` guards for development-only logs

## Support & Resources

- [Firebase iOS Documentation](https://firebase.google.com/docs/ios/setup)
- [Analytics Event Reference](https://firebase.google.com/docs/reference/swift/firebaseanalytics/api/reference/Classes/Analytics)
- [Crashlytics Documentation](https://firebase.google.com/docs/crashlytics)
- [Stack Overflow - Firebase](https://stackoverflow.com/questions/tagged/firebase)

## Migration Notes

If migrating from another analytics platform:
1. Map existing events to new `AnalyticsEvent` enum
2. Update event parameters to match Firebase conventions
3. Test side-by-side for a transition period
4. Archive old analytics data before switching

---

**Last Updated**: 2025-01-12
**Maintained By**: BaoLife Development Team
**Version**: 1.0
