import re
import unicodedata

from helpers.db import ejecutar_sp


def limpiar_razon_social(razon_social: str) -> str:
    if not razon_social:
        return ""

    # Normalizar acentos
    texto = unicodedata.normalize("NFKD", razon_social)
    texto = "".join(c for c in texto if not unicodedata.combining(c))

    # Pasar a mayúsculas
    texto = texto.upper()

    # Quitar tipo societario
    patrones = [
        r'\bS\.?\s*R\.?\s*L\.?\b',
        r'\bS\.?\s*A\.?\b',
        r'\bS\.?\s*A\.?\s*S\.?\b',
        r'\bSAS\b',
        r'\bSRL\b',
        r'\bSA\b'
    ]

    for p in patrones:
        texto = re.sub(p, '', texto)

    # Limpiar basura
    texto = re.sub(r'[^A-Z0-9\s]', ' ', texto)
    texto = re.sub(r'\s+', ' ', texto).strip()

    return texto

def buscar_cuit(razon_social: str, conn=None) -> str | None:
    razon_limpia = limpiar_razon_social(razon_social)    
    
    try:
        result = ejecutar_sp(
            'buscador_paises_padron',
            ['buscador', 'J', razon_limpia, 'AR', None, None, None, None, None, None, None, None],
            conn,
        )
        
        # El SP devuelve el CUIT en la 4ª columna cuando encuentra exactamente un resultado
        if result and len(result) == 1:
            return list(result[0].values())[3]
        return None
    except Exception as e:
        print(f"Error buscando CUIT: {e}")
        return None


def buscar_razon_social(razon_social, country_code='AR'):
    """Alias de buscar_cuit() para compatibilidad."""
    return buscar_cuit(razon_social)
