# EV Charging Feature

## Overview

When `FeatureFlags.enableEVCharging = true`, the app discovers EV charging stations along planned trip routes using Apple's MapKit APIs.

## Feature Flag

```swift
// SportsTime/Core/FeatureFlags.swift
enum FeatureFlags {
    static let enableEVCharging = false  // Set to true to enable
}
```

## API Calls

### 1. MKDirections (Route Calculation)

**Purpose:** Get actual driving route polylines between stops

**When called:** After trip planning completes, for each travel segment

**Call pattern:**
- 1 call per travel segment (city-to-city)
- A 5-city trip = 4 MKDirections calls

**Response includes:**
- Route polyline (used for EV charger search)
- Actual driving distance (replaces Haversine estimate)
- Expected travel time

### 2. MKLocalPointsOfInterestRequest (EV Charger Search)

**Purpose:** Find EV charging stations near sample points along the route

**When called:** For each sample point along the route polyline

**Call pattern:**
- Routes are sampled every 100 miles
- Each sample point triggers 1 POI search
- 5-mile search radius around each point

**Example:**
| Route Distance | Sample Points | POI Searches |
|----------------|---------------|--------------|
| 100 miles      | 2 (start+end) | 2 calls      |
| 300 miles      | 4             | 4 calls      |
| 500 miles      | 6             | 6 calls      |

## Total API Overhead

### Per Travel Segment
```
1 MKDirections call + (distance_miles / 100) MKLocalSearch calls
```

### Example: Boston → New York → Philadelphia → Washington DC

| Segment | Distance | MKDirections | POI Searches | Total |
|---------|----------|--------------|--------------|-------|
| BOS→NYC | 215 mi   | 1            | 3            | 4     |
| NYC→PHL | 95 mi    | 1            | 2            | 3     |
| PHL→DC  | 140 mi   | 1            | 2            | 3     |
| **Total** |        | **3**        | **7**        | **10 calls** |

## Performance Impact

### Latency Added to Trip Planning

| Component | Time per Call | Notes |
|-----------|---------------|-------|
| MKDirections | 200-500ms | Network round-trip |
| MKLocalSearch (POI) | 100-300ms | Per sample point |

**Typical overhead:** 2-5 seconds added to trip planning

### Parallel Processing

- All travel segments are enriched in parallel (using Swift TaskGroup)
- POI searches within a segment are sequential (to avoid rate limiting)

## Rate Limiting

### Apple MapKit Limits

- MapKit has daily quotas based on your Apple Developer account
- Free tier: ~25,000 service requests/day
- Paid tier: Higher limits available

### Our Mitigations

1. **Feature is opt-in** - Only runs when user enables "EV Charging Needed"
2. **Reasonable sampling** - 100-mile intervals, not every mile
3. **Deduplication** - Chargers appearing in multiple searches are deduplicated
4. **Fail gracefully** - If POI search fails, trip planning continues without chargers

## Data Flow

```
User enables "EV Charging Needed" toggle
            ↓
Trip planning runs (sync, Haversine estimates)
            ↓
ItineraryBuilder.enrichWithEVChargers() called
            ↓
For each travel segment (in parallel):
    ├── MKDirections.calculate() → Get polyline
    └── EVChargingService.findChargersAlongRoute()
            ├── Sample polyline every 100 miles
            ├── MKLocalPointsOfInterestRequest per sample
            ├── Filter to .evCharger category
            └── Deduplicate results
            ↓
TravelSegment.evChargingStops populated
            ↓
TripDetailView shows expandable charger list
```

## Files Involved

| File | Purpose |
|------|---------|
| `Core/FeatureFlags.swift` | Feature toggle |
| `Core/Services/EVChargingService.swift` | POI search logic |
| `Planning/Engine/ItineraryBuilder.swift` | Enrichment orchestration |
| `Features/Trip/ViewModels/TripCreationViewModel.swift` | Triggers enrichment |
| `Features/Trip/Views/TripDetailView.swift` | Displays chargers |
| `Core/Models/Domain/TravelSegment.swift` | EVChargingStop model |

## Testing Notes

1. **Simulator limitations** - MapKit POI results may be limited in simulator
2. **Test on device** - Real EV charger data requires physical device
3. **Monitor console** - Look for `[ItineraryBuilder]` log messages showing charger counts

## Future Improvements

- Cache EV charger results to reduce API calls on re-planning
- Allow configurable sample interval (50mi for shorter range EVs)
- Show chargers on the map view
- Filter by charger network (Tesla, Electrify America, etc.)
