"""
Diagnostico: para una lista de telefonos, muestra la fecha de creacion del
contacto (contacts.created_at) y la fecha del primer/ultimo mensaje.
"""
import os
import psycopg2
from dotenv import load_dotenv

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", "972132288"]

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} {'phone_number':16} {'CONTACTO_CREADO':22} {'1ER_MSJE':22} {'ULT_MSJE':22}")
print("-" * 100)

for tel in TELEFONOS:
    cur.execute("""
        SELECT c.phone_number, c.created_at,
               MIN(m.created_at) AS primer_msje,
               MAX(m.created_at) AS ultimo_msje
        FROM contacts c
        LEFT JOIN conversations cv ON cv.contact_id = c.id
        LEFT JOIN messages m ON m.conversation_id = cv.id
        WHERE REPLACE(REPLACE(c.phone_number, '+51',''), '+','') LIKE %s
        GROUP BY c.phone_number, c.created_at
        ORDER BY c.created_at ASC
    """, (f"%{tel}",))
    rows = cur.fetchall()
    if not rows:
        print(f"{tel:14} {'(no encontrado)':16}")
        continue
    for ph, creado, primer, ultimo in rows:
        print(f"{tel:14} {str(ph):16} {str(creado):22} {str(primer):22} {str(ultimo):22}")

conn.close()
