# Daily Quest System - Integration Guide

## Overview

The Daily Quest System provides players with 3 daily quests (easy/medium/hard) that award diamonds upon completion. This guide explains how to integrate quest tracking into existing game systems.

## Files Created

- `/home/user/lichun/ws/retention/daily_quests.py` - Main quest system implementation
- `/home/user/lichun/ws/retention/__init__.py` - Updated with quest exports

## Database Tables

Already created in migration `001_monetization_and_retention.sql`:

- `daily_quest_templates` - Quest definitions (11 quest types pre-populated)
- `player_daily_quests` - Player quest assignments and progress

## Quest Types Implemented

### Easy Quests (5-10 diamonds)
- `talk_to_characters` - Talk to 3 different characters
- `buy_item` - Buy an item from the store
- `attend_class` - Attend 2 classes
- `socialize` - Socialize with friends (2 times)

### Medium Quests (15-20 diamonds)
- `work_hours` - Work for 6 hours
- `go_on_date` - Go on a date
- `complete_activities` - Complete 5 activities
- `study` - Study for 4 hours

### Hard Quests (25-35 diamonds)
- `spend_energy` - Spend 50 energy on activities
- `earn_money` - Earn $500
- `increase_affinity` - Increase affinity by 20 points total

## API Functions

### Core Functions

```python
from retention.daily_quests import (
    generate_daily_quests,      # Assign 3 quests per day
    update_quest_progress,      # Track progress
    complete_quest,             # Mark complete & award diamonds
    get_active_quests,          # Get today's quests
    get_quest_statistics,       # Get completion stats
    handle_daily_quest_check,   # WebSocket handler
    initialize_quest_templates  # Server startup
)
```

### Function Usage

#### 1. Generate Daily Quests
```python
# Call on first login of day or at midnight
quests = generate_daily_quests(player_id)
# Returns: List[Dict] with 3 quest objects
```

#### 2. Update Quest Progress
```python
# Call after any tracked action
result = update_quest_progress(player_id, 'work_hours', 2)
# Returns: Dict with updated quest data or None if no matching quest

# Check if quest was just completed
if result and result.get('just_completed'):
    # Quest completed! Diamonds already awarded
    pass
```

#### 3. Get Active Quests
```python
# Get player's current daily quests
quests = get_active_quests(player_id)
# Returns: List of 3 quest dicts with progress/status
```

## Integration Points

### 1. Server Startup (app.py)

Add quest template initialization:

```python
# In app.py startup sequence
from retention.daily_quests import initialize_quest_templates

async def startup():
    # ... existing startup code ...
    initialize_quest_templates()
    logging.info("Daily quest templates initialized")
```

### 2. Player Connection (app.py)

Check and assign daily quests on login:

```python
# In WebSocket connection handler
async def handle_player_connect(player_id, websocket):
    # ... existing connection code ...

    # Check daily quests
    from retention.daily_quests import handle_daily_quest_check
    handle_daily_quest_check(player_id, send_message_to_client)
```

### 3. Conversation System

Track "talk to characters" quest:

**File:** `ws/conversationEvents.py` or conversation handler

```python
# After successful conversation/message sent
from retention.daily_quests import update_quest_progress

def handle_conversation(player_id, target_id, message):
    # ... existing conversation logic ...

    # Update quest progress
    update_quest_progress(player_id, 'talk_to_characters', 1)
```

### 4. Work/Employment System

Track work hours and activity completion:

**File:** `ws/intradayActivity.py` or work event handlers

```python
# After work activity completes
from retention.daily_quests import update_quest_progress

def handle_work_activity(player, hours_worked):
    # ... existing work logic ...

    # Update work hours quest
    update_quest_progress(player.id, 'work_hours', hours_worked)

    # Update generic activity quest
    update_quest_progress(player.id, 'complete_activities', 1)

    # Track money earned for quest
    if money_earned > 0:
        update_quest_progress(player.id, 'earn_money', money_earned)
```

### 5. Education System

Track class attendance and study hours:

**File:** `ws/events.py` or education handlers

```python
# After attending class
from retention.daily_quests import update_quest_progress

def handle_class_attendance(player_id):
    # ... existing class logic ...

    update_quest_progress(player_id, 'attend_class', 1)
    update_quest_progress(player_id, 'complete_activities', 1)

# After studying
def handle_study_session(player_id, hours):
    # ... existing study logic ...

    update_quest_progress(player_id, 'study', hours)
    update_quest_progress(player_id, 'complete_activities', 1)
```

