"""Check DB data for a specific developer."""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from utils.connection import init, query_df

EMAIL = "ajaysingh07032003@gmail.com"

conn = init()

# 1. Check sessions
print(f"=== DB Check for: {EMAIL} ===\n")

sessions = query_df(conn, """
    SELECT id, source, model, repo_name, cwd, first_seen, org
    FROM sessions
    WHERE user_email = %s
    ORDER BY first_seen
""", (EMAIL,))
print(f"Total sessions: {len(sessions)}")
if len(sessions) > 0:
    print(f"\nSessions by source:")
    print(sessions.groupby("source").size().to_string())
    print(f"\nSessions by model:")
    print(sessions.groupby("model").size().to_string())
    print(f"\nDate range: {sessions['first_seen'].min()} → {sessions['first_seen'].max()}")
    print(f"\nAll sessions:")
    for _, row in sessions.iterrows():
        model = str(row['model']) if row['model'] and str(row['model']) != 'nan' else 'n/a'
        repo = str(row['repo_name']) if row['repo_name'] and str(row['repo_name']) != 'nan' else 'n/a'
        print(f"  {row['first_seen']}  {row['source']:12s}  {model:20s}  {repo}")

# 2. Check messages
messages = query_df(conn, """
    SELECT m.msg_type, COUNT(*) as cnt,
           MIN(m.timestamp) as earliest,
           MAX(m.timestamp) as latest
    FROM messages m
    JOIN sessions s ON s.id = m.session_id
    WHERE s.user_email = %s
    GROUP BY m.msg_type
    ORDER BY cnt DESC
""", (EMAIL,))
print(f"\n=== Messages ===")
if len(messages) > 0:
    for _, row in messages.iterrows():
        print(f"  {row['msg_type']:15s}  {row['cnt']:6d}  ({row['earliest']} → {row['latest']})")
    total = messages['cnt'].sum()
    print(f"  {'TOTAL':15s}  {total:6d}")
else:
    print("  No messages found!")

# 3. Check messages per day
daily = query_df(conn, """
    SELECT DATE(m.timestamp) as day, COUNT(*) as cnt
    FROM messages m
    JOIN sessions s ON s.id = m.session_id
    WHERE s.user_email = %s AND m.timestamp IS NOT NULL
    GROUP BY DATE(m.timestamp)
    ORDER BY day
""", (EMAIL,))
print(f"\n=== Messages per Day ===")
if len(daily) > 0:
    for _, row in daily.iterrows():
        bar = "█" * min(int(row['cnt'] / 10), 50)
        print(f"  {row['day']}  {row['cnt']:5d}  {bar}")
else:
    print("  No daily data!")

# 4. Also check if email appears with different casing or typos
similar = query_df(conn, """
    SELECT DISTINCT user_email
    FROM sessions
    WHERE user_email ILIKE %s
       OR user_email ILIKE %s
""", (f"%ajay%", f"%singh%"))
print(f"\n=== Similar emails in DB ===")
for _, row in similar.iterrows():
    print(f"  {row['user_email']}")

conn.close()
