# MbetterClient Game Flow Documentation

## Overview

This document provides a detailed visual representation of the MbetterClient game flow, including state transitions, component interactions, and timing sequences. The diagrams show how matches progress from initial loading to completion, including betting phases and result extraction.

## Table of Contents

1. [Match Lifecycle Flow](#match-lifecycle-flow)
2. [Component Interaction Diagram](#component-interaction-diagram)
3. [Betting System Flow](#betting-system-flow)
4. [Timer and Automation Flow](#timer-and-automation-flow)
5. [Extraction Process Flow](#extraction-process-flow)
6. [Error Handling and Recovery](#error-handling-and-recovery)

---

## Match Lifecycle Flow

### Complete Match State Machine

```
┌─────────────────┐
│   SCHEDULED     │ ◄─────────────────┐
│                 │                   │
│ • Match loaded  │                   │
│ • Not available │                   │
│   for betting   │                   │
└─────────┬───────┘                   │
          │                           │
          ▼                           │
┌─────────────────┐                   │
│      BET        │ ◄─────────────────┘
│                 │ ◄─────────────────┐
│ • Active betting│                   │
│ • Customer bets │                   │
│   accepted      │                   │
└─────────┬───────┘                   │
          │                           │
          ▼                           │
┌─────────────────┐                   │
│    INGAME       │ ◄─────────────────┘
│                 │ ◄─────────────────┐
│ • Match in      │                   │
│   progress      │                   │
│ • Betting locked│                   │
└─────────┬───────┘                   │
          │                           │
          ▼                           │
┌─────────────────┐                   │
│   COMPLETED     │ ◄─────────────────┘
│                 │ ◄─────────────────┐
│ • Match finished│                   │
│ • Results       │                   │
│   extracted     │                   │
└─────────┬───────┘                   │
          │                           │
          ▼                           │
┌─────────────────┐                   │
│   CANCELLED     │ ◄─────────────────┘
│                 │ ◄─────────────────┐
│ • Match aborted │                   │
│ • No results    │                   │
│ • Bets refunded│                   │
└─────────────────┘                   │
                                      │
                                      │
                 ┌────────────────────┘
                 │ Emergency cancellation
                 ▼
```

### State Transition Triggers

```
SCHEDULED → BET:
├── START_GAME message (manual/auto)
├── Global betting mode = "all_bets_on_start"
└── Match time reached

BET → INGAME:
├── MATCH_START message
├── Timer expiration
└── Manual progression

INGAME → COMPLETED:
├── Match completion detection
├── Result extraction successful
└── Outcome values available

Any State → CANCELLED:
├── Emergency stop
├── Match abandonment
└── System error
```

---

## Component Interaction Diagram

### System Architecture Overview

```
┌─────────────────────────────────────────────────────────────────┐
│                    MBETTERCLIENT SYSTEM                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐         │
│  │  Web        │    │  API        │    │  Database   │         │
│  │  Dashboard  │◄──►│  Client     │◄──►│  Manager    │         │
│  │             │    │             │    │             │         │
│  └──────┬──────┘    └──────┬──────┘    └──────┬──────┘         │
│         │                  │                  │                │
│         ▼                  ▼                  ▼                │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐         │
│  │ Message Bus │◄──►│ Games Thread│◄──►│ Match Timer │         │
│  │             │    │             │    │             │         │
│  └──────┬──────┘    └──────┬──────┘    └──────┬──────┘         │
│         │                  │                  │                │
│         ▼                  ▼                  ▼                │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐         │
│  │   Qt Player │    │Screen Cast  │    │ Extraction  │         │
│  │             │    │             │    │   Engine    │         │
│  └─────────────┘    └─────────────┘    └─────────────┘         │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

### Message Flow Between Components

```
Web Dashboard → Message Bus → Games Thread → Match Timer
      ↓              ↓              ↓            ↓
   API Calls    Message Routing  State Changes  Timer Events
      ↓              ↓              ↓            ↓
Database ←─── API Client ←─── External Server ←─── Results
   ↑              ↑              ↑            ↑
Bet Creation  Fixture Sync   Match Updates  Timer Sync
```

---

## Betting System Flow

### Customer Bet Creation Process

```
┌─────────────┐
│   Customer  │
│  Requests   │
│    Bet      │
└──────┬──────┘
       │
       ▼
┌─────────────┐     ┌─────────────────┐
│   Cashier   │────►│  Validate Match │
│ Interface   │     │   Status = BET  │
└──────┬──────┘     └─────────┬───────┘
       │                      │
       ▼                      │
┌─────────────┐               │
│ Select Match│◄──────────────┘
│ & Outcomes  │
└──────┬──────┘
       │
       ▼
┌─────────────┐     ┌─────────────────┐
│ Enter Bet   │────►│  Validate       │
│ Amounts     │     │  Amounts > 0    │
└──────┬──────┘     └─────────┬───────┘
       │                      │
       ▼                      │
┌─────────────┐               │
│ Confirm Bet │◄──────────────┘
│ Details     │
└──────┬──────┘
       │
       ▼
┌─────────────┐     ┌─────────────────┐
│ Generate    │────►│  Create UUID    │
│ Bet ID      │     │  for Tracking   │
└──────┬──────┘     └─────────┬───────┘
       │                      │
       ▼                      │
┌─────────────┐               │
│ Save to     │◄──────────────┘
│ Database    │
└──────┬──────┘
       │
       ▼
┌─────────────┐
│ Print       │
│ Receipt     │
└──────┬──────┘
       │
       ▼
┌─────────────┐
│ Customer    │
│ Receives    │
│ Receipt     │
└─────────────┘
```

### Bet Resolution Flow

```
Match Completion → Extract Results → Map to Bet Outcomes → Calculate Winnings
       ↓               ↓               ↓               ↓
  INGAME → COMPLETED  Database Query  Association     Cap Check
  Status               match_outcomes  Rules           70% Limit
                       table          WIN1/X/WIN2     Redistribution
```

---

## Timer and Automation Flow

### Match Timer Sequence

```
┌─────────────────┐
│   Timer Start   │
│                 │
│ • Command line  │
│ • Manual trigger│
│ • Auto-start    │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│  Find Next      │
│    Match        │
│                 │
│ Priority Order: │
│ 1. BET status   │
│ 2. SCHEDULED    │
│ 3. PENDING      │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│   Countdown     │
│   Timer         │
│                 │
│ • 20 min default│
│ • Visual display│
│ • Color coding  │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐     ┌─────────────────┐
│ Timer Expires   │────►│ Send MATCH_START│
│                 │     │ Message         │
└─────────┬───────┘     └─────────┬───────┘
          │                       │
          ▼                       ▼
┌─────────────────┐     ┌─────────────────┐
│   Reset Timer   │     │   Match Status  │
│   for Next      │     │   → INGAME      │
│   Match         │     └─────────┬───────┘
└─────────────────┘               │
                                  ▼
                    ┌─────────────────┐
                    │   Betting       │
                    │   Locked        │
                    └─────────────────┘
```

### Global Betting Mode Comparison

#### Mode 1: All Bets on Start
```
START_GAME Trigger
        │
        ▼
┌─────────────────┐
│ All Matches in  │
│ Fixture Become  │
│   BET Status    │
│                 │
│ Match 1: BET    │
│ Match 2: BET    │
│ Match 3: BET    │
│ Match 4: BET    │
└───────┬─────────┘
        │
        ▼
Timer → Match 1 → INGAME
        │
        ▼
Timer → Match 2 → INGAME
        │
        ▼
Timer → Match 3 → INGAME
```

#### Mode 2: One Bet at a Time
```
START_GAME Trigger
        │
        ▼
┌─────────────────┐
│ Only First      │
│ Match Becomes   │
│   BET Status    │
│                 │
│ Match 1: BET    │
│ Match 2: SCHED. │
│ Match 3: SCHED. │
│ Match 4: SCHED. │
└───────┬─────────┘
        │
        ▼
Timer → Match 1 → INGAME → COMPLETED
        │
        ▼
┌─────────────────┐
│ Match 2 Auto-   │
│ becomes BET     │
│ Status          │
└───────┬─────────┘
        │
        ▼
Timer → Match 2 → INGAME
```

---

## Extraction Process Flow

### Result Extraction Algorithm

```
┌─────────────────┐
│ Match Completed │
│   Detection     │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│ Query Database │
│                 │
│ SELECT * FROM   │
│ match_outcomes  │
│ WHERE match_id  │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│ Load Extraction│
│ Associations   │
│                 │
│ WIN1: WIN1,KO1 │
│ X: DRAW,12     │
│ WIN2: WIN2,KO2 │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│ Map Outcomes to │
│ Bet Results     │
│                 │
│ KO_ROUND_1 → WIN1│
│ DRAW → X        │
│ PTS_WIN → WIN2  │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│ Calculate       │
│ Redistribution  │
│                 │
│ Check 70% Cap   │
│ Scale if needed │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│ Update Bet      │
│ Results         │
│                 │
│ WON/LOST/CANCEL │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│ Record          │
│ Statistics      │
│                 │
│ Profit/Loss     │
│ Cap Applied     │
└─────────────────┘
```

### Redistribution Cap Logic

```
Total Collected: $1000
Winning Bets: 8 bets × $50 = $400 requested

Cap Check: 70% of $1000 = $700 maximum
         │
         ▼
$400 < $700 ✓ No cap applied
         │
         ▼
Pay full $400 to winners
House profit: $600
```

```
Total Collected: $1000
Winning Bets: 20 bets × $50 = $1000 requested

Cap Check: 70% of $1000 = $700 maximum
         │
         ▼
$1000 > $700 ✗ Cap applied
         │
         ▼
Scale factor: $700/$1000 = 0.7
         │
         ▼
Pay $35 per winning bet ($700 total)
House profit: $300
```

---

## Error Handling and Recovery

### System Failure Recovery

```
System Error Detected
        │
        ▼
┌─────────────────┐
│   Error Type    │
│   Analysis      │
│                 │
│ • Database      │
│ • Network       │
│ • Component     │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│   Recovery      │
│   Strategy      │
│                 │
│ • Retry         │
│ • Fallback      │
│ • Manual        │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│   State         │
│   Restoration   │
│                 │
│ • Match status  │
│ • Timer sync    │
│ • Bet integrity│
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│   System        │
│   Resume        │
│                 │
│ • Normal ops    │
│ • Data integrity│
│ • User notified │
└─────────────────┘
```

### Match Interruption Scenarios

#### Scenario 1: Network Failure During Match
```
Match INGAME → Network Lost → System Detects Failure
      │                    │               │
      ▼                    ▼               ▼
Timer Paused        Auto-retry        Status: ERROR
Connection          Connection        Recovery Mode
      │                    │               │
      ▼                    ▼               ▼
Connection OK →    Success →         Resume Match
Timer Resumes      Continue           Normal Flow
                    Match
```

#### Scenario 2: Database Connection Lost
```
Bet Creation → Database Error → Transaction Rollback
      │               │               │
      ▼               ▼               ▼
Error Logged      User Notified     Retry Option
to System         "Try Again"       Available
      │               │               │
      ▼               ▼               ▼
Admin Alert →    Connection OK →   Bet Succeeds
Manual Check     Auto-retry        UUID Generated
Database         Success
```

### Component Failure Recovery

```
Component Failure Detected
        │
        ▼
┌─────────────────┐
│   Identify      │
│   Failed        │
│   Component     │
│                 │
│ • API Client    │
│ • Video Player  │
│ • Database      │
│ • Message Bus   │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│   Graceful      │
│   Degradation   │
│                 │
│ • Fallback mode │
│ • Reduced func  │
│ • User notified │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│   Auto-restart  │
│   Attempt       │
│                 │
│ • Component     │
│ • Dependencies  │
│ • Health check  │
└─────────┬───────┘
          │
          ▼
┌─────────────────┐
│   Recovery      │
│   Success?      │
└──────┬──┬──────┘
       │  │
       ▼  ▼
┌─────────────┐  ┌─────────────┐
│   Success   │  │   Failure   │
│             │  │             │
│ • Resume     │  │ • Admin     │
│   normal     │  │   alert     │
│   ops        │  │ • Manual    │
│ • Log event  │  │   recovery  │
└─────────────┘  └─────────────┘
```

---

## Timing and Synchronization

### Match Timer Synchronization

```
Server Time: 14:30:00
Match Interval: 20 minutes
Next Match Start: 14:50:00

Timer Display: 00:19:45 ⬅ 19m 45s remaining
Color: Green (normal)

Timer Display: 00:05:00 ⬅ 5 minutes remaining
Color: Yellow (warning)

Timer Display: 00:01:00 ⬅ 1 minute remaining
Color: Red + Pulse (danger)

Timer Display: 00:00:00 ⬅ Timer expired
Action: Send MATCH_START message
```

### Multi-Match Coordination

```
Fixture: 4 matches, 20-minute intervals

Time: 14:30:00
Match 1: INGAME (started manually)
Match 2: BET (active betting)
Match 3: SCHEDULED (waiting)
Match 4: SCHEDULED (waiting)

Time: 14:50:00 (20 min later)
Match 1: COMPLETED (finished)
Match 2: INGAME (timer triggered)
Match 3: BET (auto-promoted)
Match 4: SCHEDULED (still waiting)

Time: 15:10:00 (20 min later)
Match 1: COMPLETED
Match 2: COMPLETED
Match 3: INGAME
Match 4: BET
```

---

## Performance and Scalability

### System Load Distribution

```
Peak Load Scenario (Multiple Concurrent Matches)

┌─────────────────────────────────────────────────────────────┐
│                    SYSTEM LOAD BALANCE                      │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │
│  │ Web Server  │  │ Database    │  │ API Client  │         │
│  │             │  │             │  │             │         │
│  │ CPU: 15%    │  │ CPU: 25%    │  │ CPU: 10%    │         │
│  │ RAM: 150MB  │  │ RAM: 200MB  │  │ RAM: 80MB   │         │
│  │ Requests:   │  │ Queries:    │  │ Calls:      │         │
│  │ 50/sec      │  │ 100/sec     │  │ 5/sec       │         │
│  └─────────────┘  └─────────────┘  └─────────────┘         │
│                                                             │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │
│  │ Video Player│  │ Screen Cast │  │ Match Timer │         │
│  │             │  │             │  │             │         │
│  │ CPU: 30%    │  │ CPU: 20%    │  │ CPU: 5%     │         │
│  │ RAM: 300MB  │  │ RAM: 150MB  │  │ RAM: 50MB   │         │
│  │ Streams: 1  │  │ Streams: 1  │  │ Timers: 4   │         │
│  └─────────────┘  └─────────────┘  └─────────────┘         │
│                                                             │
│  Total System Load: CPU 45%, RAM 930MB                     │
│  Concurrent Users: 50, Active Matches: 4                   │
└─────────────────────────────────────────────────────────────┘
```

### Bottleneck Analysis

```
Performance Bottlenecks (Most to Least Critical)

1. Database Queries (Highest Impact)
   ├── Bet creation during peak betting
   ├── Match outcome retrieval
   └── Statistics calculation

2. Network Latency (Medium Impact)
   ├── API synchronization delays
   ├── Screen casting bandwidth
   └── Real-time status updates

3. Memory Usage (Low Impact)
   ├── Video player memory
   ├── Large fixture data
   └── Template caching

4. CPU Usage (Lowest Impact)
   ├── Video encoding/decoding
   ├── Timer calculations
   └── Background processing
```

This comprehensive game flow documentation provides visual representations of all major processes within the MbetterClient system, from individual match progression to system-wide component interactions. The diagrams help illustrate complex workflows and state transitions that are essential for understanding the betting system's operation.