# Analyze-Trip Edge Function Enhancement

## Overview
Enhanced the `analyze-trip` edge function with advanced metrics calculation, density-based scoring, and comprehensive debug information to provide intelligent tour recommendations.

## Key Enhancements

### 1. Distance & Duration Calculations

Each place now includes:
- **Distance from previous place**: Calculated using Haversine formula (km)
- **Travel time from previous place**: Estimated based on distance (assuming 40 km/h average speed)
- **Visit duration**: Parsed from duration string (e.g., "2 hours" → 120 minutes)

**Example Output:**
```json
{
  "name": "Göreme Open Air Museum",
  "type": "museum",
  "lat": 38.6425,
  "lng": 34.8317,
  "distanceFromPreviousKm": 3.2,
  "travelTimeFromPreviousMinutes": 5,
  "visitDurationMinutes": 120
}
```

### 2. Daily Density Score

Each day is analyzed with a comprehensive density score:

**Formula:**
```
density_score = (total_distance_km * 5 + total_time_hours * 10) / number_of_places
```

**Density Levels:**
- **Low** (<20): Self-planning is manageable
- **Moderate** (20-35): Tour is optional but could add value
- **High** (35-50): Tour is recommended
- **Very High** (≥50): Tour is highly recommended

**Metrics Calculated:**
- Total places per day
- Total distance traveled (km)
- Total travel time (minutes)
- Total visit time (minutes)
- Total time commitment (hours)
- Density score and level

**Example Daily Metrics:**
```json
{
  "dayNumber": 1,
  "date": "2024-06-15",
  "totalPlaces": 5,
  "totalDistanceKm": 45.3,
  "totalTravelTimeMinutes": 68,
  "totalVisitTimeMinutes": 360,
  "totalTimeMinutes": 428,
  "densityScore": 42.8,
  "densityLevel": "high"
}
```

### 3. AI Decision Logic Based on Density

The AI now makes recommendations based on density scores:

**Decision Thresholds:**
- Density ≥50: Highly recommend tour (confidence ≥0.85)
- Density 35-50: Recommend tour (confidence 0.70-0.85)
- Density 20-35: Optional tour (confidence 0.50-0.70)
- Density <20: Don't recommend tour (confidence <0.50)

**Additional Factors:**
1. **Total Distance**: >100km strongly suggests organized transportation
2. **Time Commitment**: >8 hours/day suggests professional guidance
3. **Group Size**: ≥4 travelers benefit from private guide
4. **Place Count**: ≥5 places/day requires efficient routing

### 4. Debug Information

Comprehensive debug info explaining every recommendation:

**Structure:**
```json
{
  "debug_info": {
    "dailyMetrics": [...],
    "overallMetrics": {
      "totalDays": 3,
      "totalPlaces": 12,
      "totalDistanceKm": 125.7,
      "totalTimeHours": 18.5,
      "averageDensityScore": 38.2,
      "maxDensityScore": 48.5
    },
    "decisionFactors": [
      {
        "factor": "High Density Day",
        "value": 48.5,
        "impact": "positive",
        "reasoning": "At least one day has high density (35-50), suggesting tour guidance would improve experience."
      },
      {
        "factor": "Long Distance Travel",
        "value": "126 km",
        "impact": "positive",
        "reasoning": "Total distance exceeds 100km, organized transportation would save time and reduce stress."
      }
    ],
    "recommendation_reasoning": "AI Analysis: Your plan has high density with 126km total distance. A guided tour would optimize routing and save approximately 2 hours. Confidence: 82%. Max density score: 48.5."
  }
}
```

## Technical Implementation

### Helper Functions

1. **calculateDistance()**: Haversine formula for accurate distance calculation
2. **parseDurationToMinutes()**: Converts duration strings to minutes
3. **estimateTravelTime()**: Calculates travel time based on distance
4. **calculateDensityScore()**: Computes daily density score
5. **getDensityLevel()**: Categorizes density into levels
6. **analyzeTripMetrics()**: Main analysis function for all days

### Enhanced Interfaces

