#!/usr/bin/env python3
"""
Version Manager for Progression Loader
"""

import re
import sys

def get_current_version():
    """Get the current version from update_config.py"""
    try:
        with open('update_config.py', 'r') as f:
            content = f.read()
            match = re.search(r'"current_version":\s*"([^"]+)"', content)
            if match:
                return match.group(1)
    except FileNotFoundError:
        pass
    return None

def set_version(new_version):
    """Set the version in update_config.py"""
    try:
        with open('update_config.py', 'r') as f:
            content = f.read()
        
        updated_content = re.sub(
            r'"current_version":\s*"[^"]+"',
            f'"current_version": "{new_version}"',
            content
        )
        
        with open('update_config.py', 'w') as f:
            f.write(updated_content)
        
        print(f"✅ Updated version to {new_version}")
        return True
    except Exception as e:
        print(f"❌ Error updating version: {e}")
        return False

def validate_version(version_string):
    """Validate semantic versioning format"""
    pattern = r'^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9\-\.]+))?$'
    return re.match(pattern, version_string) is not None

def suggest_next_version(current_version):
    """Suggest next version numbers"""
    if not current_version:
        return ["1.0.0"]
    
    try:
        parts = current_version.split('.')
        if len(parts) >= 3:
            major, minor, patch = int(parts[0]), int(parts[1]), int(parts[2])
            return [
                f"{major}.{minor}.{patch + 1}",  # Patch
                f"{major}.{minor + 1}.0",        # Minor
                f"{major + 1}.0.0"               # Major
            ]
    except ValueError:
        pass
    
    return ["1.0.0"]

def main():
    """Main interface"""
    if len(sys.argv) < 2:
        current = get_current_version()
        print(f"Current Version: {current or 'Not found'}")
        
        if current:
            suggestions = suggest_next_version(current)
            print("Suggested versions:", ", ".join(suggestions))
        
        print("\nUsage:")
        print("  python version_manager.py <version>  # Set version")
        print("  python version_manager.py current    # Show current")
        print("\nExample: python version_manager.py 1.0.1")
        return
    
    command = sys.argv[1]
    
    if command == "current":
        current = get_current_version()
        print(f"Current version: {current or 'Not found'}")
        return
    
    # Set version
    new_version = command
    
    if not validate_version(new_version):
        print(f"❌ Invalid version format: {new_version}")
        print("Use format: MAJOR.MINOR.PATCH (e.g., 1.0.1)")
        return
    
    if set_version(new_version):
        print("Next steps:")
        print(f"  git add update_config.py")
        print(f"  git commit -m 'Bump version to {new_version}'")
        print(f"  git tag v{new_version} && git push --tags")

if __name__ == "__main__":
    main()