#!/usr/bin/env python3
"""
Test Desktop App MongoDB Connection
This script tests if the desktop app can connect to MongoDB and save recordings.
"""

import os
from pymongo import MongoClient
from datetime import datetime

def test_desktop_mongo_connection():
    """Test if desktop app can connect to MongoDB"""
    print("🔍 Testing Desktop App MongoDB Connection")
    print("=" * 50)
    
    try:
        mongo_uri = os.getenv('MONGODB_URI')
        mongo_db = os.getenv('MONGODB_DB')
        
        if not mongo_uri or not mongo_db:
            print("❌ MongoDB configuration not found")
            return
            
        client = MongoClient(mongo_uri)
        db = client[mongo_db]
        
        # Test connection
        client.server_info()
        print("✅ MongoDB connection successful")
        
        # Check if there are any recent recordings from today
        today = datetime.now().strftime('%Y-%m-%d')
        today_recordings = list(db.codegen_recordings.find({
            'name': {'$regex': f'2025-10-06'}
        }))
        
        print(f"\n📅 Recordings from today ({today}):")
        if today_recordings:
            for rec in today_recordings:
                name = rec.get('name', 'Unknown')
                user_id = rec.get('userId') or rec.get('currentJWTUserId') or rec.get('user_id')
                date = rec.get('date', 'Unknown')
                print(f"   {name} - User: {user_id} - Date: {date}")
        else:
            print("   No recordings from today found")
        
        # Test inserting a test recording
        print(f"\n🧪 Testing recording insertion...")
        test_recording = {
            'name': 'test-desktop-connection.spec.js',
            'original_filename': 'test-desktop-connection.spec.js',
            'path': '/test/path.spec.js',
            'date': datetime.now().isoformat(),
            'content': '// Test recording content',
            'userId': '3468924c-fa4f-4d21-90b5-09f1602c57f0',
            'user_id': '3468924c-fa4f-4d21-90b5-09f1602c57f0',
            'currentJWTUserId': '3468924c-fa4f-4d21-90b5-09f1602c57f0',
            'sessionId': 'test-session-123'
        }
        
        result = db.codegen_recordings.insert_one(test_recording)
        print(f"✅ Test recording inserted with ID: {result.inserted_id}")
        
        # Verify the insertion
        inserted_doc = db.codegen_recordings.find_one({'_id': result.inserted_id})
        if inserted_doc:
            print(f"✅ Verification successful: {inserted_doc.get('name')}")
        else:
            print("❌ Verification failed: document not found")
        
        # Clean up test recording
        db.codegen_recordings.delete_one({'_id': result.inserted_id})
        print("🧹 Test recording cleaned up")
        
        client.close()
        
    except Exception as e:
        print(f"❌ Error: {e}")

if __name__ == "__main__":
    test_desktop_mongo_connection()
