import json
import re
from hatchling.builders.hooks.plugin.interface import BuildHookInterface

def sanitize_name(name):
    # Replace invalid characters with words
    name = name.replace('#', 'SHARP')
    name = name.replace('*', 'STAR')
    name = name.replace('+', 'PLUS')
    # Replace any remaining non-alphanumeric characters with underscore
    name = re.sub(r'[^a-zA-Z0-9_]', '_', name)
    # Prepend underscore if it starts with a digit
    if name[0].isdigit():
        name = '_' + name
    return name.upper()

class CustomBuildHook(BuildHookInterface):
    def initialize(self, version, build_data):
        lang_json_path = "src/pylocc/language.json"
        output_py_path = "src/pylocc/language.py"

        with open(lang_json_path, "r", encoding="utf-8") as f:
            languages = json.load(f)

        enum_content = "# This file is auto-generated by the build system.\n"
        enum_content += "# DO NOT EDIT THIS FILE MANUALLY.\n\n"
        enum_content += "import json\n"
        enum_content += "from enum import Enum\n"
        enum_content += "from pathlib import Path\n\n"
        enum_content += "class Language(Enum):\n"

        for lang_name in sorted(languages.keys()):
            enum_member_name = sanitize_name(lang_name)
            enum_content += f'    {enum_member_name} = "{lang_name}"\n'

        enum_content += """

    def get_config(self):
        config_path = Path(__file__).parent / "language.json"
        with open(config_path, "r", encoding="utf-8") as f:
            all_configs = json.load(f)
        return all_configs.get(self.value)
"""

        with open(output_py_path, "w", encoding="utf-8") as f:
            f.write(enum_content)

        print(f"Generated {output_py_path} from {lang_json_path}")
