from langdetect import detect
from langdetect.lang_detect_exception import LangDetectException
from googletrans import Translator
from deep_translator import GoogleTranslator
import pandas as pd
import re
import langid

class Translation:
    def __init__(self, text, target_lang):
        self.text = text
    
    def translatef(text, target_lang):
        try:
            print(text, target_lang)
            if target_lang=='zh':
                target_lang=='zh-CN'
            translator = GoogleTranslator(source='auto', target=target_lang)
            translated = translator.translate(text)
            print(translated)
            #return translated.text
            return translated
        except Exception as e:
            return f"Error during translation: {str(e)}"

    @staticmethod   

    def detect_language(text):
        try:
            lang, confidence = langid.classify(text)
            print(text)
            #print(lang)
            return lang  # Devuelve el código ISO del idioma
        except Exception as e:
            return f"ERROR: {str(e)}"


def search_error_in_excel(text, excel_path="errors.xlsx"):
    """
    Busca información en un archivo Excel según palabras clave y muestra texto, enlace o imagen.
    
    :param text: Texto proporcionado por el usuario.
    :param excel_path: Ruta al archivo Excel.
    :return: Texto, enlace o imagen según la consulta del usuario.
    """
    # Detectar palabras clave "error" o "errores" y un número
    match = re.search(r"(?:error|errores)\s*(\d+)", text, re.IGNORECASE)
    if not match:
        return "No se encontró ningún código de error en el texto.", None

    error_code = int(match.group(1))

    # Detectar tipo de consulta: "texto", "vídeo", o "foto"
    is_text = "protocolo" in text.lower() or "registro" in text.lower() or "log" in text.lower()
    is_video = "video" in text.lower()
    is_photo = "foto" in text.lower() or "imagen" in text.lower()

    if not (is_text or is_video or is_photo):
        return "Debe especificar si desea 'texto', 'video' o 'foto' en su consulta.", None

    # Cargar el archivo Excel
    try:
        df = pd.read_excel(excel_path)
    except FileNotFoundError:
        return f"El archivo {excel_path} no fue encontrado.", None
    except Exception as e:
        return f"Error al abrir el archivo Excel: {str(e)}", None

    # Verificar si el código de error existe en las columnas
    if error_code not in df.columns:
        return f"No se encontró información para el código de error {error_code}.", None

    # Devolver información basada en el tipo de consulta
    try:
        if is_text:
            return str(df[error_code].dropna().iloc[0]),  "protocolo"  # Primera fila
        elif is_video:
            return str(df[error_code].dropna().iloc[1]),  "video"  # Segunda fila
        elif is_photo:
            image_path = str(df[error_code].dropna().iloc[2])  # Tercera fila
            return image_path, "foto"  # Devolver la ruta de la imagen
    except IndexError:
        return f"La información para el código de error {error_code} está incompleta en el archivo Excel.", None