import requests
import urllib.parse
import time
import mysql.connector
from datetime import datetime, timedelta
import pytz

DB_CONFIG = {
    'host': 'cpanel.fullmecanicaeirl.com',  # o el host que te indique tu proveedor, normalmente 'localhost'
    'port': 3306,
    'user': 'fullmeca_jaccespedes',
    'password': '9{[3O&i4a74o',
    'database': 'fullmeca_automotrizbd',
    'charset': 'utf8mb4'
}

def get_inspection_alerts():
    """Obtiene inspecciones que coinciden con la fecha, hora y minutos actuales en Perú"""
    lima_tz = pytz.timezone('America/Lima')
    now_lima = datetime.now(lima_tz)
    current_time_str = now_lima.strftime('%Y-%m-%d %H:%M')
    print("Fecha y hora actual del sistema (Perú):", current_time_str)
    query = f"""
    SELECT 
        inspections.id,
        inspections.date,
        inspections.reason,
        inspections.mileage,
        inspections.auto,
        inspections.customer,
        vehicles.model,
        vehicles.license_plate,
        customers.name AS customer_name,
        customers.razon_social AS customer_razon_social,
        companies.razon_social AS company_razon_social
    FROM inspections
    LEFT JOIN vehicles ON inspections.id_vehicle = vehicles.id
    LEFT JOIN services ON vehicles.id_service = services.id
    LEFT JOIN customers ON services.id_customer = customers.id
    LEFT JOIN companies ON customers.id_company = companies.id
    WHERE DATE_FORMAT(inspections.date, '%Y-%m-%d %H:%i') = '{current_time_str}'
    """
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor(dictionary=True)
        cursor.execute(query)
        alerts = cursor.fetchall()
        cursor.close()
        conn.close()
        return alerts
    except Exception as e:
        print(f"Error DB: {e}")
        return []

def get_whatsapp_numbers():
    """Obtiene todos los números de WhatsApp registrados"""
    query = """
    SELECT phone_number, api_key
    FROM numbers 
    WHERE phone_number IS NOT NULL AND api_key IS NOT NULL
    """
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor(dictionary=True)
        cursor.execute(query)
        numbers = cursor.fetchall()
        cursor.close()
        conn.close()
        return numbers
    except Exception as e:
        print(f"Error obteniendo números: {e}")
        return []

def build_message(alert):
    fecha = alert['date'].strftime('%d/%m/%Y %H:%M') if isinstance(alert['date'], datetime) else str(alert['date'])
    motivo = alert['reason'] or ''
    # Si no hay modelo y placa, usar vehicle
    if alert.get('model') or alert.get('license_plate'):
        modelo = alert.get('model') or ''
        placa = alert.get('license_plate') or ''
        vehiculo_str = f"{modelo} - Placa: {placa}"
    else:
        vehiculo_str = alert.get('auto') or ''
    kilometraje = alert.get('mileage') or ''
    # Si no existe cliente, usar customer
    cliente = alert.get('customer_razon_social') or alert.get('customer_name') or alert.get('customer') or ''
    empresa = alert.get('company_razon_social') or ''
    mensaje = (
        f"🚗 *Recordatorio de Inspección* 🚗\n\n"
        f"Fecha y hora: {fecha}\n"
        f"Motivo: {motivo}\n"
        f"Vehículo: {vehiculo_str}\n"
        f"Kilometraje: {kilometraje}\n"
        f"Cliente: {cliente}\n"
    )
    if empresa:
        mensaje += f"Empresa: {empresa}\n"
    mensaje += "\n¡Contáctanos para más información!\nEquipo Automotriz"
    return mensaje

def send_whatsapp(phone, api_key, message):
    clean_phone = ''.join(filter(str.isdigit, phone))
    url = f"https://api.callmebot.com/whatsapp.php?phone={clean_phone}&text={urllib.parse.quote(message)}&apikey={api_key}"
    try:
        r = requests.get(url, timeout=30)
        return r.status_code == 200
    except Exception as e:
        print(f"Error enviando a {phone}: {e}")
        return False

def send_alerts():
    """Envía alertas de inspección solo si fecha, hora y minutos coinciden exactamente"""
    alerts = get_inspection_alerts()
    numbers = get_whatsapp_numbers()

    print("Datos de inspecciones:", alerts)
    print("Números de WhatsApp:", numbers)
    
    if not alerts:
        print("No hay inspecciones programadas para este momento exacto.")
        return
    
    if not numbers:
        print("No hay números de WhatsApp registrados.")
        return
    
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M')
    print(f"Hora actual: {current_time}")
    print(f"Encontradas {len(alerts)} inspecciones para enviar a {len(numbers)} números.")
    
    # Construir mensaje con todas las inspecciones
    if len(alerts) == 1:
        message = build_message(alerts[0])
    else:
        # Si hay múltiples inspecciones, crear un mensaje resumido
        message = f"🚗 *Recordatorio de Inspecciones* 🚗\n\n"
        message += f"Tienes {len(alerts)} inspecciones programadas para este momento:\n\n"
        
        for i, alert in enumerate(alerts[:5], 1):  # Mostrar máximo 5 inspecciones
            fecha = alert['date'].strftime('%d/%m/%Y %H:%M') if isinstance(alert['date'], datetime) else str(alert['date'])
            modelo = alert['model'] or ''
            placa = alert['license_plate'] or ''
            message += f"{i}. {modelo} ({placa}) - {fecha}\n"
        
        if len(alerts) > 5:
            message += f"... y {len(alerts) - 5} más.\n"
        
        message += "\n¡Contáctanos para más información!\nEquipo Automotriz"
    
    # Enviar el mensaje a todos los números registrados
    for number in numbers:
        ok = send_whatsapp(number['phone_number'], number['api_key'], message)
        status = 'Enviado' if ok else 'Fallo'
        print(f"{number['phone_number']}: {status}")
        time.sleep(2)  # Pausa entre envíos

if __name__ == "__main__":
    while True:
        print("Enviando alertas de inspección...")
        send_alerts()
        print("Proceso completado. Esperando 60 segundos para el próximo envío...")
        time.sleep(60)  # Espera 60 segundos antes de volver a enviar
