import mysql.connector
from datetime import datetime
from db_utils import get_db, normalizephone

def importar_whatsapp_logs(job_id, proyecto):
    print("---------------------------------------------")
    print(f"Importando logs de WhatsApp - {proyecto} - {job_id}")
    print("---------------------------------------------")
    db = get_db()
    cursor = db.cursor(dictionary=True)

    cursor.execute("SELECT * FROM nsjobs WHERE id = %s", (job_id,))
    jobdata = cursor.fetchone()


    cursor.execute("""
        SELECT * FROM nslog
        WHERE accion IN ('Contesto WP', 'WP message')
        AND detalles != '' and mail not like '%@g.us' and mail not like '%@broadcast'  
        AND detalles IS NOT NULL
        and ((accion = 'Contesto WP'  and url = %s) or (accion = 'WP message'  and mail  = %s))
        and ((accion = 'Contesto WP'  and mail in (select replace(destino, '+', '') from nsjobitems where job = %s)) 
            or (accion = 'WP message'  and target in (select replace(destino, '+', '') from nsjobitems where job = %s)))
        AND LENGTH(detalles) > 0
        and (status is null or status != 1)
        ORDER BY id ASC
    """, (jobdata["remitente"],jobdata["remitente"], job_id, job_id))    
    logs = cursor.fetchall()

    for log in logs:
        if log["accion"] == "Contesto WP":
            direction = "incoming"
            contact_phone = log["mail"]
            user_phone = log["url"]
        else:
            direction = "outgoing"
            contact_phone = log["target"]
            user_phone = log["mail"]
        
        contact_phone = normalizephone(contact_phone)



        content = log["detalles"]
        timestamp = log["created"] if "created" in log and log["created"] else datetime.now()
        print(f"📱 {timestamp} {direction} - {contact_phone} ({user_phone}) : {content}")

        # Buscar o crear usuario
        cursor.execute("SELECT id FROM user_account WHERE whatsapp_number = %s", (user_phone,))
        row = cursor.fetchone()
        if not row:
            print(f"⚠️ Usuario no encontrado: {user_phone}")
            continue
        user_id = row["id"]
        


        # Buscar contacto
        cursor.execute("SELECT id FROM contact WHERE phone = %s ", (contact_phone,))
        row = cursor.fetchone()
        if row:
            contact_id = row["id"]
        else:
            cursor.execute("""
                INSERT INTO contact (name, phone, source, is_lead, proyecto, campana, alta)
                VALUES (%s, %s, 'Whatsapp', 1, %s, %s, NOW())
            """, (contact_phone, contact_phone, proyecto, jobdata['titulo']))
            db.commit()
            contact_id = cursor.lastrowid

        # Evitar duplicados por contenido y timestamp
        cursor.execute("""
            SELECT id FROM message
            WHERE contact_id = %s AND user_id = %s AND content = %s AND timestamp = %s
        """, (contact_id, user_id, content, timestamp))
        if cursor.fetchone():
            print(f"📌 Mensaje duplicado: contacto {contact_phone} a las {timestamp}")
            continue

        # Insertar mensaje
        cursor.execute("""
            INSERT INTO message (
                user_id, contact_id, direction, content, timestamp,
                channel, subject, address, addressname
            )
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
        """, (
            user_id, contact_id, direction, content, timestamp,
            'WhatsApp', 'Mensaje de WhatsApp', contact_phone, contact_phone
        ))
        db.commit()

        cursor.execute("update nslog set status = 1 where id = %s", (log["id"],))
        db.commit()

        print(f"✅ Mensaje guardado: {direction} {contact_phone} ({user_phone})")

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--job", required=True, type=int, help="ID del job para usar como campaña")
    parser.add_argument("--proyecto", required=True, help="Nombre del proyecto asociado")
    args = parser.parse_args()

    importar_whatsapp_logs(args.job, args.proyecto)