```typescript
interface Place {
  name: string;
  type: string;
  lat?: number;
  lng?: number;
  duration?: string;
  // Calculated metrics
  distanceFromPreviousKm?: number;
  travelTimeFromPreviousMinutes?: number;
  visitDurationMinutes?: number;
}

interface DayMetrics {
  dayNumber: number;
  date: string;
  totalPlaces: number;
  totalDistanceKm: number;
  totalTravelTimeMinutes: number;
  totalVisitTimeMinutes: number;
  totalTimeMinutes: number;
  densityScore: number;
  densityLevel: 'low' | 'moderate' | 'high' | 'very_high';
  places: Place[];
}

interface DebugInfo {
  dailyMetrics: DayMetrics[];
  overallMetrics: {
    totalDays: number;
    totalPlaces: number;
    totalDistanceKm: number;
    totalTimeHours: number;
    averageDensityScore: number;
    maxDensityScore: number;
  };
  decisionFactors: {
    factor: string;
    value: string | number;
    impact: 'positive' | 'negative' | 'neutral';
    reasoning: string;
  }[];
  recommendation_reasoning: string;
}
```

## AI Prompt Enhancement

The AI prompt now includes:
- Detailed density analysis for each day
- Per-place distance and travel time information
- Decision factors with impact assessment
- Clear density-based decision guidelines
- Confidence calculation formula

## Response Examples

### High Density Trip (Recommend Tour)

```json
{
  "recommend": true,
  "reason": "Your itinerary has very high density (score: 52.3) with 135km total distance. A guided tour would optimize routing and save approximately 3 hours.",
  "recommended_type": "daily_tour",
  "daily_tour_slug": "red_tour",
  "confidence": 0.87,
  "comparison_metrics": {
    "distance_saved_km": 40,
    "time_saved_hours": 3.2,
    "logistics_removed": ["Ticket purchasing", "Transfer arrangement", "Guide finding", "Route planning"],
    "expert_value": ["Local expert knowledge", "Historical information", "Hidden spots", "Local recommendations"]
  },
  "debug_info": {
    "overallMetrics": {
      "maxDensityScore": 52.3,
      "totalDistanceKm": 135.0,
      "totalTimeHours": 22.5
    },
    "decisionFactors": [
      {
        "factor": "Very High Density Day",
        "value": 52.3,
        "impact": "positive",
        "reasoning": "At least one day has very high density (≥50), indicating complex logistics that would benefit from professional tour organization."
      }
    ]
  }
}
```

### Low Density Trip (No Recommendation)

```json
{
  "recommend": false,
  "reason": "Your plan has low density (score: 15.2) with manageable distances. Self-planning is feasible.",
  "confidence": 0.38,
  "debug_info": {
    "overallMetrics": {
      "maxDensityScore": 15.2,
      "totalDistanceKm": 28.0,
      "totalTimeHours": 8.5
    },
    "decisionFactors": [
      {
        "factor": "Low Density",
        "value": 15.2,
        "impact": "negative",
        "reasoning": "Days have low density (<20), self-planning is manageable."
      }
    ]
  }
}
```

## Benefits

1. **Data-Driven Decisions**: Recommendations based on quantifiable metrics, not just place count
2. **Transparency**: Users can see exactly why a tour was recommended
3. **Accurate Calculations**: Real distance and time estimates using geographic coordinates
4. **Flexible Thresholds**: Density scoring adapts to different trip complexities
5. **Debugging Support**: Comprehensive debug info helps developers understand AI decisions

## Usage

The function is automatically called when analyzing trip itineraries. No changes needed to the API call:

```typescript
const response = await supabase.functions.invoke('analyze-trip', {
  body: {
    destination: 'Cappadocia',
    days: [...],
    travelers: 2,
    interests: ['history', 'nature']
  }
});

// Response now includes debug_info
const { recommend, confidence, debug_info } = response.data;
```

## Future Enhancements

Potential improvements:
- Real-time traffic data integration
- Weather-based adjustments
- Seasonal crowd density factors
- User feedback loop for confidence calibration
- Machine learning model for pattern recognition
