#!/usr/bin/env python3
"""
Increment StreamA2026 version

Usage:
    python increment_version.py

This script increments the last number in the VERSION file (e.g., 0.0.0.0 -> 0.0.0.1)
"""
from pathlib import Path
from datetime import datetime


def increment_version():
    """Increment the last number in the VERSION file"""
    version_file = Path(__file__).parent.parent / "VERSION"
    frontend_version_file = Path(__file__).parent.parent / "frontend" / "VERSION"
    env_file = Path(__file__).parent.parent / ".env"
    
    if not version_file.exists():
        print("ERROR: VERSION file not found")
        return None
    
    # Read current version (first line only, second line is build date)
    with open(version_file, 'r') as f:
        current_version = f.readline().strip()
    
    # Parse version
    parts = current_version.split('.')
    if len(parts) != 4:
        print(f"ERROR: Invalid version format: {current_version}. Expected format: X.Y.Z.W")
        return None
    
    try:
        # Increment last number
        major, minor, patch, build = map(int, parts)
        build += 1
        new_version = f"{major}.{minor}.{patch}.{build}"
        
        # Get current date and time in YYYY-MM-DD HH:MM:SS format
        build_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # Write new version with build date to project root
        with open(version_file, 'w') as f:
            f.write(f"{new_version}\n{build_date}")
        
        # Write new version with build date to frontend
        with open(frontend_version_file, 'w') as f:
            f.write(f"{new_version}\n{build_date}")
        
        # Update .env file with new VERSION and BUILD_DATE
        if env_file.exists():
            with open(env_file, 'r') as f:
                env_lines = f.readlines()
            
            has_version = any(line.startswith('VERSION=') for line in env_lines)
            has_build_date = any(line.startswith('BUILD_DATE=') for line in env_lines)
            
            with open(env_file, 'w') as f:
                for line in env_lines:
                    if line.startswith('VERSION='):
                        f.write(f'VERSION={new_version}\n')
                    elif line.startswith('BUILD_DATE='):
                        f.write(f'BUILD_DATE={build_date}\n')
                    else:
                        f.write(line)
                
                # Add VERSION if it doesn't exist
                if not has_version:
                    f.write(f'VERSION={new_version}\n')
                # Add BUILD_DATE if it doesn't exist
                if not has_build_date:
                    f.write(f'BUILD_DATE={build_date}\n')
        
        print(f"Version incremented: {current_version} -> {new_version}")
        print(f"Build date: {build_date}")
        return new_version
        
    except ValueError as e:
        print(f"ERROR: Invalid version numbers: {e}")
        return None


if __name__ == "__main__":
    increment_version()
