# BaoLife Backend Architecture Diagram

## System Overview

```
┌─────────────────────────────────────────────────────────────────────────┐
│                         iOS Client (SwiftUI)                             │
└────────────────────────┬────────────────────────────────────────────────┘
                         │ WebSocket: wss://lichun.app/wss/
                         │ 
                         ▼
        ┌────────────────────────────────────────────┐
        │      WebSocket Server (app.py:711 lines)   │
        │  - async handler() - Connection manager    │
        │  - async consumer() - Message router       │
        │  - async producer() - Update broadcaster   │
        │  - async initLifeSim() - Game tick engine  │
        │  - Port: 8001 (asyncio + websockets)       │
        └─────────┬──────────────────┬───────────────┘
                  │                  │
                  ▼                  ▼
        ┌──────────────────┐  ┌─────────────────────┐
        │   Game Engine    │  │  Event System       │
        │ functions.py     │  │ events.py (1238 ln) │
        │ (2862 lines)     │  │ dayEvents.py        │
        │                  │  │ conversationEvents  │
        │ - loadGame()     │  │ - 50+ life events   │
        │ - saveGame()     │  │ - Question system   │
        │ - character ops  │  │ - AI responses      │
        │ - state mgmt     │  │ - Dilemma system    │
        └────────┬─────────┘  └──────────┬──────────┘
                 │                       │
                 └───────────┬───────────┘
                             │
                             ▼
        ┌──────────────────────────────────────────┐
        │        MySQL Database (60+ tables)        │
        │  InnoDB, Connection Pooling, Indexes     │
        └──────────────────────────────────────────┘
                             │
    ┌────────────┬───────────┼───────────┬─────────┐
    │            │           │           │         │
    ▼            ▼           ▼           ▼         ▼
   Core      Monetization Retention  Dating  Analytics
   Tables    (Phase 1)   (Phase 2)  (Phase 3)  (Phase 6)
   (40+)     (14 new)    (14 new)   (5 new)    (3 new)
```

---

## Module Architecture by Phase

### CORE MODULES (Original)
```
ws/
├── app.py              - WebSocket server entry point
├── functions.py        - Game state, DB operations
├── events.py           - Event system
├── intradayActivity.py - Activity execution
├── conversationEvents  - AI conversations
└── rate_limiter.py     - Request throttling
```

### PHASE 1: MONETIZATION (Components 9-12)
```
monetization/
├── energy_refills.py    - Buy energy (4 tiers, 10-50💎)
├── time_skips.py        - Skip time (4 types, 5-100💎)
├── diamond_economy.py   - Currency tracking
└── validation.py        - Rate limit + idempotency check
```

### PHASE 2: RETENTION (Components 18-21)
```
retention/
├── achievements.py      - 44 achievements (5 categories)
├── daily_rewards.py     - 7-day login cycle (125💎/week)
├── daily_quests.py      - 11 quest types (15-100💎/day)
├── statistics.py        - 16 lifetime stats + photo album
└── tutorial.py          - Onboarding system
```

### PHASE 3-4: DATING (Components 28, 33, 43, 54)
```
dating/
├── bio_generator.py     - AI NPC bio generation
├── compatibility.py     - Personality match (0-100%)
├── relationship_events  - 18K lines of relationship content
├── date_activities.py   - Multiple venue types
└── matching.py          - Match suggestions
```

### PHASE 5: PERFORMANCE (Components 44-45)
```
performance/
├── caching.py           - LRU cache (256 entries, 5-min TTL)
├── batch_messaging.py   - Message batching
└── offline/
    └── queue.py         - Offline queue (1000 events, 7 days)
```

### PHASE 6: MONITORING (Components 54-57)
```
analytics/
└── events.py            - Event tracking + buffering

monitoring/
├── performance.py       - Operation duration metrics
└── sentry_setup.py      - Error reporting (10% sampling)

experiments/
└── ab_testing.py        - Feature flags (7 variants)

errors/
└── error_handler.py     - Unified error handling
```

### PHASE 7: LEGAL & PRODUCTION (Components 63-65)
```
deployment/
├── health_check.py      - Kubernetes probes
└── production_checklist - 200+ items

api/
└── data_management.py   - GDPR export/delete (30-day grace)

static/
├── privacy.html         - Privacy policy
├── terms.html           - Terms of service
└── support.html         - Support center
```

---

## Data Flow: Purchase Example

