import os

def fix_content(content):
    replacements = {
        'Ã¡': 'á', 'Ã£': 'ã', 'Ãª': 'ê', 'Ã§': 'ç', 'Ã³': 'ó',
        'Ã­': 'í', 'Ãº': 'ú', 'Ã©': 'é', 'Ã´': 'ô', 'Ã€': 'À',
        'Ã‰': 'É', 'Ã“': 'Ó', 'Ãš': 'Ú', 'Ã‚': 'Â', 'Ã‡': 'Ç',
        'Ãƒ': 'Ã', 'Ãµ': 'õ', 'Ã ': 'à', 'Ã¨': 'è', 'Ã¬': 'ì',
        'Ã²': 'ò', 'Ã¹': 'ù', 'Ã±': 'ñ', 'Ã‘': 'Ñ'
    }
    # Double encoding fixes
    double_replacements = {
        'ÃƒÂ¡': 'á', 'ÃƒÂ£': 'ã', 'ÃƒÂ³': 'ó', 'ÃƒÂª': 'ê', 'ÃƒÂ§': 'ç',
        'ÃƒÂ©': 'é', 'ÃƒÂ­': 'í', 'ÃƒÂº': 'ú', 'ÃƒÂ´': 'ô', '├â┬¡': 'í',
        'Ãâ¡': 'á', 'Ãâ£': 'ã', 'Ãâ³': 'ó', 'Ãâª': 'ê', 'Ãâ§': 'ç'
    }
    
    for old, new in double_replacements.items():
        content = content.replace(old, new)
    for old, new in replacements.items():
        content = content.replace(old, new)
    return content

def process_directory(directory):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(('.tsx', '.ts', '.js', '.jsx')):
                path = os.path.join(root, file)
                try:
                    with open(path, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    fixed = fix_content(content)
                    
                    if fixed != content:
                        print(f"Corrigindo: {path}")
                        with open(path, 'w', encoding='utf-8') as f:
                            f.write(fixed)
                except UnicodeDecodeError:
                    try:
                        with open(path, 'r', encoding='latin-1') as f:
                            content = f.read()
                        fixed = fix_content(content)
                        print(f"Corrigindo (latin-1): {path}")
                        with open(path, 'w', encoding='utf-8') as f:
                            f.write(fixed)
                    except Exception as e:
                        print(f"Erro em {path}: {e}")

if __name__ == "__main__":
    process_directory(r"C:\dev\saveinmed\frontend\src")
    process_directory(r"C:\dev\saveinmed\saveinmed-frontend\src")
