# Changelog

All notable changes to this project will be documented in this file.

## [1.2.6] - 2025-08-26

### Added
- **Automated Game Timer**: New `--start-timer` command line switch that sends START_GAME message after specified delay (default 4 minutes)
- **MatchTimerComponent Integration**: Fixed timer component initialization and registration with thread manager
- **Timer State API**: Real-time timer state API endpoints for web dashboard integration
- **Message Bus Communication**: Proper inter-thread communication between timer component and web dashboard
- **Timer Configuration**: Configurable timer delay with command-line parameter support

### Enhanced
- **Application Architecture**: Enhanced timer system with proper component lifecycle management
- **Web Dashboard Integration**: Timer state caching and API endpoint integration
- **Command Line Interface**: Extended CLI with timer configuration options
- **Documentation**: Comprehensive timer feature documentation and usage examples

### Fixed
- **MatchTimerComponent Registration**: Fixed timer component not being initialized during application startup
- **Timer State Communication**: Resolved web dashboard timer state requests not reaching timer component
- **API Endpoint Integration**: Fixed timer state API endpoints returning placeholder data

### Technical Details
- **Timer Architecture**: Implemented threading.Timer with proper daemon thread management
- **Message Bus Integration**: Added CUSTOM message type handling for timer state requests
- **Settings Integration**: Added TimerConfig dataclass with database persistence support
- **Web Dashboard Enhancement**: Added timer state caching and message handler for timer responses
- **Cross-Platform Compatibility**: Timer system works consistently across Windows, Linux, and macOS

## [1.2.5] - 2025-08-26

### Added
- **Extraction Management Page**: Complete drag-and-drop interface for managing outcome associations with extraction results
- **Server Time Digital Clock**: Prominent 24-hour format clock showing server time across all dashboard interfaces
- **Database Models for Extraction**: New `ExtractionAssociationModel` and `GameConfigModel` for storing outcome associations and game settings
- **Database Migration System**: Migration_014 for extraction associations and game configuration tables
- **API Endpoints for Extraction**: Complete REST API for managing outcome associations and game configuration
- **Drag & Drop Functionality**: Interactive outcome management with visual feedback and association persistence
- **Multi-Association Support**: Outcomes can be associated with multiple extraction results simultaneously
- **Trash Bin Removal**: Context-aware removal of associations based on drag source location
- **Game Configuration Panel**: Time limit settings for UNDER/OVER outcomes with database persistence
- **Server Time API**: `/api/server-time` endpoint providing server timestamp for accurate time display
- **Cross-Interface Clock**: Digital clock appears on all authenticated pages including cashier dashboard

### Enhanced
- **Web Dashboard Navigation**: Added extraction management page to main navigation menu
- **User Experience**: Silent drag-and-drop operations without alert interruptions
- **Time Synchronization**: Automatic server time sync every 30 seconds with offset calculation
- **Responsive Design**: Clock and extraction interface work seamlessly across all screen sizes
- **Error Handling**: Graceful fallbacks for server time API failures

### Fixed
- **Drag & Drop Detection**: Fixed trash bin drop zone detection with proper CSS classes
- **Multiple Associations**: Resolved issue preventing outcomes from being associated with multiple results
- **Alert Interruptions**: Removed popup alerts during drag-and-drop operations for smoother workflow
- **Clock Positioning**: Optimized clock placement in cashier dashboard navbar

### Technical Details
- **Database Schema**: Added extraction_associations and game_config tables with proper indexing
- **API Integration**: RESTful endpoints for CRUD operations on extraction data
- **JavaScript Architecture**: Modular drag-and-drop system with event delegation and state management
- **CSS Styling**: Professional clock design with hover effects and responsive breakpoints
- **Time Management**: Client-server time offset calculation for accurate server time display
- **Cross-Platform Compatibility**: Extraction system works consistently across different browsers and devices

## [1.2.4] - 2025-08-22

### Added
- **Complete Screen Casting System**: Integrated comprehensive screen capture and Chromecast streaming functionality into MBetterC application
- **ScreenCastComponent**: New threaded component inheriting from ThreadedComponent with full lifecycle management
- **Web-Based Screen Cast Interface**: Complete web dashboard at `/screen_cast` with device discovery, streaming controls, and real-time status updates
- **Chromecast Device Discovery**: Automatic discovery and management of Chromecast devices on the local network using pychromecast library
- **Cross-Platform Screen Capture**: FFmpeg-based screen recording with platform-specific audio/video input sources:
  - Linux: `:0.0+0,0` (X11) with `pulse` audio input
  - Windows: `desktop` with `dshow` audio input
  - macOS: `1:0` (screen) with `:0` audio input