### 6. Shopping System

Track item purchases:

**File:** Store/purchase handlers

```python
# After successful purchase
from retention.daily_quests import update_quest_progress

def handle_purchase(player_id, item_id, price):
    # ... existing purchase logic ...

    update_quest_progress(player_id, 'buy_item', 1)
```

### 7. Dating/Relationship System

Track dates and affinity increases:

**File:** Relationship event handlers

```python
# When date starts
from retention.daily_quests import update_quest_progress

def handle_date_activity(player_id, partner_id):
    # ... existing date logic ...

    update_quest_progress(player_id, 'go_on_date', 1)
    update_quest_progress(player_id, 'complete_activities', 1)

# When affinity increases
def handle_affinity_increase(player_id, target_id, amount):
    # ... existing affinity logic ...

    update_quest_progress(player_id, 'increase_affinity', amount)
```

### 8. Social Activities

Track socializing with friends:

**File:** Social activity handlers

```python
# After social activity (hangout, party, etc.)
from retention.daily_quests import update_quest_progress

def handle_socialize(player_id):
    # ... existing social logic ...

    update_quest_progress(player_id, 'socialize', 1)
    update_quest_progress(player_id, 'complete_activities', 1)
```

### 9. Energy System

Track energy spending:

**File:** Activity/energy deduction handlers

```python
# When energy is spent on any activity
from retention.daily_quests import update_quest_progress

def deduct_energy(player, amount):
    # ... existing energy deduction ...

    update_quest_progress(player.id, 'spend_energy', amount)
```

### 10. Daily Reset (Midnight)

Reset and generate new quests at midnight:

**File:** `ws/app.py` in daily reset logic

```python
# In daily reset function
from retention.daily_quests import generate_daily_quests

async def handle_daily_reset(player_id):
    # ... existing reset logic ...

    # Generate new daily quests
    new_quests = generate_daily_quests(player_id)

    # Notify client
    await send_to_client(player_id, {
        'type': 'dailyQuestsAssigned',
        'quests': new_quests
    })
```

## WebSocket Messages

### Client → Server

```javascript
// Request current quests
{
    type: "getActiveQuests"
}
```

### Server → Client

```javascript
// New quests assigned
{
    type: "dailyQuestsAssigned",
    quests: [
        {
            id: 123,
            quest_type: "work_hours",
            description: "Work for 6 hours",
            progress: 0,
            progress_required: 6,
            diamond_reward: 15,
            difficulty: "medium",
            icon_name: "briefcase",
            completed: false
        },
        // ... 2 more quests
    ]
}

// Quest progress update
{
    type: "questProgress",
    quest_id: 123,
    progress: 3,
    progress_required: 6
}

// Quest completed
{
    type: "questComplete",
    quest_id: 123,
    reward: 15  // diamonds awarded
}

// Current quest status
{
    type: "dailyQuestsStatus",
    quests: [/* array of quest objects */]
}
```

## Testing Checklist

- [ ] Server starts without errors (quest templates initialized)
- [ ] Player receives 3 quests on first login of day
- [ ] Quest progress updates when performing tracked actions
- [ ] Quest completes and awards diamonds when progress reaches requirement
- [ ] Quest progress persists across sessions
- [ ] New quests assigned at midnight/next day
- [ ] Statistics tracking works (get_quest_statistics)
- [ ] Multiple quest types can progress simultaneously
- [ ] Completed quests don't continue tracking progress

## Error Handling

All functions include try/catch error handling and logging:

```python
# Errors are logged but don't crash the system
try:
    update_quest_progress(player_id, 'work_hours', 2)
except Exception as e:
    # Logged automatically, quest system fails gracefully
    pass
```

## Performance Notes

- Quest checks use indexed queries (player_id + assigned_date)
- Only active quests for current day are queried
- Progress updates are single UPDATE statements
- No N+1 query problems

## Future Enhancements

Potential additions (not implemented yet):

1. **Weekly Quests** - Longer-term challenges
2. **Special Event Quests** - Holiday/seasonal quests
3. **Quest Chains** - Multi-day quest sequences
4. **Quest Rerolls** - Spend diamonds to change a quest
5. **Bonus Objectives** - Extra rewards for completing all 3
6. **Quest Notifications** - Push notifications for quest completion

## Support

For questions or issues:
- Check logs: Look for "daily quest" or "quest progress" in server logs
- Database: Query `player_daily_quests` to see player's quests
- Debug: Add extra logging to `update_quest_progress()` calls