```
Client (iOS)
    │
    ├─ Send: {"type": "purchase_energy_refill", "refill_type": "full"}
    │
    ▼
app.py: consumer()
    │
    ├─ Parse message type
    │
    ▼
validation.py: @rate_limit decorator
    │
    ├─ Check: 10 purchases/minute?
    │
    ▼
validation.py: IdempotencyManager
    │
    ├─ Check: Duplicate IAP? (SHA256 key)
    │
    ▼
energy_refills.py: purchase_energy_refill()
    │
    ├─ Validate: Player has diamonds?
    │
    ▼
database: UPDATE players SET diamonds = diamonds - 35
database: INSERT INTO energy_refill_purchases (...)
database: INSERT INTO diamond_transactions (...)
    │
    ▼
analytics/events.py: track_purchase_completed()
    │
    ├─ Add to buffer (flushed at 100 events)
    │
    ▼
Send response to client:
{
  "type": "energy_updated",
  "energy": 100,
  "diamonds": 965,
  "transaction_id": "uuid"
}
```

---

## Data Flow: Daily Login Example

```
Client reconnects
    │
    ├─ Send: {"type": "check_daily_login"}
    │
    ▼
app.py: consumer()
    │
    ▼
daily_rewards.py: check_daily_login()
    │
    ├─ Query: player_login_streak
    │ 
    ├─ Check: Last login > 24 hours?
    │   ├─ YES: Reset streak to 1
    │   └─ NO: Increment streak
    │
    ├─ Check: New day reward available?
    │
    ▼
daily_rewards.py: claim_daily_reward()
    │
    ├─ Get day's reward (1-7)
    ├─ Award diamonds + energy + item
    │
    ▼
database: INSERT INTO player_login_streak
database: UPDATE players SET diamonds = diamonds + amount
database: INSERT INTO diamond_transactions
    │
    ▼
statistics.py: increment_stat('total_login_days')
    │
    ▼
Send to client:
{
  "type": "daily_reward_claimed",
  "day": 3,
  "reward": "15 diamonds + 50 energy",
  "streak": 3
}
```

---

## Database Schema Relationships

```
┌─────────────────────────────────────────────────────────────────┐
│                       CORE TABLES (~40)                         │
├─────────────────────────────────────────────────────────────────┤
│ users                    characters          locations           │
│ ├─ userID (PK)          ├─ characterID       ├─ locationID       │
│ ├─ email                ├─ userID (FK)       ├─ name             │
│ └─ created_at           └─ stats             └─ type             │
└──────┬──────────────────────────────────────────────────────────┘
       │
       ├─────────────────────┬────────────────────┬──────────────┐
       │                     │                    │              │
       ▼                     ▼                    ▼              ▼
┌──────────────────┐ ┌──────────────────┐ ┌────────────────┐ ┌────────────────┐
│ MONETIZATION     │ │ RETENTION        │ │ DATING         │ │ ANALYTICS      │
├──────────────────┤ ├──────────────────┤ ├────────────────┤ ├────────────────┤
│Phase 1 (14 tbl) │ │Phase 2 (14 tbl) │ │Phase 3 (5 tbl)│ │Phase 6 (3 tbl)│
├──────────────────┤ ├──────────────────┤ ├────────────────┤ ├────────────────┤
│ energy_refill    │ │ achievements     │ │ npc_bios       │ │ analytics_     │
│ _purchases       │ │ (44 records)     │ │                │ │ events         │
│                  │ │                  │ │ dating_        │ │                │
│ time_skip_       │ │ player_          │ │ compatibility  │ │ analytics_     │
│ purchases        │ │ achievements     │ │                │ │ sessions       │
│                  │ │                  │ │ relationship_  │ │                │
│ diamond_         │ │ daily_login_     │ │ events         │ │ deletion_log   │
│ transactions     │ │ rewards          │ │                │ │ (GDPR)         │
│                  │ │                  │ │ date_          │ │                │
│ processed_       │ │ player_login_    │ │ venues         │ │                │
│ transactions     │ │ streak           │ │                │ │                │
│ (idempotency)    │ │                  │ │ date_          │ │                │
│                  │ │ daily_quest_     │ │ activities     │ │                │
│                  │ │ templates (11)   │ │                │ │                │
│                  │ │                  │ │                │ │                │
│                  │ │ player_daily_    │ │                │ │                │
│                  │ │ quests           │ │                │ │                │
│                  │ │                  │ │                │ │                │
│                  │ │ player_          │ │                │ │                │
│                  │ │ statistics       │ │                │ │                │
│                  │ │                  │ │                │ │                │
│                  │ │ player_photo_    │ │                │ │                │
│                  │ │ album            │ │                │ │                │
│                  │ │                  │ │                │ │                │
│                  │ │ player_inventory │ │                │ │                │
└──────────────────┘ └──────────────────┘ └────────────────┘ └────────────────┘
```

---

## Message Flow Architecture

