# Changelog

All notable changes to the Fixture Manager daemon project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.2.3] - 2025-08-26

### Added
- **Match Status System**: Comprehensive 8-state status tracking for matches
  - New `status` column with enum values: 'pending', 'scheduled', 'bet', 'ingame', 'cancelled', 'failed', 'paused', 'done'
  - Default status 'pending' for all new matches
  - Database migration Migration_006 for schema updates
  - Web interface integration showing status information
  - API endpoints include status in responses

### Enhanced
- **Active Status Logic**: Updated to require match status='pending' in addition to ZIP upload completion
  - Match is now considered "active" only when: ZIP upload completed + checksum present + status='pending'
  - More precise control over match activation workflow
  - Better separation between upload completion and match processing states

### Fixed
- **Database Configuration**: Fixed MySQL/MariaDB authentication issues
- **Configuration Loading**: Robust fallback mechanisms for various deployment scenarios
- **PyInstaller Compatibility**: Cross-platform persistent directory system

### Technical Details
- **Database Schema**: Added status column (enum, indexed, default 'pending')
- **Model Updates**: Enhanced Match model with status field and updated set_active() logic
- **Migration System**: New Migration_006 with proper rollback support
- **Web Interface**: Updated templates to display status information
- **API Integration**: Status field included in all match-related API responses

---

## [1.2.2] - 2025-08-21

### Fixed
- **Fixture parser fighter column mapping bug** - Fixed issue where both fighter1 and fighter2 were being sourced from the fighter1 column
  - Improved partial column matching logic in [`FixtureParser.detect_required_columns()`](app/upload/fixture_parser.py:179)
  - Added specific logic for fighter column detection to prevent cross-mapping
  - Fighter1 columns now properly map to fighter1 database field
  - Fighter2 columns now properly map to fighter2 database field
  - Enhanced matching prevents false positives (e.g., "fighter2" column incorrectly matching "fighter1" field)
  - Maintains backward compatibility with existing column naming conventions

### Technical Details
- **Root Cause**: The original partial matching logic used `possible_name.split()[0]` which caused both "fighter 1" and "fighter 2" to become "fighter" after splitting, leading to incorrect column mapping
- **Solution**: Implemented fighter-specific matching logic that checks for both the "fighter" keyword and the specific number (1 or 2) in the column name
- **Impact**: Ensures accurate data mapping during fixture file uploads, preventing fighter data mix-ups

---

## [1.2.1] - 2025-08-21

### Added
- **Cross-platform persistent directory system** for PyInstaller compatibility
  - Windows support using `%APPDATA%/MBetter` directory structure
  - macOS support using `~/Library/Application Support/MBetter` directory
  - Linux support with primary `/opt/MBetter` and fallback `~/.local/share/MBetter`
  - Automatic PyInstaller environment detection and optimization
- **Configuration file migration system**
  - Automatic `.env` to `mbetterd.conf` migration for PyInstaller deployments
  - `migrate_config.py` utility script for production environment transitions
  - Persistent configuration storage in platform-appropriate locations
  - Fallback support for legacy `.env` files during development
- **Authenticated ZIP download API endpoint**
  - New `/api/download/zip/<match_id>` endpoint with hybrid authentication
  - Supports both JWT and API token authentication with automatic fallback
  - Access control ensuring users can only download their own match files (or admin access)
  - Secure file serving from persistent ZIP upload directories

### Enhanced
- **Upload directory persistence** - All uploads now stored outside PyInstaller temp directories
  - ZIP files stored in persistent ZIP_UPLOADS_DIR
  - Fixture files stored in persistent FIXTURES_DIR
  - Temporary files managed in persistent TEMP_DIR
- **Configuration system improvements**
  - Enhanced config loading with priority: environment variables > config file > defaults
  - Automatic configuration file discovery in persistent directories
  - Comprehensive error handling with fallback mechanisms
- **API updates endpoint improvements**
  - ZIP download URLs now use authenticated API endpoint instead of web routes
  - Enhanced security for programmatic access to ZIP files
  - Consistent authentication across all API endpoints

### Fixed
- **PyInstaller temporary directory issues** - Files now persist between application restarts
- **Cross-platform path handling** - Proper directory structures for all supported platforms
- **Configuration loading reliability** - Robust fallback mechanisms for various deployment scenarios

### Technical Details
- **Directory Structure**: Platform-specific persistent directories with proper fallbacks
- **Config Migration**: Seamless transition from development .env to production mbetterd.conf
- **PyInstaller Detection**: Automatic environment detection and directory path adjustment
- **Authentication**: Unified authentication system across web and API endpoints
- **File Storage**: Persistent upload storage with cross-platform compatibility

