import os
import re
import json

BASE_DIR = "FrontEnd/js"
IMPORT_MAP_FILE = "import-map.json"

# Load import map
with open(IMPORT_MAP_FILE, "r", encoding="utf-8") as f:
    import_map = json.load(f)["imports"]

# Build lookup by filename only
filename_to_key = {}
for key, path in import_map.items():
    filename = os.path.basename(path)
    filename_to_key[filename.lower()] = key

def replace_imports_in_file(filepath):
    with open(filepath, "r", encoding="utf-8") as f:
        content = f.read()

    changed = False

    def replacer(match):
        nonlocal changed
        old_path = match.group(1)
        filename = os.path.basename(old_path).lower()

        if filename in filename_to_key:
            new_path = filename_to_key[filename]
            changed = True
            return f'{match.group(0).split("from")[0].strip()} from "{new_path}";'

        return match.group(0)

    # Regex for import ... from '...';
    new_content = re.sub(r'import\s+[^;]*\s+from\s+[\'"]([^\'"]+)[\'"];?', replacer, content)

    if changed:
        with open(filepath, "w", encoding="utf-8") as f:
            f.write(new_content)
        print(f"✅ Updated imports in {filepath}")

def process_directory(base_dir):
    for root, _, files in os.walk(base_dir):
        for file in files:
            if file.endswith(".js"):
                replace_imports_in_file(os.path.join(root, file))

if __name__ == "__main__":
    process_directory(BASE_DIR)