```
                    ┌─────────────────────┐
                    │   Client (iOS)      │
                    │  (SwiftUI App)      │
                    └──────────┬──────────┘
                               │
                  (WebSocket: wss://lichun.app/wss/)
                               │
                ┌──────────────▼───────────────┐
                │   app.py: handler()          │
                │ - Register connection        │
                │ - Start producer() + consumer()
                └──────┬──────────────┬────────┘
                       │              │
                       ▼              ▼
            ┌──────────────────┐  ┌───────────────┐
            │ producer()       │  │ consumer()    │
            │ (Server → Client)│  │ (Client→Srv) │
            ├──────────────────┤  ├───────────────┤
            │ Time updates     │  │ Parse msg type│
            │ State updates    │  │ Route handler │
            │ Event prompts    │  │ Execute logic │
            │ Notifications    │  │ Call functions│
            │ Batch messages   │  │ Update DB     │
            │                  │  │ Send response │
            └──────────────────┘  └───────────────┘
                       ▲                  │
                       │                  ▼
                       │         ┌─────────────────────┐
                       │         │ Message Handlers    │
                       │         ├─────────────────────┤
                       │         │ purchase_*          │
                       │         │ check_daily_login   │
                       │         │ update_quest_*      │
                       │         │ start_conversation  │
                       │         │ answer_question     │
                       │         │ export_data         │
                       │         └────────┬────────────┘
                       │                  │
                       │                  ▼
                       │         ┌─────────────────────┐
                       │         │ Module Functions    │
                       │         ├─────────────────────┤
                       │         │ monetization/*      │
                       │         │ retention/*         │
                       │         │ dating/*            │
                       │         │ functions.py        │
                       │         │ events.py           │
                       │         └────────┬────────────┘
                       │                  │
                       │                  ▼
                       │         ┌─────────────────────┐
                       │         │ Database Operations │
                       │         ├─────────────────────┤
                       │         │ SELECT             │
                       │         │ UPDATE             │
                       │         │ INSERT             │
                       │         │ DELETE (rare)      │
                       │         └────────┬────────────┘
                       │                  │
                       │                  ▼
                       │         ┌─────────────────────┐
                       │         │ MySQL Database      │
                       │         │ (60+ tables)        │
                       │         └─────────────────────┘
                       │
                       └──── Batch response messages
```

---

## Performance Architecture

```
┌────────────────────────────────────────────────────────┐
│  Client Request                                        │
└─────────────┬──────────────────────────────────────────┘
              │
              ▼
┌────────────────────────────────────────────────────────┐
│ Performance Monitor: @measure_performance decorator    │
│ - Start timer                                          │
│ - Generate unique ID                                  │
│ - Track percentiles (p50, p95, p99)                    │
└─────────────┬──────────────────────────────────────────┘
              │
              ▼
┌────────────────────────────────────────────────────────┐
│ Rate Limiter: @rate_limit(10/min) decorator           │
│ - Check bucket                                         │
│ - Check time window                                    │
│ - Allow or reject                                      │
└─────────────┬──────────────────────────────────────────┘
              │
              ▼
┌────────────────────────────────────────────────────────┐
│ Player Data Cache: player_cache.get(user_id)          │
│ - Check in-memory LRU (256 entries)                    │
│ - TTL: 5 minutes                                       │
│ - Hit: Return cached                                   │
│ - Miss: Load from DB + cache                           │
└─────────────┬──────────────────────────────────────────┘
              │
              ▼
┌────────────────────────────────────────────────────────┐
│ Business Logic Execution                              │
│ - Update game state                                    │
│ - Process achievements                                │
│ - Track statistics                                    │
└─────────────┬──────────────────────────────────────────┘
              │
              ▼
┌────────────────────────────────────────────────────────┐
│ Message Batcher: queue for batch delivery              │
│ - Add to batch queue                                   │
│ - Check batch size (10 messages)                       │
│ - Time interval (100ms)                                │
│ - Batch ready: Flush to WebSocket                      │
│ - Not ready: Queue and wait                            │
└─────────────┬──────────────────────────────────────────┘
              │
              ▼
┌────────────────────────────────────────────────────────┐
│ Analytics Tracker: track_event()                       │
│ - Add to event buffer                                  │
│ - Buffer size: 100 events                              │
│ - Batch to DB when full                               │
└─────────────┬──────────────────────────────────────────┘
              │
              ▼
┌────────────────────────────────────────────────────────┐
│ Client Response                                        │
│ - Batch of 1-10 messages                              │
│ - WebSocket send                                      │
└─────────────┬──────────────────────────────────────────┘
              │
              ▼
┌────────────────────────────────────────────────────────┐
│ Monitoring                                             │
│ - Log operation time                                   │
│ - Update percentile stats                              │
│ - Alert if >1 second                                   │
│ - Track in Sentry                                      │
└────────────────────────────────────────────────────────┘
```

---

## Offline Mode Architecture

