#!/usr/bin/env python3
"""
Force Django to reload by clearing cache and restarting
"""

import os
import shutil
import glob

print("🔄 Force reloading Django...")
print("=" * 60)

# Step 1: Remove Python bytecode cache
print("\n1️⃣ Clearing Python bytecode cache...")
removed_count = 0

for root, dirs, files in os.walk('.'):
    # Remove __pycache__ directories
    if '__pycache__' in dirs:
        pycache_dir = os.path.join(root, '__pycache__')
        try:
            shutil.rmtree(pycache_dir)
            removed_count += 1
            print(f"   Removed: {pycache_dir}")
        except Exception as e:
            print(f"   Warning: Could not remove {pycache_dir}: {e}")
    
    # Remove .pyc files
    for file in files:
        if file.endswith('.pyc'):
            pyc_file = os.path.join(root, file)
            try:
                os.remove(pyc_file)
                print(f"   Removed: {pyc_file}")
            except Exception as e:
                print(f"   Warning: Could not remove {pyc_file}: {e}")

print(f"✅ Removed {removed_count} __pycache__ directories")

# Step 2: Restart Django multiple times to be sure
print("\n2️⃣ Restarting Django (multiple attempts)...")

os.makedirs('tmp', exist_ok=True)

for i in range(3):
    try:
        # Touch restart.txt
        with open('tmp/restart.txt', 'w') as f:
            f.write(f'restart {i+1}\n')
        
        # Also try restart.py if it exists
        if os.path.exists('tmp/restart.py'):
            os.utime('tmp/restart.py', None)
        
        print(f"   Restart attempt {i+1}/3")
    except Exception as e:
        print(f"   Warning on attempt {i+1}: {e}")

print("✅ Django restart triggered")

# Step 3: Verify the file timestamp
print("\n3️⃣ Verifying file timestamps...")
view_file = 'loans/views.py'
if os.path.exists(view_file):
    mtime = os.path.getmtime(view_file)
    from datetime import datetime
    mod_time = datetime.fromtimestamp(mtime)
    print(f"   {view_file} last modified: {mod_time}")
else:
    print(f"   ❌ {view_file} not found!")

print("\n" + "=" * 60)
print("✅ FORCE RELOAD COMPLETE")
print("=" * 60)
print("\nNext steps:")
print("1. Wait 30 seconds for Django to fully reload")
print("2. Open a NEW private/incognito browser window")
print("3. Login again: https://grazuri.uzuriapps.xyz/")
print("4. Try '+ New Loan Application' button")
print("\nIf STILL not working, the issue is elsewhere (not code/cache)")
print("=" * 60)
