import os
import glob
import difflib

# Read valid keys
valid_keys = set()
with open('valid_keys.txt', 'r') as f:
    for line in f:
        valid_keys.add(line.strip())

def process_file(filepath):
    with open(filepath, 'r') as f:
        lines = f.readlines()
    
    new_lines = []
    changed = False
    
    for line in lines:
        stripped = line.strip()
        # Skip empty lines, metadata sections, or already commented lines with ;
        if not stripped or stripped.startswith('[') or stripped.startswith(';'):
            new_lines.append(line)
            continue
            
        if '=' in line:
            parts = line.split('=', 1)
            key = parts[0].strip()
            val = parts[1]
            
            if key in valid_keys:
                new_lines.append(line)
            else:
                matches = difflib.get_close_matches(key, valid_keys, n=1, cutoff=0.8)
                if matches:
                    new_key = matches[0]
                    new_lines.append(line.replace(key + ' ', new_key + ' ', 1) if key + ' ' in line else line.replace(key + '=', new_key + '=', 1))
                    print(f"{filepath}: Reacted {key} to {new_key}")
                    changed = True
                else:
                    new_lines.append(';;;' + line)
                    print(f"{filepath}: Commented {key}")
                    changed = True
        else:
            new_lines.append(line)
            
    if changed:
        with open(filepath, 'w') as f:
            f.writelines(new_lines)

for root, dirs, files in os.walk('print_config/prusa_slicer'):
    for file in files:
        if file.endswith('.ini'):
            process_file(os.path.join(root, file))