```
Client connects normally
         │
         ▼
  ┌──────────────┐
  │ CONNECTED    │
  │ Real-time    │
  │ game loop    │
  └──────┬───────┘
         │
         ├─ Network failure
         │
         ▼
  ┌──────────────────────────┐
  │ DISCONNECTED             │
  │ - Cache player state     │
  │ - Queue offline actions  │
  │ - Simulate local time    │
  └──────┬───────────────────┘
         │
         ├─ Player takes action
         │
         ▼
  ┌──────────────────────────┐
  │ Offline Queue (max 1000)  │
  │ - Store event            │
  │ - Set timestamp          │
  │ - Maintain order         │
  │ - Max age: 7 days        │
  └──────┬───────────────────┘
         │
         ├─ Network returns / Reconnect
         │
         ▼
  ┌──────────────────────────┐
  │ On Reconnect             │
  │ - Sync offline duration  │
  │ - Replay queued events   │
  │ - Resolve conflicts      │
  │ - Catch up with server   │
  │ - Re-enter game loop     │
  └──────┬───────────────────┘
         │
         ▼
  ┌──────────────┐
  │ CONNECTED    │
  │ Synced state │
  └──────────────┘
```

---

## Security & Compliance Architecture

```
┌──────────────────────────────────────────────────────────┐
│ SECURITY LAYERS                                          │
├──────────────────────────────────────────────────────────┤
│ 1. Rate Limiting (@rate_limit decorator)                │
│    - 10 purchases/min (energy)                           │
│    - 5 purchases/min (time skips)                        │
│    - Exponential backoff on exceed                       │
│                                                          │
│ 2. Idempotency (SHA256 keys)                             │
│    - Processed_transactions table                        │
│    - Prevents duplicate IAP processing                   │
│    - Audit trail for all purchases                       │
│                                                          │
│ 3. Input Validation                                      │
│    - Parameterized SQL queries (SQL injection safe)     │
│    - Type checking on all inputs                         │
│    - Balance validation before deductions               │
│                                                          │
│ 4. Error Handling (Sentry)                               │
│    - 10% trace sampling                                 │
│    - 10% profile sampling                               │
│    - Player context in errors                           │
│    - Breadcrumb tracking                                │
│                                                          │
│ 5. GDPR Compliance                                       │
│    - Data export (Article 20)                            │
│    - Account deletion with 30-day grace                 │
│    - Hard deletion after grace period                   │
│    - Deletion log audit trail                           │
│    - Transaction isolation (REPEATABLE READ)            │
│                                                          │
│ 6. PII Protection                                        │
│    - No PII in logs (Sentry: send_default_pii=False)    │
│    - Deletion of data on account removal                │
│    - Encrypted API credentials via env vars            │
└──────────────────────────────────────────────────────────┘
```

---

## A/B Testing Architecture

```
Player connects
         │
         ▼
    ┌─────────────────────────────┐
    │ get_variant(player_id, flag) │
    │ e.g., 'tutorial_flow'        │
    └──────────┬────────────────────┘
               │
               ├─ Check cache (fast path)
               │  └─ If cached: return variant
               │
               ├─ Not cached: Hash player_id
               │  MD5(player_id + flag) % 100
               │  = consistent variant per player
               │
               ├─ Assign variant
               │  0-49: Control
               │  50-99: Treatment
               │
               ▼
    ┌──────────────────────────────┐
    │ Feature-specific behavior    │
    ├──────────────────────────────┤
    │ if variant == 'treatment':   │
    │    show_new_tutorial()       │
    │ else:                        │
    │    show_old_tutorial()       │
    │                              │
    │ if is_in_treatment(...):     │
    │    use_new_algorithm()       │
    └──────────┬───────────────────┘
               │
               ▼
    ┌──────────────────────────────┐
    │ Analytics Tracking           │
    │ - Variant assignment         │
    │ - Metrics per variant        │
    │ - Statistical comparison     │
    └──────────────────────────────┘
```

---

## Deployment Pipeline

```
Source Code → Tests → Docker Build → Registry → Kubernetes
    │            │          │           │           │
    ▼            ▼          ▼           ▼           ▼
  GitHub      pytest     Dockerfile   Docker      health_check
  commit      coverage    image        Hub         probes
    │                      └── Labels:  └── Health endpoints
    └─ Pre-commit            version        - /health
       hooks                 build_id   └── Monitoring
                             date        - Sentry
                                        - Performance metrics
                                        - Analytics dashboard

Production Checklist (200+ items):
├─ Security (15 items)
├─ Database (10 items)
├─ Performance (11 items)
├─ Monitoring (10 items)
├─ Testing (10 items)
├─ Code Quality (10 items)
├─ Configuration (10 items)
├─ Legal (11 items)
├─ DevOps (12 items)
├─ UX (9 items)
├─ Business (10 items)
└─ Communication (7 items)
```