- **HTTP Streaming Server**: Dedicated HTTP server for serving screen capture streams to Chromecast devices
- **Administrative Configuration**: Comprehensive screen cast settings panel in web dashboard configuration with:
  - Video quality settings (resolution, frame rate, bitrate)
  - Audio configuration options
  - Network streaming parameters
  - Chromecast device management
- **Real-Time Status Management**: Live status monitoring with proper button state management and streaming feedback
- **Network Stream URL Generation**: Automatically generated network-accessible streaming URLs for Chromecast compatibility
- **Command-Line Integration**: Screen casting enabled by default with `--no-screen-cast` flag for opt-out configuration

### Enhanced
- **Application Architecture**: Extended from 4 to 5 threaded components with screen casting integration
- **Message Bus Communication**: Added `WEB_ACTION` message type support for web interface screen cast commands
- **Database Configuration**: Added `ScreenCastConfig` dataclass with comprehensive settings and database persistence
- **Web Dashboard Navigation**: Added screen cast section with intuitive device discovery and control interface
- **Dependencies Management**: Added `ffmpeg-python>=0.2.0` and `pychromecast>=13.0.0` to requirements.txt

### Fixed
- **Message Bus Registration**: Proper component registration with message bus for screen cast messaging
- **Command Line Override**: Database settings no longer override `--no-screen-cast` command line argument
- **Message Type Compatibility**: Changed from non-existent `SYSTEM_COMMAND` to proper `WEB_ACTION` message type
- **Network IP Detection**: Implemented robust local IP detection for Chromecast-accessible stream URLs
- **Button State Management**: Real-time status access for proper UI button enabling/disabling
- **Chromecast Lifecycle**: Fixed streaming start/stop cycle by properly resetting Chromecast app state
- **API Compatibility**: Handled pychromecast API changes with safe attribute access patterns

### Technical Details
- **ScreenCastComponent Implementation**: Complete threaded component with HTTP server, FFmpeg capture, and Chromecast streaming
- **Web Routes Integration**: Added `screen_cast_routes.py` Flask blueprint with comprehensive API endpoints
- **Template Integration**: Added screen cast web interface templates with real-time device discovery
- **Configuration Integration**: Screen cast settings fully integrated into main configuration system
- **Cross-Platform FFmpeg Commands**: Platform-specific screen capture command generation with proper audio/video sources
- **HTTP Server Management**: Dedicated HTTP server thread for streaming with proper cleanup and lifecycle management
- **Chromecast App Management**: Proper DefaultMediaReceiver app lifecycle with start/stop/quit sequence

## [1.2.3] - 2025-08-21

### Added
- **Boxing Match Database Tables**: Complete `matches` and `match_outcomes` database tables adapted from mbetterd MySQL schema to SQLite
- **Cross-Platform Persistent Storage**: Comprehensive PyInstaller executable persistence with platform-specific user directories
- **Match Data Models**: Full SQLAlchemy models for boxing match management including:
  - Match tracking with fighter townships, venues, and timing information
  - Match outcomes with float values and column-based storage
  - ZIP file upload management with progress tracking and status monitoring
  - User association and creation tracking
