import json
import sys
import re

def validate_project_name(name):
    if not re.match(r'^[A-Za-z0-9_-]+$', name):
        raise ValueError("Project name must contain only ASCII letters, numbers, hyphens, or underscores.")

def update_prjsettings(new_name):
    with open('prjsettings.json', 'r') as file:
        settings = json.load(file)
    settings['projectName'] = new_name
    with open('prjsettings.json', 'w') as file:
        json.dump(settings, file, indent=4)

def update_launch_config(new_name):
    with open('.vscode/launch.json', 'r') as file:
        config = json.load(file)
    for conf in config['configurations']:
        if 'program' in conf:
            conf['program'] = re.sub(r'[^/\\]+Debug\.exe$', new_name + 'Debug.exe', conf['program'])
    with open('.vscode/launch.json', 'w') as file:
        json.dump(config, file, indent=4)

if __name__ == "__main__":
    if len(sys.argv) > 2:
        # 引数が多すぎる場合、使用方法を表示
        print("Usage: python change_project_name.py [new_project_name]")
        sys.exit(1)
    elif len(sys.argv) == 2:
        # 引数が1つ提供されている場合、それを使用
        new_project_name = sys.argv[1]
    else:
        # 引数がない場合、ユーザーに入力を求める
        new_project_name = input("Enter the new project name: ").strip()
        if not new_project_name:
            print("No project name provided.")
            sys.exit(1)

    try:
        validate_project_name(new_project_name)
        update_prjsettings(new_project_name)
        update_launch_config(new_project_name)
    except ValueError as e:
        print("Error: " + str(e))
        sys.exit(1)

