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 create_default_image_file():
    """Creates a file named 'Default Image <contents>' with the contents of C:\\version.txt or default content."""
    file_content = read_version_file()
    file_name = f"Default Image {file_content}"
    default_image_path = os.path.join(os.getcwd(), file_name)

    try:
        with open(default_image_path, "w") as file:
            file.write(file_content)
        print(f"Created file '{file_name}' with content: {file_content}")
    except IOError as e:
        print(f"Failed to create '{file_name}': {e}")

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}")
        create_default_image_file()
        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()