# 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

```
~/.config/MbetterClient/          # Linux
~/Library/Application Support/MbetterClient/  # macOS
%APPDATA%\MbetterClient\          # Windows
├── mbetterclient.db              # SQLite database
├── config/
│   ├── app.json                  # Application settings
│   ├── api_endpoints.json        # API client configuration
│   └── templates.json            # Overlay template settings
└── logs/
    ├── app.log                   # Application logs
    ├── web.log                   # Web dashboard logs
    └── api.log                   # API client logs
```

## 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
  --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

### 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

## 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>
```

## 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

Add custom tables for application-specific data:

```python
# In database/models.py

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
- Regular backup of configuration and database

### 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.