import os
import sys
import time
import shutil

def read_version_file():
    """Reads the version from C:\version.txt"""
    try:
        with open("C:\\version.txt", "r") as file:
            return file.read().strip()
    except FileNotFoundError:
        return "default_version"

def rename_and_launch():
    version_name = read_version_file()
    new_exe_name = f"{version_name}.exe"

    # Current EXE path (no .py references anymore)
    current_exe = sys.executable

    # Prevent infinite recursion if already renamed
    if os.path.basename(current_exe) == new_exe_name:
        print(f"Running as {new_exe_name}")
        while True:
            time.sleep(60)  # Keep the renamed process running
    else:
        renamed_exe_path = os.path.join(os.path.dirname(current_exe), new_exe_name)

        # Only rename if the target file doesn't already exist
        if not os.path.exists(renamed_exe_path):
            shutil.copy(current_exe, renamed_exe_path)
        
        # Relaunch the renamed version and terminate the current one
        os.system(f'start "" "{renamed_exe_path}"')
        sys.exit()

if __name__ == "__main__":
    rename_and_launch()
