# Debugging

This guide covers debugging tools and techniques for OrchardGo.

## React Native Debugger

### Enable Debugging

**iOS Simulator:**
- Press `Cmd + D`
- Select "Debug" from menu

**Android Emulator:**
- Press `Cmd + M` (macOS) or `Ctrl + M` (Windows/Linux)
- Select "Debug" from menu

**Physical Device:**
- Shake the device
- Select "Debug" from menu

### Chrome DevTools

React Native debugging uses Chrome DevTools:

1. Enable debugging from dev menu
2. Browser opens automatically: `http://localhost:8081/debugger-ui`
3. Use Chrome DevTools for:
   - Console logging
   - Breakpoints
   - Network inspection (limited)
   - React DevTools

**Note:** The new debugger doesn't include Network Inspector. Use proxy tools like [Proxyman](https://proxyman.io/) or [Charles](https://www.charlesproxy.com/) instead.

## Hermes Debugger

OrchardGo uses Hermes engine in production for better performance.

### Enable Hermes for Debugging (Temporary)

**iOS:**
Edit `ios/Podfile:61`:
```ruby
:hermes_enabled => true  # Change false to true
```

**Android:**
Edit `android/gradle.properties:39`:
```properties
hermesEnabled=true  # Change false to true
```

Then:
```bash
yarn install
```

**⚠️ IMPORTANT:** Do not commit these changes! Hermes debugging breaks CodePush and Sentry.

### Revert After Debugging

```bash
# Revert changes
git checkout ios/Podfile android/gradle.properties

# Reinstall
yarn install
```

## Appium Inspector

Appium Inspector allows you to inspect app elements for testing and debugging.

### Setup

1. **Start Appium Server:**
   ```bash
   yarn appium:run
   ```

