"""
Debug script to check if Meet signals are being recorded and stored.
Run this while or after recording a Google Meet.
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from backend.db.chroma import get_all_signals, get_group_ids
from backend.config import MEET_DEFAULT_GROUP_ID
import json

print("=" * 60)
print("ThirdEye Meet Recording Diagnostic")
print("=" * 60)

# Check all groups
print("\n1. All ChromaDB groups:")
all_groups = get_group_ids()
print(f"   Found {len(all_groups)} groups: {all_groups}")

# Check default meet group
print(f"\n2. Default meet group: {MEET_DEFAULT_GROUP_ID}")
try:
    meet_signals = get_all_signals(MEET_DEFAULT_GROUP_ID)
    print(f"   Found {len(meet_signals)} signals")
    
    if meet_signals:
        # Count by type
        types = {}
        meetings = {}
        for sig in meet_signals:
            meta = sig.get("metadata", {})
            sig_type = meta.get("type", "unknown")
            meet_id = meta.get("meeting_id", "unknown")
            
            types[sig_type] = types.get(sig_type, 0) + 1
            if meet_id not in meetings:
                meetings[meet_id] = 0
            meetings[meet_id] += 1
        
        print("\n   Signal types:")
        for t, count in types.items():
            print(f"     - {t}: {count}")
        
        print("\n   Meetings recorded:")
        for mid, count in meetings.items():
            print(f"     - {mid}: {count} signals")
        
        # Show first few signals
        print("\n   First 3 signals (metadata only):")
        for i, sig in enumerate(meet_signals[:3]):
            print(f"\n   Signal {i+1}:")
            meta = sig.get("metadata", {})
            for key in ["type", "meeting_id", "timestamp", "lens"]:
                print(f"     {key}: {meta.get(key, 'N/A')}")
            doc = sig.get("document", "")
            print(f"     document: {doc[:100]}...")
    else:
        print("   ⚠️ No signals found in meet_sessions group")
        print("   This means either:")
        print("     - Extension hasn't recorded anything yet")
        print("     - Backend isn't running")
        print("     - Signals are being stored in a different group")
        
except Exception as e:
    print(f"   ❌ Error: {e}")

# Check all groups for meet signals
print("\n3. Checking ALL groups for meet-related signals:")
for group in all_groups:
    try:
        signals = get_all_signals(group)
        meet_lens = [s for s in signals if s.get("metadata", {}).get("lens") == "meet"]
        if meet_lens:
            print(f"   - {group}: {len(meet_lens)} meet signals")
            meetings_in_group = set(s.get("metadata", {}).get("meeting_id") for s in meet_lens)
            print(f"     Meetings: {list(meetings_in_group)}")
    except Exception as e:
        print(f"   - {group}: Error - {e}")

print("\n" + "=" * 60)
print("Diagnostic complete!")
print("=" * 60)
