import os
import yaml

# Directory containing the YAML files
CONFIG_DIR = "configmaps"
MAPPING_YML = "config_mappings.yml"

# Load the placeholder mappings
with open(MAPPING_YML, "r") as yamlfile:
    placeholder_mappings = yaml.safe_load(yamlfile)

# Function to replace placeholders with original values
def replace_placeholders(obj):
    if isinstance(obj, dict):
        for k, v in obj.items():
            if isinstance(v, str) and v in placeholder_mappings:
                obj[k] = placeholder_mappings[v]
            else:
                replace_placeholders(v)
    elif isinstance(obj, list):
        for i, item in enumerate(obj):
            if isinstance(item, str) and item in placeholder_mappings:
                obj[i] = placeholder_mappings[item]
            else:
                replace_placeholders(item)

# Process all YAML files and replace placeholders
for filename in os.listdir(CONFIG_DIR):
    if filename.endswith(".yml") or filename.endswith(".yaml"):
        file_path = os.path.join(CONFIG_DIR, filename)
        
        with open(file_path, "r") as file:
            data = yaml.safe_load(file)
        
        if data:
            replace_placeholders(data)
            
            with open(file_path, "w") as file:
                yaml.safe_dump(data, file, default_flow_style=False,sort_keys=False)

print("Placeholders replaced with original values in all files.")