import os
import re

def fix_toml(filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        
    sections = {}
    current_section = None
    
    for line in lines:
        sline = line.strip()
        
        if sline.startswith('[') and sline.endswith(']'):
            current_section = sline
            if current_section not in sections:
                sections[current_section] = []
        else:
            if current_section is None:
                if sline:  # Ignore empty lines at the very top before any section
                    current_section = "_TOP_"
                    if current_section not in sections:
                        sections[current_section] = []
            if current_section is not None:
                sections[current_section].append(line)
                
    with open(filepath, 'w', encoding='utf-8') as f:
        if "_TOP_" in sections:
            for line in sections["_TOP_"]:
                f.write(line)
            del sections["_TOP_"]
            
        for sec, slines in sections.items():
            f.write(sec + '\n')
            for line in slines:
                if line.strip(): # keep only non-empty to avoid huge gaps
                    f.write(line)
            f.write('\n')

for file in ['locales/template.toml', 'locales/ko.toml', 'locales/en.toml']:
    fix_toml(file)
    print("Fixed", file)

