import os
import re

def deep_clean(content):
    # Padrão quádruplo corrompido (ex: ÃÆ’Ã†â€™Ãâ€šÂÂ¡ -> á)
    patterns = {
        r'ÃÆ’Ã†â€™Ãâ€šÂÂ¡': 'á',
        r'ÃÆ’Ã†â€™Ãâ€šÂÂ£': 'ã',
        r'ÃÆ’Ã†â€™Ãâ€šÂÂª': 'ê',
        r'ÃÆ’Ã†â€™Ãâ€šÂÂ§': 'ç',
        r'ÃÆ’Ã†â€™Ãâ€šÂÂ³': 'ó',
        r'ÃÆ’Ã†â€™Ãâ€šÂÂ­': 'í',
        r'ÃÆ’Ã†â€™Ãâ€šÂÂº': 'ú',
        r'ÃÆ’Ã†â€™Ãâ€šÂÂ©': 'é',
        r'ÃÆ’Ã†â€™Ãâ€šÂÂ´': 'ô',
        r'ÃÆ’Ã†â€™Ãâ€šÂÂ ': 'à',
        r'ÃÆ’ÂÂ§ÃÆ’ÂÂ£': 'çã',
        r'ÃÆ’ÂÂ§': 'ç',
        r'ÃÆ’ÂÂ£': 'ã',
        r'ÃÆ’ÂÂ¡': 'á',
        r'Ãâ€šÂÂ': '', # Lixo residual
        r'Ã†â€™': '',   # Lixo residual
        r'ÃÆ’': '',     # Lixo residual
    }
    
    # Rodar as substituições mais complexas primeiro
    for pattern, replacement in patterns.items():
        content = re.sub(pattern, replacement, content)
    
    # Limpeza final de caracteres simples se sobrarem
    simple_fixes = {
        'Ã¡': 'á', 'Ã£': 'ã', 'Ãª': 'ê', 'Ã§': 'ç', 'Ã³': 'ó',
        'Ã­': 'í', 'Ãº': 'ú', 'Ã©': 'é', 'Ã´': 'ô'
    }
    for old, new in simple_fixes.items():
        content = content.replace(old, new)
        
    return content

def process_file(path):
    try:
        with open(path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        cleaned = deep_clean(content)
        
        if cleaned != content:
            print(f"Limpeza profunda: {path}")
            with open(path, 'w', encoding='utf-8') as f:
                f.write(cleaned)
    except Exception as e:
        print(f"Erro em {path}: {e}")

if __name__ == "__main__":
    dir_path = r"C:\dev\saveinmed\frontend\src"
    for root, dirs, files in os.walk(dir_path):
        for f in files:
            if f.endswith(('.tsx', '.ts')):
                process_file(os.path.join(root, f))
