#!/usr/bin/env python3
"""
Force Data Refresh
This script forces both applications to refresh their data by clearing caches and restarting.
"""

import os
import subprocess
import time
import requests
from pymongo import MongoClient

def force_data_refresh():
    """Force both applications to refresh their data"""
    print("🔄 Force Data Refresh")
    print("=" * 50)
    
    try:
        # Step 1: Clear browser cache programmatically
        print("🧹 Clearing browser cache...")
        print("   Please manually clear your browser cache:")
        print("   1. Press Ctrl+Shift+Delete")
        print("   2. Select 'All time'")
        print("   3. Clear everything")
        print("   4. Or use Ctrl+Shift+R to hard refresh")
        
        input("   Press Enter when you've cleared the browser cache...")
        
        # Step 2: Check if website is running
        print("\n🌐 Checking website status...")
        try:
            response = requests.get("http://localhost:5008/", timeout=5)
            if response.status_code == 200:
                print("✅ Website is running")
            else:
                print(f"❌ Website returned status {response.status_code}")
        except requests.exceptions.RequestException:
            print("❌ Website is not running")
            print("   Please start the website with: python app.py")
            return
        
        # Step 3: Test the API endpoint directly
        print("\n🧪 Testing API endpoint...")
        try:
            # This will test the endpoint without authentication
            response = requests.get("http://localhost:5008/api/list-codegen-files", timeout=5)
            print(f"   API Status: {response.status_code}")
            if response.status_code == 401:
                print("✅ API is working (requires authentication)")
            else:
                print(f"⚠️ Unexpected API response: {response.text[:100]}")
        except requests.exceptions.RequestException as e:
            print(f"❌ API test failed: {e}")
        
        # Step 4: Verify database data
        print("\n📊 Verifying database data...")
        mongo_uri = os.getenv('MONGODB_URI')
        mongo_db = os.getenv('MONGODB_DB')
        
        if mongo_uri and mongo_db:
            client = MongoClient(mongo_uri)
            db = client[mongo_db]
            
            user_id = '34d0f132-76ff-4adf-b98a-e8649016e747'
            recordings_count = db.codegen_recordings.count_documents({'userId': user_id})
            test_cases_count = db.test_cases.count_documents({'user_id': user_id})
            scripts_count = db.generated_scripts.count_documents({'user_id': user_id})
            
            print(f"   ✅ Database has {recordings_count} recordings for user {user_id}")
            print(f"   ✅ Database has {test_cases_count} test cases for user {user_id}")
            print(f"   ✅ Database has {scripts_count} scripts for user {user_id}")
            
            client.close()
        
        # Step 5: Instructions for desktop app
        print("\n🖥️ Desktop App Instructions:")
        print("   1. Close the desktop application completely")
        print("   2. Check Task Manager to ensure no Electron processes are running")
        print("   3. Restart the desktop application")
        print("   4. Log out and log back in")
        
        input("   Press Enter when you've restarted the desktop app...")
        
        # Step 6: Final verification
        print("\n✅ Final Steps:")
        print("   1. Both applications should now be restarted")
        print("   2. Browser cache should be cleared")
        print("   3. You should be logged in with the same account on both platforms")
        print("   4. Check if data is now consistent")
        
        print("\n🎯 Expected Result:")
        print("   - Website should show the same recordings as desktop app")
        print("   - Both should show the same 8+ recordings from October 3rd")
        print("   - No more data inconsistency")
        
    except Exception as e:
        print(f"❌ Error: {e}")

if __name__ == "__main__":
    force_data_refresh()


