import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def generar_html_email(peticion, api_datos_empresa_completo):
    """
    Genera el HTML del email con los datos de la petición
    """
    # Leer plantilla de email
    basedir = os.path.abspath(os.path.dirname(__file__))
    template_path = os.path.join(basedir, 'templates', 'email.html')
    with open(template_path, 'r', encoding='utf-8') as f:
        template = f.read()
    
    # Valores por defecto
    variables = {
        'logo': '',
        'nombre_lote': peticion.codigo_lote or '',
        'foto_lote': '',
        'elementos_lote': peticion.observaciones or '',
        'nombre_entrega': peticion.empleado or '',
        'direccion_entrega': peticion.direccion or '',
        'contacto': peticion.telefono or '',
        'email_empleado': peticion.email or '',
        'observaciones': peticion.observaciones or ''
    }
    
    # Intentar obtener datos de la API si tenemos empresa
    if peticion.empresa:
        data = api_datos_empresa_completo(
            peticion.empresa,
            peticion.identificador_cliente,
            None
        )
        
        if data and 'plataforma' in data:
            plataforma = data['plataforma']
            
            if plataforma.get('logo'):
                variables['logo'] = plataforma['logo']
            
            if peticion.codigo_lote and 'lotes' in plataforma:
                codigo_buscar = peticion.codigo_lote.replace('_', ' ')
                for lote in plataforma['lotes']:
                    if lote.get('codigo_lote') == codigo_buscar:
                        variables['nombre_lote'] = lote.get('name', variables['nombre_lote'])
                        variables['foto_lote'] = lote.get('imagen_miniatura', variables['foto_lote'])
                        variables['elementos_lote'] = lote.get('detalles_lote', variables['elementos_lote'])
                        break
            
            if peticion.direccion:
                variables['direccion_entrega'] = peticion.direccion.replace('España ', '')
    
    # Reemplazar variables en la plantilla
    for key, value in variables.items():
        template = template.replace('{{ ' + key + ' }}', str(value or ''))
    
    return template

def enviar_email_smtp(destinatario, asunto, html_content):
    """
    Envía un email usando SMTP de Gmail
    """
    try:
        msg = MIMEMultipart('alternative')
        msg['Subject'] = asunto
        msg['From'] = 'LOTIFY S.L. <hola@lotify.es>'
        msg['To'] = destinatario
        msg['Reply-To'] = 'hola@lotify.es'
        
        part = MIMEText(html_content, 'html', 'utf-8')
        msg.attach(part)
        
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login('equipo@lotify.es', 'xvmqyburkijlpmuf')
        server.send_message(msg)
        server.quit()
        
        return True, None
    except Exception as e:
        return False, str(e)
