"""
Diagnostico: para una lista de telefonos, muestra su cached_label_list crudo
y la Ultima_Etiqueta calculada (misma logica del DAX / leads_logic).
"""
import os
import psycopg2
from dotenv import load_dotenv
import leads_logic as L   # reutiliza ultima_etiqueta() ya existente

load_dotenv()

PG_HOST = os.getenv("PG_HOST")
PG_DB   = os.getenv("PG_DATABASE") or os.getenv("PG_DB")
PG_USER = os.getenv("PG_USER")
PG_PASS = os.getenv("PG_PASSWORD") or os.getenv("PG_PASS")
PG_PORT = os.getenv("PG_PORT", "5432")

TELEFONOS = """
948400152 953932854 959735396 971615688 972132288 976595677
56953794663 56961258851 56962820196 59173326356 59175648709
900079313 900153292 900610393 900779778 902490667 902671008
902968272 907312317 907818325
""".split()

conn = psycopg2.connect(host=PG_HOST, dbname=PG_DB, user=PG_USER,
                        password=PG_PASS, port=PG_PORT, connect_timeout=30)
cur = conn.cursor()

print(f"{'TELEFONO':14} {'ULTIMA_ETIQUETA':22} | cached_label_list (crudo)")
print("-" * 90)

for tel in TELEFONOS:
    # busca cualquier variante del numero (con o sin 51 adelante)
    cur.execute("""
        SELECT cv.cached_label_list, m.created_at
        FROM messages m
        JOIN conversations cv ON m.conversation_id = cv.id
        JOIN contacts c ON cv.contact_id = c.id
        WHERE REPLACE(REPLACE(c.phone_number, '+51',''), '+','') LIKE %s
        ORDER BY m.created_at DESC
        LIMIT 1
    """, (f"%{tel}",))
    row = cur.fetchone()
    if row is None:
        print(f"{tel:14} {'(no encontrado)':22} |")
        continue
    crudo = row[0]
    ult = L.ultima_etiqueta(crudo)
    print(f"{tel:14} {ult:22} | {crudo}")

conn.close()
