"""
Diagnostico: contactos que SI tienen mensajes, pero NINGUNO de campaña.
Muestra sus mensajes (content) para revisar por que no hicieron match.
"""
import os
import psycopg2
from dotenv import load_dotenv
import data_manager_v2 as dm   # reutiliza las frases de campaña

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")

FRASES = [c[0] for c in dm._campanias_supabase()]
likes = " OR ".join(["m.content LIKE %s"] * len(FRASES))
params = [f"%{fr}%" for fr in FRASES]

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

# Buscar contactos con >=1 mensaje pero 0 de campaña (traemos algunos pocos)
sql = f"""
SELECT c.id, c.phone_number, c.created_at,
       COUNT(m.id) AS total_msjes,
       SUM(CASE WHEN ({likes}) THEN 1 ELSE 0 END) AS msjes_campania
FROM contacts c
JOIN conversations cv ON cv.contact_id = c.id
JOIN messages m ON m.conversation_id = cv.id AND m.sender_type = 'Contact'
GROUP BY c.id, c.phone_number, c.created_at
HAVING COUNT(m.id) >= 1 AND SUM(CASE WHEN ({likes}) THEN 1 ELSE 0 END) = 0
ORDER BY c.created_at DESC
LIMIT 5
"""
cur.execute(sql, params + params)
contactos = cur.fetchall()

for cid, ph, creado, tot, camp in contactos:
    print("=" * 80)
    print(f"CONTACTO id={cid}  tel={ph}  creado={creado}  #msjes={tot}  campaña={camp}")
    # Mostrar sus mensajes (content) del contacto
    cur.execute("""
        SELECT m.created_at, LEFT(m.content, 90)
        FROM messages m
        JOIN conversations cv ON m.conversation_id = cv.id
        WHERE cv.contact_id = %s AND m.sender_type = 'Contact'
        ORDER BY m.created_at ASC
        LIMIT 10
    """, (cid,))
    for fecha, txt in cur.fetchall():
        print(f"   [{fecha}]  {txt!r}")

conn.close()
