# MbetterClient - Complete Documentation

## Table of Contents

1. [Installation & Setup](#installation--setup)
2. [Configuration](#configuration)
3. [Usage Guide](#usage-guide)
4. [API Reference](#api-reference)
5. [Development Guide](#development-guide)
6. [Troubleshooting](#troubleshooting)
7. [Advanced Topics](#advanced-topics)

## Installation & Setup

### System Requirements

- **Operating System**: Windows 10+, macOS 10.14+, or Linux (Ubuntu 18.04+)
- **Python**: 3.8 or higher
- **Memory**: 512 MB RAM minimum, 1 GB recommended
- **Storage**: 100 MB free space
- **Network**: Optional (for REST API features)

### Detailed Installation

1. **Install Python Dependencies**
   ```bash
   # Ensure you have the latest pip
   python -m pip install --upgrade pip
   
   # Install all dependencies
   pip install -r requirements.txt
   
   # For development
   pip install pytest pytest-qt black pylint
   ```

2. **Verify Installation**
   ```bash
   python main.py --help
   ```

3. **First Run Setup**
   - Application creates configuration directory automatically
   - Default admin user is created (username: admin, password: admin)
   - SQLite database is initialized with schema
   - Web server starts on http://localhost:5000

### Directory Structure After Installation

#### Persistent User Directories (PyInstaller Compatible)

The application automatically creates platform-appropriate persistent directories:

**Linux**:
```
~/.local/share/MbetterClient/     # Data directory
├── mbetterclient.db              # SQLite database with matches & outcomes
├── logs/
│   ├── mbetterclient.log        # Application logs
│   └── error.log                # Error logs
├── data/                        # Application data
└── uploads/                     # File uploads

~/.config/MbetterClient/         # Config directory
└── templates/                   # User uploaded overlay templates
```

**Windows**:
```
%APPDATA%\MbetterClient\         # Unified location
├── mbetterclient.db             # SQLite database
├── logs/                        # Log files
├── data/                        # Application data
├── uploads/                     # File uploads
└── templates/                   # User templates
```

**macOS**:
```
~/Library/Application Support/MbetterClient/  # Unified location
├── mbetterclient.db             # SQLite database
├── logs/                        # Log files
├── data/                        # Application data
├── uploads/                     # File uploads
└── templates/                   # User templates
```

## Configuration

### Application Settings

Edit configuration through the web dashboard or modify JSON files directly:

#### app.json
```json
{
  "web": {
    "host": "localhost",
    "port": 5000,
    "secret_key": "your-secret-key",
    "jwt_secret_key": "jwt-secret-key",
    "jwt_expiration_hours": 24,
    "session_timeout_hours": 8
  },
  "qt": {
    "fullscreen": true,
    "default_template": "news_template",
    "video_directory": "/path/to/videos",
    "supported_formats": ["mp4", "avi", "mov", "mkv"]
  },
  "api": {
    "max_retries": 3,
    "retry_backoff": 2,
    "default_timeout": 30,
    "max_consecutive_failures": 5,
    "user_agent": "MbetterClient/1.0.0"
  },
  "logging": {
    "level": "INFO",
    "max_file_size": "10MB",
    "backup_count": 5
  }
}
```

#### api_endpoints.json
```json
{
  "news_api": {
    "url": "https://newsapi.org/v2/top-headlines",
    "method": "GET",
    "headers": {
      "X-API-Key": "your-api-key"
    },
    "params": {
      "country": "us",
      "pageSize": 5
    },
    "interval": 300,
    "enabled": true,
    "timeout": 30,
    "retry_attempts": 3,
    "response_handler": "news"
  },
  "weather_api": {
    "url": "https://api.openweathermap.org/data/2.5/weather",
    "method": "GET",
    "params": {
      "q": "New York",
      "appid": "your-api-key",
      "units": "metric"
    },
    "interval": 1800,
    "enabled": false,
    "timeout": 15,
    "response_handler": "default"
  }
}
```

### Environment Variables

Create a `.env` file in the project root:

```bash
# Web Dashboard Configuration
WEB_HOST=0.0.0.0
WEB_PORT=5000
SECRET_KEY=your-very-secret-key-here
JWT_SECRET_KEY=your-jwt-secret-key-here

# Database
DATABASE_PATH=./data/mbetterclient.db

# Application Settings
LOG_LEVEL=INFO
DEBUG=False
FULLSCREEN=True

# API Client
API_CLIENT_TIMEOUT=30
API_CLIENT_RETRIES=3

# Development
FLASK_ENV=production
FLASK_DEBUG=False
```

## Usage Guide

### Command Line Usage

```bash
# Basic usage
python main.py

# Available options
python main.py [OPTIONS]

Options:
  --web-host TEXT          Web interface host [default: localhost]
  --web-port INTEGER       Web interface port [default: 5000]
  --fullscreen            Start video player in fullscreen mode
  --no-fullscreen         Start video player in windowed mode
  --overlay-type TEXT     Overlay rendering system: webengine or native [default: webengine]
  --no-qt                 Disable PyQt video player
  --no-web                Disable web dashboard
  --no-api                Disable API client
  --database-path TEXT    Custom database path
  --log-level TEXT        Logging level [default: INFO]
  --config-dir TEXT       Custom configuration directory
  --help                  Show this message and exit
```

### Web Dashboard Usage

#### Login and Authentication

1. Navigate to `http://localhost:5000`
2. Login with default credentials:
   - Username: `admin`
   - Password: `admin`
3. **Important**: Change default password immediately

#### Dashboard Overview

- **System Status**: Real-time component health monitoring
- **Video Control**: Play, pause, stop video with template selection
- **Quick Actions**: Common operations like starting playback or updating overlays

#### Video Control Panel

- **File Selection**: Choose video files from local filesystem
- **Template Selection**: Choose from news, sports, or simple templates
- **Overlay Data**: Configure dynamic text and data for overlays
- **Playback Controls**: Standard video controls with fullscreen support

#### API Token Management

1. Navigate to "API Tokens" section
2. Click "Create New Token"
3. Provide descriptive name and expiration time
4. Copy generated token (shown only once)
5. Use token for API authentication

#### User Management (Admin Only)

- **Add Users**: Create new user accounts with role assignment
- **Manage Permissions**: Set admin or regular user privileges
- **Password Reset**: Reset user passwords
- **User Activity**: View login history and token usage

#### System Administration (Admin Only)

- **Application Shutdown**: Remote shutdown button in Administrator Actions section
- **Force Termination**: Guaranteed shutdown mechanism that bypasses any deadlocks
- **System Control**: Complete system management from web interface

### Overlay System

The application features a dual overlay rendering system with command-line selection:

#### WebEngine Overlays (Default)

```bash
python main.py --overlay-type webengine
```

**Features:**
- Rich JavaScript and HTML/CSS support
- Complex animations and web-based content
- Dynamic template rendering with web technologies
- Full DOM manipulation capabilities

**Best For:**
- Complex overlays with animations
- Web content integration
- Advanced JavaScript functionality

**Considerations:**
- Higher resource usage
- Potential timing issues with DOM loading
- JavaScript errors can affect overlay stability

#### Native Qt Overlays

```bash
python main.py --overlay-type native
```

**Features:**
- High performance Qt widget rendering
- Rock-solid stability with no JavaScript dependencies
- Lower resource consumption
- Immediate rendering without DOM loading delays

**Best For:**
- Simple text overlays
- Production environments requiring maximum stability
- Systems with limited resources
- Clean, consistent text rendering

**Considerations:**
- Limited to Qt widget rendering capabilities
- No web-based animations or complex layouts

### Video Player Usage

#### Keyboard Shortcuts

- `Space`: Play/Pause toggle
- `F11`: Toggle fullscreen mode
- `Esc`: Exit fullscreen mode
- `←` / `→`: Seek backward/forward (10 seconds)
- `↑` / `↓`: Volume up/down
- `M`: Mute/unmute
- `R`: Reset video position
- `Q`: Quit application

#### Overlay Templates

**News Template**:
- Scrolling ticker text at bottom
- Breaking news headline
- Logo display
- Timestamp

**Sports Template**:
- Team names and scores
- Game status and time
- League/tournament information
- Statistics display

**Simple Template**:
- Title and subtitle text
- Basic text overlay
- Customizable positioning

### API Client Configuration

#### Adding New Endpoints

1. Access "Configuration" → "API Endpoints" (Admin only)
2. Click "Add Endpoint"
3. Configure:
   - **Name**: Unique identifier
   - **URL**: Full API endpoint URL
   - **Method**: HTTP method (GET, POST, etc.)
   - **Headers**: Authentication and custom headers
   - **Parameters**: Query parameters or request body
   - **Interval**: Request frequency in seconds
   - **Response Handler**: Data processing method

#### Response Handlers

- **default**: Basic JSON response processing
- **news**: Extracts headlines and ticker text for news overlays
- **sports**: Processes game scores and team information
- **custom**: User-defined processing logic

### Fixtures Management System

The application includes a comprehensive fixtures management system with real-time API synchronization and web dashboard integration:

#### Fixtures Dashboard

Access the fixtures management interface through the web dashboard:

- **Fixtures List**: View all synchronized fixtures with match counts and status
- **Fixture Details**: Detailed view of individual fixtures with all matches and outcomes
- **Admin Controls**: Reset functionality to clear all fixture data and ZIP files
- **Real-time Updates**: Live synchronization with server using proper timestamp handling

#### API Synchronization

The fixtures system synchronizes with the server API using Unix timestamp format:

```http
POST /api/updates
Authorization: Bearer <token>
Content-Type: application/json

{
  "from": "1755773200"
}
```

**Response Format:**
```json
{
  "fixtures": [
    {
      "fixture_id": "fixture_123",
      "fixture_active_time": 1755773200,
      "matches": [
        {
          "match_number": 101,
          "fighter1_township": "Kampala Central",
          "fighter2_township": "Nakawa",
          "fixture_id": "fixture_123",
          "fixture_active_time": 1755773200,
          "outcomes": {
            "round_1_score": 10.5,
            "round_2_score": 9.8
          }
        }
      ]
    }
  ]
}
```

### Match Data Management

The application includes comprehensive boxing match data management with database tables adapted from the mbetterd system:

#### Match Database Structure

**matches table**: Core match information
- Match numbers, fighter townships, venues
- Start/end times and results
- File metadata and SHA1 checksums
- ZIP upload tracking with progress
- User association and timestamps
- `fixture_active_time` field for server synchronization (Unix timestamp)

**match_outcomes table**: Detailed match results
- Foreign key relationships to matches
- Column-based outcome storage with float values
- Unique constraints preventing duplicate outcomes

#### Match Data API

Access match data through the web dashboard or API:

```http
GET /api/matches
Authorization: Bearer <token>
```

**Response:**
```json
{
  "matches": [
    {
      "id": 1,
      "match_number": 101,
      "fighter1_township": "Kampala Central",
      "fighter2_township": "Nakawa",
      "venue_kampala_township": "Kololo",
      "start_time": "2025-08-21T14:00:00Z",
      "end_time": "2025-08-21T14:45:00Z",
      "result": "Winner: Fighter 1",
      "active_status": true,
      "outcomes": {
        "round_1_score": 10.5,
        "round_2_score": 9.8,
        "total_score": 20.3
      }
    }
  ]
}
```

#### Creating Match Records

```http
POST /api/matches
Authorization: Bearer <token>
Content-Type: application/json

{
  "match_number": 102,
  "fighter1_township": "Rubaga",
  "fighter2_township": "Makindye",
  "venue_kampala_township": "Lugogo",
  "outcomes": [
    {
      "column_name": "round_1_score",
      "float_value": 9.5
    },
    {
      "column_name": "round_2_score",
      "float_value": 8.7
    }
  ]
}
```

## API Reference

### Authentication

All API endpoints require authentication via Bearer token.

#### Get Access Token

```http
POST /auth/token
Content-Type: application/json

{
  "username": "admin",
  "password": "admin"
}
```

**Response:**
```json
{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
  "token_type": "bearer",
  "user": {
    "id": 1,
    "username": "admin",
    "is_admin": true
  }
}
```

### System Status

#### Get System Status

```http
GET /api/status
Authorization: Bearer <token>
```

**Response:**
```json
{
  "status": "online",
  "timestamp": "2025-01-19T10:00:00.000Z",
  "uptime": 3600,
  "components": {
    "qt_player": "running",
    "web_dashboard": "running",
    "api_client": "running"
  },
  "config": {
    "valid": true
  },
  "database": {
    "connected": true
  }
}
```

### Video Control

#### Play Video

```http
POST /api/video/control
Authorization: Bearer <token>
Content-Type: application/json

{
  "action": "play",
  "file_path": "/path/to/video.mp4",
  "template": "news_template",
  "overlay_data": {
    "headline": "Breaking News",
    "ticker_text": "This is a breaking news update"
  }
}
```

#### Pause Video

```http
POST /api/video/control
Authorization: Bearer <token>
Content-Type: application/json

{
  "action": "pause"
}
```

#### Get Video Status

```http
GET /api/video/status
Authorization: Bearer <token>
```

**Response:**
```json
{
  "player_status": "playing",
  "current_file": "/path/to/video.mp4",
  "current_template": "news_template",
  "position": 45.2,
  "duration": 120.0,
  "volume": 80,
  "fullscreen": true
}
```

### Overlay Management

#### Update Overlay

```http
POST /api/overlay
Authorization: Bearer <token>
Content-Type: application/json

{
  "template": "news_template",
  "data": {
    "headline": "Updated Headline",
    "ticker_text": "New ticker information",
    "logo_url": "https://example.com/logo.png"
  }
}
```

#### Get Available Templates

```http
GET /api/templates
Authorization: Bearer <token>
```

**Response:**
```json
{
  "templates": {
    "news_template": {
      "name": "News Template",
      "description": "Breaking news with scrolling text",
      "fields": ["headline", "ticker_text", "logo_url"]
    },
    "sports_template": {
      "name": "Sports Template",
      "description": "Sports scores and updates",
      "fields": ["team1", "team2", "score1", "score2", "event"]
    }
  }
}
```

### Configuration Management

#### Get Configuration

```http
GET /api/config?section=web
Authorization: Bearer <token>
```

#### Update Configuration

```http
POST /api/config
Authorization: Bearer <token>
Content-Type: application/json

{
  "section": "api_endpoints",
  "config": {
    "news_api": {
      "enabled": true,
      "interval": 600
    }
  }
}
```

### User Management

#### List Users (Admin Only)

```http
GET /api/users
Authorization: Bearer <token>
```

#### Create User (Admin Only)

```http
POST /api/users
Authorization: Bearer <token>
Content-Type: application/json

{
  "username": "newuser",
  "email": "user@example.com",
  "password": "securepassword",
  "is_admin": false
}
```

### Token Management

#### List API Tokens

```http
GET /api/tokens
Authorization: Bearer <token>
```

#### Create API Token

```http
POST /api/tokens
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "My API Token",
  "expires_hours": 8760
}
```

#### Revoke API Token

```http
DELETE /api/tokens/{token_id}
Authorization: Bearer <token>
```

### System Control (Admin Only)

#### Shutdown Application

```http
POST /api/system/shutdown
Authorization: Bearer <token>
Content-Type: application/json

{
  "force": true
}
```

**Response:**
```json
{
  "status": "success",
  "message": "Application shutdown initiated"
}
```

**Note**: This endpoint provides immediate HTTP response before initiating shutdown. The application will terminate completely within 1 second using force-exit mechanism to bypass any potential deadlocks.

## Development Guide

### Setting Up Development Environment

1. **Clone Repository**
   ```bash
   git clone https://git.nexlab.net/mbetter/mbetterc.git
   cd mbetterc
   ```

2. **Create Virtual Environment**
   ```bash
   python -m venv venv
   source venv/bin/activate  # Linux/macOS
   # or
   venv\Scripts\activate     # Windows
   ```

3. **Install Development Dependencies**
   ```bash
   pip install -r requirements.txt
   pip install pytest pytest-qt black pylint mypy
   ```

4. **Run Tests**
   ```bash
   pytest tests/
   ```

### Code Style and Quality

#### Formatting with Black

```bash
# Format all code
black mbetterclient/

# Check formatting
black --check mbetterclient/
```

#### Linting with Pylint

```bash
# Lint all modules
pylint mbetterclient/

# Lint specific module
pylint mbetterclient/qt_player/
```

#### Type Checking with MyPy

```bash
# Type check
mypy mbetterclient/
```

### Testing

#### Running Tests

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=mbetterclient

# Run specific test file
pytest tests/test_message_bus.py

# Run PyQt tests (requires X server or Xvfb on Linux)
pytest tests/test_qt_player.py
```

#### Writing Tests

Example test structure:

```python
import pytest
from mbetterclient.core.message_bus import MessageBus, MessageType

class TestMessageBus:
    def setup_method(self):
        self.message_bus = MessageBus()
    
    def test_component_registration(self):
        queue = self.message_bus.register_component("test_component")
        assert queue is not None
        assert "test_component" in self.message_bus._queues
    
    def test_message_publishing(self):
        self.message_bus.register_component("sender")
        self.message_bus.register_component("receiver")
        
        message = Message(
            type=MessageType.VIDEO_PLAY,
            sender="sender",
            recipient="receiver",
            data={"file_path": "test.mp4"}
        )
        
        result = self.message_bus.publish(message)
        assert result is True
```

### Adding New Features

#### Creating Custom Templates

1. **Define Template Class**
   ```python
   # mbetterclient/qt_player/templates.py
   
   class CustomTemplate(OverlayTemplate):
       def __init__(self):
           super().__init__("custom_template", "Custom Template")
           self.fields = ["title", "content", "color"]
       
       def render(self, painter, size, data):
           # Custom rendering logic
           painter.setPen(QColor(data.get("color", "#FFFFFF")))
           painter.drawText(10, 30, data.get("title", ""))
           painter.drawText(10, 60, data.get("content", ""))
   ```

2. **Register Template**
   ```python
   # In template manager initialization
   template_manager.register_template(CustomTemplate())
   ```

#### Adding API Response Handlers

```python
# mbetterclient/api_client/client.py

class CustomResponseHandler(ResponseHandler):
    def handle_response(self, endpoint: APIEndpoint, response: requests.Response):
        try:
            data = response.json()
            processed_data = {
                'source': endpoint.name,
                'timestamp': datetime.utcnow().isoformat(),
                'custom_field': data.get('important_data')
            }
            return processed_data
        except Exception as e:
            return self.handle_error(endpoint, e)
```

#### Extending Web Dashboard

1. **Add New Route**
   ```python
   # mbetterclient/web_dashboard/routes.py
   
   @main_bp.route('/custom')
   @login_required
   def custom_page():
       return render_template('custom.html')
   ```

2. **Create Template**
   ```html
   <!-- mbetterclient/web_dashboard/templates/custom.html -->
   {% extends "base.html" %}
   
   {% block content %}
   <h1>Custom Page</h1>
   <p>Custom functionality here</p>
   {% endblock %}
   ```

### Message Bus System

#### Message Types

Define new message types in `core/message_bus.py`:

```python
class MessageType(Enum):
    # Add new message type
    CUSTOM_ACTION = "CUSTOM_ACTION"
```

#### Message Builders

Add helper methods for creating messages:

```python
@staticmethod
def custom_action(sender: str, action_data: Dict[str, Any]) -> Message:
    return Message(
        type=MessageType.CUSTOM_ACTION,
        sender=sender,
        data=action_data
    )
```

#### Message Handlers

Subscribe to messages in component initialization:

```python
def initialize(self) -> bool:
    self.message_bus.subscribe(
        self.name, 
        MessageType.CUSTOM_ACTION, 
        self._handle_custom_action
    )
    return True

def _handle_custom_action(self, message: Message):
    action_data = message.data
    # Process custom action
```

## Troubleshooting

### Common Issues

#### Application Won't Start

**Symptoms**: Python errors on startup, missing dependencies
**Solutions**:
1. Verify Python version: `python --version` (must be 3.8+)
2. Check virtual environment activation
3. Reinstall dependencies: `pip install -r requirements.txt --force-reinstall`
4. Check file permissions on configuration directory

#### Video Player Issues

**Symptoms**: Black screen, video won't play, no audio
**Solutions**:
1. Verify video file path and format
2. Check PyQt5 multimedia installation:
   ```bash
   python -c "from PyQt5.QtMultimedia import QMediaPlayer; print('OK')"
   ```
3. Install system multimedia codecs
4. Try different video format (MP4 recommended)
5. Check file permissions and disk space

#### Web Dashboard Inaccessible

**Symptoms**: Connection refused, page won't load
**Solutions**:
1. Check if port 5000 is already in use:
   ```bash
   # Linux/macOS
   lsof -i :5000
   # Windows
   netstat -an | findstr :5000
   ```
2. Try different port: `python main.py --web-port 8080`
3. Check firewall settings
4. Verify Flask installation: `pip show Flask`

#### Database Errors

**Symptoms**: SQLite errors, configuration not saving
**Solutions**:
1. Check database file permissions
2. Verify disk space availability
3. Delete corrupted database (will recreate):
   ```bash
   rm ~/.config/MbetterClient/mbetterclient.db
   ```
4. Check SQLite installation: `python -c "import sqlite3; print(sqlite3.sqlite_version)"`

#### API Client Not Working

**Symptoms**: External API requests failing, no data updates
**Solutions**:
1. Check internet connectivity
2. Verify API key and endpoint URL
3. Check API rate limits and quotas
4. Review application logs for specific errors
5. Test endpoint manually with curl:
   ```bash
   curl -H "Authorization: Bearer your-token" https://api.example.com/endpoint
   ```

### Logging and Debugging

#### Enable Debug Logging

```bash
# Run with debug logging
python main.py --log-level DEBUG

# Or set environment variable
export LOG_LEVEL=DEBUG
python main.py
```

#### Log File Locations

- **Linux**: `~/.config/MbetterClient/logs/`
- **macOS**: `~/Library/Application Support/MbetterClient/logs/`
- **Windows**: `%APPDATA%\MbetterClient\logs\`

#### Useful Log Commands

```bash
# View recent logs
tail -f ~/.config/MbetterClient/logs/app.log

# Search for errors
grep ERROR ~/.config/MbetterClient/logs/app.log

# Filter by component
grep "qt_player" ~/.config/MbetterClient/logs/app.log
```

### Performance Optimization

#### Video Performance

- Use hardware-accelerated video formats (H.264)
- Reduce video resolution for older hardware
- Close unused applications to free memory
- Use SSD storage for video files

#### Web Dashboard Performance

- Increase status update intervals for slower systems
- Disable real-time features if not needed
- Use browser developer tools to identify bottlenecks
- Consider using reverse proxy (nginx) for production

#### API Client Performance

- Adjust request intervals based on API limits
- Implement request caching for static data
- Use compression for large responses
- Monitor network usage and optimize accordingly

### Build Issues

#### PyInstaller Problems

**Symptoms**: Build fails, missing modules, large executable size
**Solutions**:
1. Update PyInstaller: `pip install --upgrade pyinstaller`
2. Clear PyInstaller cache: `pyi-makespec --clean main.py`
3. Add missing modules to hiddenimports in build.py
4. Use UPX compression (if available): Set `upx=True` in build config
5. Exclude unnecessary modules in build.py

#### Platform-Specific Issues

**Windows**:
- Install Visual C++ Redistributable
- Add Windows Defender exclusion for build directory
- Use Windows-compatible paths in configuration

**macOS**:
- Install Xcode command line tools: `xcode-select --install`
- Code signing may be required for distribution
- Use .icns icon format

**Linux**:
- Install required system libraries: `apt-get install python3-pyqt5.qtmultimedia`
- Ensure Qt libraries are available on target systems
- Use AppImage for better compatibility

## Advanced Topics

### Custom Response Handlers

Create specialized handlers for different API formats:

```python
class WeatherResponseHandler(ResponseHandler):
    def handle_response(self, endpoint: APIEndpoint, response: requests.Response):
        try:
            data = response.json()
            return {
                'source': 'weather',
                'temperature': data['main']['temp'],
                'condition': data['weather'][0]['description'],
                'location': data['name'],
                'overlay_text': f"{data['name']}: {data['main']['temp']}°C, {data['weather'][0]['description']}"
            }
        except Exception as e:
            logger.error(f"Weather processing error: {e}")
            return self.handle_error(endpoint, e)
```

### Database Schema Extensions

The application includes comprehensive match data models adapted from mbetterd:

#### Match Models

```python
# In database/models.py

class MatchModel(BaseModel):
    """Boxing matches from fixture files"""
    __tablename__ = 'matches'
    
    # Core match data
    match_number = Column(Integer, nullable=False, unique=True)
    fighter1_township = Column(String(255), nullable=False)
    fighter2_township = Column(String(255), nullable=False)
    venue_kampala_township = Column(String(255), nullable=False)
    
    # Match timing and results
    start_time = Column(DateTime)
    end_time = Column(DateTime)
    result = Column(String(255))
    
    # File metadata
    filename = Column(String(1024), nullable=False)
    file_sha1sum = Column(String(255), nullable=False)
    fixture_id = Column(String(255), nullable=False, unique=True)
    active_status = Column(Boolean, default=False)
    
    # ZIP upload tracking
    zip_filename = Column(String(1024))
    zip_sha1sum = Column(String(255))
    zip_upload_status = Column(String(20), default='pending')
    zip_upload_progress = Column(Float, default=0.0)
    
    # Relationships
    outcomes = relationship('MatchOutcomeModel', cascade='all, delete-orphan')

class MatchOutcomeModel(BaseModel):
    """Match outcome values from fixture files"""
    __tablename__ = 'match_outcomes'
    
    match_id = Column(Integer, ForeignKey('matches.id', ondelete='CASCADE'))
    column_name = Column(String(255), nullable=False)
    float_value = Column(Float, nullable=False)
    
    # Unique constraint on match_id + column_name
    __table_args__ = (
        UniqueConstraint('match_id', 'column_name'),
    )
```

#### Database Migration

```python
# Migration_008_AddMatchTables
class Migration_008_AddMatchTables(DatabaseMigration):
    def up(self, db_manager) -> bool:
        # Creates matches and match_outcomes tables with:
        # - Comprehensive indexing for performance
        # - Foreign key relationships with CASCADE DELETE
        # - Unique constraints for data integrity
        # - SQLite-compatible syntax
        pass
```

#### Custom Data Extensions

Add application-specific tables:

```python
class CustomData(Base):
    __tablename__ = 'custom_data'
    
    id = Column(Integer, primary_key=True)
    name = Column(String(100), nullable=False)
    value = Column(Text)
    created_at = Column(DateTime, default=datetime.utcnow)
    
    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'value': self.value,
            'created_at': self.created_at.isoformat()
        }
```

### Plugin System Architecture

While not fully implemented, the architecture supports plugin extensions:

```python
# Future plugin interface
class MbetterPlugin:
    def __init__(self, name: str):
        self.name = name
    
    def initialize(self, app_context):
        pass
    
    def get_routes(self):
        return []
    
    def get_message_handlers(self):
        return {}
    
    def shutdown(self):
        pass
```

### Security Considerations

#### Web Dashboard Security

- Change default passwords immediately
- Use HTTPS in production environments
- Implement rate limiting for API endpoints
- Regular token rotation
- Secure configuration file permissions

#### API Security

- Use strong JWT secrets
- Implement token expiration and refresh
- Validate all input data
- Log authentication attempts
- Monitor for unusual activity patterns

#### File System Security

- Restrict video file access paths
- Validate file types and sizes
- Use sandboxed directories with persistent user data locations
- Regular backup of configuration and database
- Cross-platform directory permission validation
- Secure PyInstaller executable data persistence

#### Cross-Platform Data Persistence

- **Windows**: All data stored in `%APPDATA%\MbetterClient\`
- **macOS**: Unified location at `~/Library/Application Support/MbetterClient/`
- **Linux**: Data in `~/.local/share/MbetterClient/`, config in `~/.config/MbetterClient/`
- **PyInstaller Detection**: Automatic runtime environment detection
- **Fallback Handling**: Graceful degradation to home directory if standard paths fail
- **Permission Testing**: Write verification before using directories

### Performance Monitoring

#### Built-in Metrics

Access metrics through the web dashboard or API:

```python
# Get system statistics
stats = {
    'memory_usage': psutil.Process().memory_info().rss / 1024 / 1024,  # MB
    'cpu_percent': psutil.Process().cpu_percent(),
    'thread_count': threading.active_count(),
    'uptime': time.time() - start_time
}
```

#### External Monitoring

Integrate with monitoring systems:

```python
# Example: Send metrics to external system
def send_metrics():
    metrics = get_system_metrics()
    requests.post('https://monitoring.example.com/metrics', json=metrics)
```

### Deployment Strategies

#### Production Deployment

1. **Use Process Manager**
   ```bash
   # With systemd
   sudo systemctl enable mbetterclient
   sudo systemctl start mbetterclient
   ```

2. **Reverse Proxy Setup**
   ```nginx
   server {
       listen 80;
       server_name mbetterclient.example.com;
       
       location / {
           proxy_pass http://127.0.0.1:5000;
           proxy_set_header Host $host;
           proxy_set_header X-Real-IP $remote_addr;
       }
   }
   ```

3. **SSL Configuration**
   ```bash
   # With Let's Encrypt
   certbot --nginx -d mbetterclient.example.com
   ```

#### Docker Deployment

```dockerfile
FROM python:3.9-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
EXPOSE 5000

CMD ["python", "main.py", "--web-host", "0.0.0.0"]
```

This comprehensive documentation covers all aspects of MbetterClient from installation to advanced deployment scenarios. For additional support, please refer to the project repository or contact the development team.