# diag_content.py  —  Revisa que valores toma content_attributes (para replicar ISBLANK).
# Ejecutar dentro de backend/:  python diag_content.py
from data_manager_v2 import DataManager

dm = DataManager()
conn = dm.pg_conn()
cur = conn.cursor()

# Distribucion de content_attributes en los mensajes de plantilla
sql = """
SELECT
    CASE
        WHEN m.content_attributes IS NULL THEN '(NULL)'
        WHEN m.content_attributes::text = '{}' THEN '(vacio {})'
        WHEN m.content_attributes::text = 'null' THEN "(texto 'null')"
        ELSE 'CON DATOS'
    END AS tipo,
    COUNT(*) AS n
FROM messages m
WHERE m.sender_type = 'User'
  AND m.additional_attributes -> 'template_params' ->> 'name' IS NOT NULL
GROUP BY 1
ORDER BY 2 DESC
"""
cur.execute(sql)
print("== content_attributes en mensajes de plantilla ==")
for tipo, n in cur.fetchall():
    print(f"   {tipo:16} {n}")

# Muestra 3 ejemplos de cada tipo con datos
print("\n== ejemplos de content_attributes CON DATOS (primeros 3) ==")
cur.execute("""
SELECT m.additional_attributes -> 'template_params' ->> 'name', m.content_attributes::text
FROM messages m
WHERE m.sender_type='User'
  AND m.additional_attributes -> 'template_params' ->> 'name' IS NOT NULL
  AND m.content_attributes IS NOT NULL
  AND m.content_attributes::text NOT IN ('{}','null')
LIMIT 3
""")
for nombre, ca in cur.fetchall():
    print(f"   {nombre}: {ca[:120]}")
conn.close()