2. **Download Appium Inspector:**
   Download from [GitHub Releases](https://github.com/appium/appium-inspector/releases)

3. **Open Appium Inspector:**
   ```bash
   yarn appium:inspector
   ```

### iOS Configuration

```json
{
  "platformName": "iOS",
  "platformVersion": "17.0",
  "deviceName": "iPhone 15",
  "automationName": "XCUITest",
  "appium_url": "http://0.0.0.0:4723",
  "settings[snapshotMaxDepth]": 62
}
```

Replace `platformVersion` and `deviceName` with your simulator specs.

### Android Configuration

```json
{
  "platformName": "Android",
  "appium:automationName": "UiAutomator2",
  "appium:platformVersion": "14",
  "appium:deviceName": "Medium_Phone_API_34",
  "appium:appium_url": "http://0.0.0.0:4723",
  "appium:appWaitActivity": "*",
  "appium:noReset": false,
  "appium:appWaitDuration": 60000,
  "appium:adbExecTimeout": 60000,
  "appium:appWaitForLaunch": false,
  "appium:fullReset": false,
  "appium:enforceAppInstall": true,
  "appium:systemPort": 8222,
  "appium:newCommandTimeout": 60000,
  "appium:ignoreHiddenApiPolicyError": true
}
```

Replace `platformVersion` and `deviceName` with your emulator specs.

## Network Debugging

### Proxyman (Recommended)

Proxyman provides HTTP/HTTPS traffic inspection.

1. Install [Proxyman](https://proxyman.io/)
2. Configure device/simulator proxy
3. Install SSL certificate
4. View all network requests

### Charles Proxy

Alternative to Proxyman:

1. Install [Charles](https://www.charlesproxy.com/)
2. Configure proxy settings
3. Enable SSL proxying
4. Monitor traffic

### React Native Network Logger

For in-app network logging:

```typescript
import { startNetworkLogging } from 'react-native-network-logger';

// In development only
if (__DEV__) {
  startNetworkLogging();
}
```

## Redux DevTools

### Redux Flipper Plugin

1. Install Flipper desktop app
2. Install Redux plugin
3. View state, actions, and diffs

### Redux Logger (Console)

```typescript
import { createLogger } from 'redux-logger';

const logger = createLogger({
  predicate: () => __DEV__,
  collapsed: true,
});
```

## Console Logging

### Best Practices

```typescript
// Basic logging
console.log('User logged in:', user);

// Warnings
console.warn('Deprecated method used');

// Errors
console.error('API request failed:', error);

// Groups for organized output
console.group('User Actions');
console.log('Login');
console.log('Profile updated');
console.groupEnd();

// Tables for structured data
console.table([
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 }
]);
```

### Remove Console Logs in Production

Babel automatically removes console logs in production builds.

## Performance Debugging

### React DevTools Profiler

1. Enable profiler in dev menu
2. Record interaction
3. Analyze component render times

### Performance Monitor

From dev menu → "Show Performance Monitor"

Displays:
- RAM usage
- JavaScript heap
- Views count
- UI/JS frame rates

## Error Tracking

### Sentry

Sentry tracks errors in production:
- Automatic error capture
- Source maps for stack traces
- Breadcrumbs for context
- Release tracking

View errors at: [Sentry Dashboard](https://sentry.io)

### DataDog

DataDog provides monitoring and logs:
- Real User Monitoring (RUM)
- Error tracking
- Performance metrics
- Custom logs

Dashboards:
- [Production CodePush](https://app.datadoghq.com/dashboard/bk2-s6f-vtz/prod-code-push-server-release-radar)
- [QA CodePush](https://app.datadoghq.com/dashboard/74n-raq-nip)

## Platform-Specific Debugging

### iOS Debugging

#### Xcode Console

```bash
# Open in Xcode
yarn xcode

# View console: View → Debug Area → Activate Console
# Shows native logs, crashes, and warnings
```

#### iOS Simulator Logs

```bash
# View device logs
xcrun simctl spawn booted log stream --level=debug

# Filter by app
xcrun simctl spawn booted log stream --predicate 'processImagePath contains "OrchardGo"'
```

### Android Debugging

#### Logcat

```bash
# View all logs
adb logcat

# Filter by app
adb logcat | grep "OrchardGo"

# Clear logs
adb logcat -c

# Save to file
adb logcat > logcat.txt
```

#### Android Studio Logcat

1. Open Android Studio
2. View → Tool Windows → Logcat
3. Filter by package name

## Debugging Deep Links

### Android

```bash
# Send deep link to Android device/emulator
yarn android:deeplink:send "https://yourdomain.com/path"

# Or use adb directly
adb shell am start -W -a android.intent.action.VIEW \
  -d "https://yourdomain.com/path" \
  com.theorchard.orchardgo
```

### iOS

```bash
# Send deep link to iOS simulator
xcrun simctl openurl booted "https://yourdomain.com/path"
```

See [Dynamic Links Guide](../guides/dynamic-links.md) for more details.

## Debugging Push Notifications

See [Push Notifications Guide](../guides/push-notifications.md) for:
- Sending test notifications
- iOS simulator push testing
- Android notification debugging

## Common Issues

### App Crashes Immediately

1. Check Xcode/Logcat console for crash logs
2. Verify environment configuration
3. Clear derived data/build folders
4. Reinstall dependencies

### White Screen / Blank Screen

1. Check Metro bundler is running
2. Reload JavaScript: Dev Menu → Reload
3. Reset Metro cache: `yarn reset`
4. Check console for errors

### "Unable to Connect to Remote Debugger"

1. Ensure Metro bundler is running
2. Check port 8081 is not blocked
3. Disable other debugging tools
4. Restart Metro: `yarn reset`

### Source Maps Not Loading

1. Verify Metro bundler has source maps enabled
2. Clear Chrome cache
3. Restart debugging session

## Debugging CodePush Updates

```bash
# Check CodePush status
LOCALAPPDATA=. yarn code-push-standalone deployment ls OrchardGoIOS --displayKeys

# View deployment history
yarn codepush:history
```

## Next Steps

- [Running the App](./running-the-app.md)
- [Testing](./testing.md)
- [Scripts Reference](./scripts-reference.md)
- [Troubleshooting Common Issues](../reference/troubleshooting.md)
