import json
import urllib.request
import uuid
from wagtail_localize.machine_translators.base import BaseMachineTranslator
from wagtail_localize.strings import StringValue

class AzureTranslator(BaseMachineTranslator):
    display_name = "Azure Translator"

    def translate(self, source_locale, target_locale, strings):
        key = self.options.get("Ocp-Apim-Subscription-Key")
        region = self.options.get("Ocp-Apim-Subscription-Region")
        text_type = self.options.get("text_type", "html")
        
        headers = {
            'Ocp-Apim-Subscription-Key': key,
            'Ocp-Apim-Subscription-Region': region,
            'Content-type': 'application/json',
            'X-ClientTraceId': str(uuid.uuid4())
        }
        
        body = []
        for string in strings:
            # Si pedimos HTML, extraemos el formato rico. Si no, texto plano.
            if text_type == 'html':
                body.append({'Text': string.get_translatable_html()})
            else:
                body.append({'Text': string.data})
                
        params = f"?api-version=3.0&from={source_locale.language_code}&to={target_locale.language_code}&textType={text_type}"
        url = 'https://api.cognitive.microsofttranslator.com/translate' + params
        
        req = urllib.request.Request(url, data=json.dumps(body).encode('utf-8'), headers=headers, method='POST')
        
        try:
            with urllib.request.urlopen(req) as response:
                result = json.loads(response.read().decode('utf-8'))
                translations = {}
                for i, string in enumerate(strings):
                    translated_text = result[i]['translations'][0]['text']
                    
                    # Devolvemos el texto a Wagtail manteniendo la estructura HTML
                    if text_type == 'html':
                        translations[string] = StringValue.from_translated_html(translated_text)
                    else:
                        translations[string] = StringValue(translated_text)
                return translations
                
        except Exception as e:
            print("Error conectando con Azure:", e)
            # En caso de error, devolvemos el original para que no se cuelgue el sistema
            return {string: string for string in strings}

    def can_translate(self, source_locale, target_locale):
        return source_locale.language_code != target_locale.language_code