#!/usr/bin/env python3
# Fix UTF-8 double-encoding corruption in sample_selector.py

import os

file_path = '/mnt/c/ProgramData/Ableton/Live 12 Suite/Resources/MIDI Remote Scripts/AbletonMCP_AI/AbletonMCP_AI/MCP_Server/sample_selector.py'

with open(file_path, 'r', encoding='utf-8') as f:
    content = f.read()

# Replace corrupted UTF-8 sequences with proper Spanish characters
# These are double-encoded characters: UTF-8 -> Latin1 -> UTF-8
corrupted_to_clean = {
    'Selecci': 'Selección',
    'gnero': 'género',
    'Matching armnico': 'Matching armónico',
    'Creaci': 'Creación',
    'batera': 'batería',
    'automtico': 'automático',
    'mltiples': 'múltiples',
    'Validaci': 'Validación',
    'Penalizaci': 'Penalización',
    'Detecci': 'Detección',
    'clculos': 'cálculos',
    'aceleraci': 'aceleración',
}

for corrupted, clean in corrupted_to_clean.items():
    # Find the corrupted pattern and fix it
    # Look for patterns like "SelecciÃƒÆ'Ã‚Â³n" -> "Selección"
    content = content.replace(corrupted + 'ÃƒÆ'Ã‚Â³', clean)
    content = content.replace(corrupted + 'ÃƒÆ'Ã‚Â©', clean.replace('ón', 'én') if 'ón' in clean else clean.replace('ción', 'ción'))
    content = content.replace(corrupted + 'ÃƒÆ'Ã‚Â­', clean.replace('ón', 'ín') if 'ón' in clean else clean)
    content = content.replace(corrupted + 'ÃƒÆ'Ã‚Â¡', clean.replace('ón', 'án') if 'ón' in clean else clean)
    content = content.replace(corrupted + 'ÃƒÆ'Ã‚Âº', clean.replace('ón', 'ún') if 'ón' in clean else clean)

# Additional direct replacements for common patterns
direct_replacements = [
    ('ÃƒÆ'Ã‚Â³', 'ó'),
    ('ÃƒÆ'Ã‚Â©', 'é'),
    ('ÃƒÆ'Ã‚Â­', 'í'),
    ('ÃƒÆ'Ã‚Â¡', 'á'),
    ('ÃƒÆ'Ã‚Âº', 'ú'),
    ('ÃƒÆ'Ã‚Â', ''),
]

for wrong, right in direct_replacements:
    content = content.replace(wrong, right)

with open(file_path, 'w', encoding='utf-8') as f:
    f.write(content)

print('UTF-8 corruption fixed successfully')