import json
import subprocess
import os
import sys
from datetime import datetime

VERSION_FILE = 'VERSION.json'
GIT_PATH_FILE = '.git_path'

def get_git_path():
    if os.path.exists(GIT_PATH_FILE):
        with open(GIT_PATH_FILE, 'r') as f:
            return f.read().strip()
    return 'git'

def run_command(cmd):
    print(f"Executing: {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"Error: {result.stderr}")
        sys.exit(1)
    return result.stdout.strip()

def main():
    git = get_git_path()
    
    # 1. Read and Parse Version
    if not os.path.exists(VERSION_FILE):
        print(f"Error: {VERSION_FILE} not found.")
        sys.exit(1)
        
    with open(VERSION_FILE, 'r') as f:
        data = json.load(f)
        
    old_version = data.get('version', '1.0.0')
    parts = old_version.split('.')
    if len(parts) < 3:
        parts.extend(['0'] * (3 - len(parts)))
    
    # Check for --minor or --major flags
    if '--minor' in sys.argv:
        parts[1] = str(int(parts[1]) + 1)
        parts[2] = '0'
    elif '--major' in sys.argv:
        parts[0] = str(int(parts[0]) + 1)
        parts[1] = '0'
        parts[2] = '0'
    else:
        # Default: patch increment
        parts[2] = str(int(parts[2]) + 1)
    
    new_version = '.'.join(parts)
    data['version'] = new_version
    data['last_build'] = datetime.now().strftime("%Y-%m-%d-%H%M")
    
    # Optional: Rotate changelog if needed, but for now just update version
    print(f"Incrementing version: {old_version} -> {new_version}")
    
    with open(VERSION_FILE, 'w') as f:
        json.dump(data, f, indent=2)

    # 2. Git Operations
    run_command([git, 'add', '.'])
    run_command([git, 'commit', '-m', f"Build [v{new_version}]"])
    
    # 3. Create branch (snapshot)
    branch_name = f"v{new_version}"
    run_command([git, 'branch', branch_name])
    
    # 4. Update master branch
    print(f"🔄 Updating 'master' branch to v{new_version}...")
    current_branch = run_command([git, 'rev-parse', '--abbrev-ref', 'HEAD'])
    run_command([git, 'checkout', 'master'])
    run_command([git, 'merge', current_branch])
    run_command([git, 'checkout', current_branch])

    # 5. Create Production Bundle
    print("📦 Generating production bundle...")
    run_command(['./export_prod.sh'])
    
    print(f"Successfully saved version {new_version}, created branch {branch_name}, updated 'master', and generated production ZIP.")
    print("Verification: check for the .zip file in the root.")

if __name__ == "__main__":
    main()