- **Database Migration System**: Migration_008_AddMatchTables with comprehensive indexing and foreign key relationships
- **Platform-Specific Directory Handling**:
  - Windows: `%APPDATA%\MbetterClient\` for all user data
  - macOS: `~/Library/Application Support/MbetterClient/` (unified location)
  - Linux: `~/.local/share/MbetterClient/` (data) & `~/.config/MbetterClient/` (config)
- **Cross-Platform Test Suite**: Comprehensive test script verifying directory creation and database persistence
- **Enhanced Error Handling**: Fallback directory creation with permission testing and write verification

### Fixed
- **PyInstaller Compatibility**: Database and user data now persist correctly when running as single executable
- **Path Resolution**: All paths now resolve to persistent user directories instead of temporary executable locations
- **Directory Creation**: Robust cross-platform directory creation with proper error handling and fallbacks
- **Database Location**: SQLite database now stored in persistent user data directory across all platforms
- **API Timestamp Format**: Fixed fixture synchronization timestamp format to send Unix timestamp as long integer instead of ISO datetime string

### Enhanced
- **User Data Management**: Automatic creation of logs/, data/, uploads/, and templates/ subdirectories
- **Permission Validation**: Write permission testing before using directories with graceful fallbacks
- **Environment Detection**: Automatic PyInstaller execution detection for appropriate path handling
- **Database Schema**: Added comprehensive indexing for optimal query performance on match data

### Technical Details
- Implemented `get_user_data_dir()`, `get_user_config_dir()`, and `get_user_cache_dir()` functions
- Added `is_pyinstaller_executable()` detection for runtime environment awareness
- Enhanced `DatabaseConfig` class to automatically use persistent user data directory
- Created `Migration_008_AddMatchTables` with proper SQLite syntax and comprehensive indexing
- Updated application initialization to call `ensure_directories()` for persistent storage setup
- Added cross-platform test script `test_persistent_dirs.py` for validation

## [1.2.2] - 2025-08-21

### Added
- **Template Management System**: Complete HTML overlay template management with upload, delete, and real-time editing capabilities
- **Persistent Template Storage**: Cross-platform user template storage (Windows: %APPDATA%, macOS: ~/Library/Application Support, Linux: ~/.config)
- **Template Priority System**: Uploaded templates automatically override built-in templates with same filename
- **Custom URL Scheme Handler**: overlay:// protocol enables uploaded templates to access JavaScript overlay.js functionality
- **Template Code Viewer**: View and copy template source code directly from web interface with syntax highlighting
- **Live Template Switching**: Dashboard and video control forms now instantly switch to selected template with overlay updates
- **Template File Watcher**: Automatic template reloading when template files change on disk (using watchdog library)
- **Enhanced Template UI**:
  - Popup preview windows for better template testing
  - Template source code modal with copy-to-clipboard functionality
  - Dynamic template dropdown population from API
  - Comprehensive template management interface

### Fixed
- **API Endpoint Mismatch**: Fixed frontend calling wrong overlay update URL (/api/overlay/update vs /api/overlay)
- **Template Selection Issues**: Fixed template selection not working from video test page by adding automatic .html extension handling
- **JavaScript Accessibility**: Solved uploaded templates unable to access overlay.js by implementing custom overlay:// URL scheme
- **MessageBuilder Methods**: Added missing overlay_update() method to MessageBuilder class
- **Template Reload Logic**: Enhanced overlay update functionality to load specific template from form selection instead of just reloading current template

### Enhanced
- **Template Loading**: Prioritizes uploaded templates over built-in ones with same filename
- **File System Integration**: Qt Resource Collections (QRC) integration for JavaScript file embedding
- **Cross-Platform Paths**: Proper persistent storage paths for all operating systems
- **PyInstaller Compatibility**: Template system works correctly in compiled executable with persistent user data outside bundle
- **WebChannel Communication**: Enhanced Qt WebChannel integration between application and JavaScript overlay templates
- **Template Name Processing**: Automatic .html extension handling and proper template name normalization

### Technical Details
- Implemented OverlayUrlSchemeHandler for serving JavaScript files via custom overlay:// protocol
- Enhanced template loading with priority system (uploaded > built-in > default fallback)
- Added comprehensive file watcher monitoring both built-in and uploaded template directories
- Integrated Qt Resource system for embedding JavaScript files accessible via qrc:// URLs
- Enhanced template selection with automatic extension handling and proper fallback mechanisms
- Updated PyInstaller configuration to include templates directory and watchdog dependency

## [1.2.1] - 2025-08-20

### Fixed
- **Critical**: Qt video player display issue completely resolved - video frames now render properly on Linux
- **Critical**: WindowStaysOnTopHint interference with Qt video rendering eliminated by fixing always_on_top configuration
- **Critical**: Database configuration persistence issue resolved - old cached settings no longer override new defaults
- **UI**: Removed all toolbars, menu bars, status bars, and context menus for clean minimal video player interface
- Main thread architecture properly implemented for Qt event loop with background components on separate threads
- Window focus and OpenGL context management fixed for proper video frame rendering
- Configuration loading sequence corrected to prevent database overrides of updated settings

### Changed
- Qt player interface now completely clean with no UI chrome (toolbars, menus, status bars removed)
- All functionality accessible via keyboard shortcuts (F11: fullscreen, S: stats, Space: play/pause, M: mute, Escape: exit)
- Database reset mechanism implemented to clear old cached configuration on major setting changes
- Main application window behavior now matches test script (can go behind other applications)
- Overlay window properly separated from main window for correct layering

### Technical Details
- Fixed settings.py default always_on_top: bool = False to prevent WindowStaysOnTopHint on main window
- Implemented database configuration reset to eliminate cached settings conflicts
- Removed setMenuBar(), setStatusBar(), and setContextMenuPolicy() calls for clean interface
- Enhanced PlayerWindow.setup_ui() to disable all UI chrome elements
- Maintained complete keyboard control functionality while removing visual clutter

## [1.2.0] - 2025-08-20

### Added
- **Qt Player Overlay System**: Dual overlay system with command-line switchable options between QWebEngineView and native Qt widgets
- **Admin Dashboard Shutdown**: Admin-only quit button in web dashboard with guaranteed force termination
- **Enhanced Overlay Templates**: Improved video overlay rendering with reduced JavaScript timing errors
- **Native Qt Widget Overlays**: Stable alternative to WebEngine overlays for better performance and reliability

### Fixed
- **Critical**: Qt player window close now properly exits entire application without deadlocks
- **Critical**: Ctrl+C signal handling fully restored and functional across all components
- **Critical**: Background thread management fixed - all threads now properly daemonized to prevent exit blocking
- **Critical**: Circular dependency deadlocks eliminated in shutdown process using force-exit mechanism
- **Critical**: WebEngine overlay timing errors significantly reduced with enhanced DOM readiness checks
- **Critical**: Desktop transparency bleed-through issues resolved by removing problematic transparency attributes
- Video controls removed for clean overlay-only interface
- JavaScript DOM safety enhanced with comprehensive error handling
- Qt threading architecture optimized for better stability

### Changed
- Background threads now run as daemon threads to prevent application exit blocking
- Qt signal integration enhanced with aboutToQuit signal handling for proper lifecycle management
- Shutdown message handling improved with sender-specific logic to avoid circular dependencies
- WebEngine readiness checks enhanced for safer overlay updates
- Force-exit mechanism implemented using os._exit(0) with delayed execution to bypass Qt event loop issues

### Technical Details
- Fixed closeEvent() in Qt player to remove forced os._exit(0) and allow proper Qt shutdown sequence
- Enhanced signal_handler() in main.py to detect Qt applications and use qt_app.quit() appropriately
- Modified ThreadManager to set daemon=True for all background threads ensuring clean process termination
- Added /api/system/shutdown endpoint with admin authentication and immediate HTTP response before force termination
- Implemented comprehensive background component cleanup in _qt_about_to_quit() method
- Added desktop transparency prevention by removing WA_TranslucentBackground window attribute
- Enhanced WebEngine overlay safety with try-catch blocks and DOM state validation

## [1.1.0] - 2025-08-19

### Added
- Enhanced token creation workflow with professional modal dialogs
- Comprehensive troubleshooting section in README
- Default admin user creation on first run
- Permanent token deletion functionality
- Section-based configuration updates
- Database operation stability improvements

### Fixed
- **Critical**: Application now exits gracefully with single Ctrl+C press
- **Critical**: API tokens properly display after creation in web interface
- **Critical**: User creation now saves properly and displays immediately
- **Critical**: Configuration updates through web dashboard now work correctly
- **Critical**: Qt player thread freezing issue resolved by running Qt event loop on main thread
- SQLAlchemy session binding issues causing data access errors
- Token revocation now permanently deletes tokens from database
- Frontend JavaScript token management and display
- Database operations extract data before session closure
- Signal handler optimization with reduced timeouts
- Web dashboard routing and static file loading issues
- ConfigManager missing update_section method
 
### Changed
- Reduced application shutdown timeouts for faster exit (10s→3s, 5s→2s)
- Updated README with comprehensive troubleshooting guide
- Enhanced API documentation with all endpoints
- Improved error handling across all components
- Qt player now runs Qt event loop on main thread instead of background thread

### Technical Details
- Fixed database session binding by extracting data to dictionaries
- Added proper signal handling flow: signal → shutdown event → cleanup → exit
- Enhanced frontend with Bootstrap modal dialogs for token display
- Implemented section-based configuration management
- Added comprehensive session lifecycle management
- Qt player thread freezing fixed by running Qt event loop on main thread instead of background thread
- Qt player no longer inherits from ThreadedComponent to comply with Qt threading requirements
- Message processing for Qt player now runs in a separate thread while Qt event loop runs on main thread

## [1.0.0] - 2025-08-15

### Added
- Initial release of MbetterClient
- PyQt video player with overlay support
- Flask web dashboard with authentication
- REST API client with configurable endpoints
- Multi-threaded architecture with message bus
- SQLite database with versioning system
- PyInstaller build configuration
- Cross-platform support (Windows, Linux, macOS)
- JWT and long-lived API token management
- User management system
- Configuration management interface
- Video upload and playback testing

### Features
- Fullscreen and windowed video playback modes
- Customizable video overlay templates
- Web-based administration interface
- API token creation and management
- User authentication and authorization
- Database migrations system
- Message-based inter-thread communication
- Comprehensive logging system
- Configuration persistence