### Security
- **Enhanced API authentication** for file downloads
- **Access control validation** for ZIP file access
- **Secure configuration file handling** with proper permissions
- **Path traversal protection** in persistent directory operations

---

## [1.2.0] - 2025-08-21

### Added
- **New `/api/updates` endpoint** for incremental fixture data synchronization
  - Supports both GET and POST HTTP methods
  - Optional `from` parameter for timestamp-based filtering
  - Returns fixtures updated after specified unix timestamp
  - Configurable default count when no `from` parameter provided
  - Includes ZIP download URLs in API response
- **Fixture active time tracking** with automatic timestamp management
  - New `fixture_active_time` column in matches table (BigInteger, indexed)
  - Automatic timestamp setting when all matches in fixture become active
  - Preserves original activation time (no overwrites)
- **Hybrid authentication system** for maximum compatibility
  - Supports JWT tokens (short-lived, from login)
  - Supports API tokens (long-lived, from web interface)
  - Tries JWT first, falls back to API tokens automatically
  - Multiple token header formats supported
- **System settings integration** for configurable behavior
  - New `api_updates_default_count` setting (default: 10)
  - Configurable via web interface
  - Proper type conversion and fallback handling
- **SHA1-based ZIP file naming** for consistency
  - Uses SHA1 hash of (unix_timestamp + original_filename)
  - Applied across all upload methods (regular and streaming)
  - Maintains compatibility with existing download infrastructure
- **Data backfill utility** for existing fixtures
  - `backfill_fixture_times.py` script for one-time data migration
  - Automatically sets fixture_active_time for existing active fixtures
  - Comprehensive logging and progress reporting
- **Fallback mechanisms** for robustness
  - Automatic fallback to active_status queries when fixture_active_time is null
  - Graceful degradation for existing data without timestamps
  - Error handling and logging for all edge cases

### Enhanced
- **Database migration system** with new Migration_005
  - Added fixture_active_time column with proper indexing
  - Python 2.7 compatibility fixes (no f-strings)
  - Custom migration runner script for easier execution
- **API authentication flexibility** 
  - Authorization header (`Bearer token`)
  - X-API-Token header
  - Query parameter support (less secure, but available)
- **Query optimization and limits**
  - Both default and filtered queries respect configurable limits
  - Proper ordering (ascending for 'from' queries, descending for default)
  - Efficient database queries with appropriate indexes
- **Logging improvements**
  - Fixed import errors in models.py
  - Consistent logging across all new features
  - Proper error handling and debug information

### Fixed
- **Import errors** in models.py (get_logger function)
- **Python 2.7 compatibility** in migration scripts
- **Type conversion issues** in SystemSettings.get_setting()
- **Query performance** with proper indexing and limits

### Technical Details
- **Database Schema**: Added fixture_active_time column (BigInteger, nullable, indexed)
- **API Endpoints**: New `/api/updates` with comprehensive functionality
- **Authentication**: Dual-mode JWT/API token support with automatic fallback
- **File Operations**: SHA1-based naming for all ZIP uploads
- **Configuration**: New system setting for API behavior customization
- **Migration**: Version 005 for schema updates with proper rollback support

### Security
- All authentication methods maintain existing security standards
- API token validation and JWT verification unchanged
- Proper input validation for all new parameters
- Rate limiting and access controls remain in effect

---

## [1.1.0] - 2025-08-18

### Added
- ✅ **API Token Management**: Complete user-generated token system
- ✅ **Enhanced Security**: SHA256 token hashing with usage tracking
- ✅ **Web Interface**: Professional token management UI
- ✅ **Multiple Auth Methods**: Bearer tokens, headers, and query parameters
- ✅ **Token Lifecycle**: Create, revoke, extend, and delete operations
- ✅ **Usage Monitoring**: Last used timestamps and IP tracking
- ✅ **Database Migration**: Automatic schema updates with versioning
- ✅ **REST API Endpoints**: Protected fixture and match data access
- ✅ **Documentation**: Comprehensive API and security guidelines

---

## [1.0.0] - 2025-08-01

### Added
- Initial release of Fixture Manager daemon
- Secure web dashboard with authentication
- RESTful API with JWT authentication
- MySQL database integration
- Advanced file upload system with progress tracking
- Dual-format support (CSV/XLSX)
- Two-stage upload workflow
- Daemon process management with systemd integration
- Security features and validation
- Comprehensive documentation