import sys

class ForceUTF8Middleware:
    """Force UTF-8 encoding for all requests and responses"""
    
    def __init__(self, get_response):
        self.get_response = get_response
    
    def __call__(self, request):
        # Traiter la requête
        if request.method == 'POST':
            # S'assurer que toutes les données POST sont en UTF-8
            if hasattr(request, 'POST') and request.POST:
                mutable = request.POST.copy()
                for key, value in request.POST.items():
                    if isinstance(value, str):
                        try:
                            # Nettoyer et recoder en UTF-8
                            mutable[key] = value.encode('latin1').decode('utf-8')
                        except (UnicodeEncodeError, UnicodeDecodeError):
                            mutable[key] = value
                request.POST = mutable
        
        response = self.get_response(request)
        
        # Ajouter l'en-tête UTF-8
        response['Content-Type'] = 'text/html; charset=utf-8'
        return response