#!/usr/bin/env python
"""
Force complete server reload - clear all Python caches
"""

import os
import subprocess
from pathlib import Path

print("=" * 60)
print("Forcing Server Reload")
print("=" * 60)
print()

BASE_DIR = Path(__file__).resolve().parent

# Step 1: Clear Python bytecode cache
print("[1/4] Clearing Python bytecode cache...")
try:
    # Find and remove __pycache__ directories
    result = subprocess.run(
        'find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true',
        shell=True,
        cwd=BASE_DIR
    )
    
    # Remove .pyc files
    result = subprocess.run(
        'find . -name "*.pyc" -delete 2>/dev/null || true',
        shell=True,
        cwd=BASE_DIR
    )
    
    print("  ✓ Bytecode cache cleared")
except Exception as e:
    print(f"  ! Warning: {e}")
print()

# Step 2: Touch restart file for Passenger
print("[2/4] Triggering Passenger restart...")
tmp_dir = BASE_DIR / 'tmp'
tmp_dir.mkdir(exist_ok=True)

restart_file = tmp_dir / 'restart.txt'
restart_file.touch()
print(f"  ✓ Created: {restart_file}")

# Also try always_restart.txt
always_restart = tmp_dir / 'always_restart.txt'
always_restart.touch()
print(f"  ✓ Created: {always_restart}")
print()

# Step 3: Check for Python processes
print("[3/4] Checking Python processes...")
try:
    result = subprocess.run(
        'ps aux | grep python | grep -v grep | head -5',
        shell=True,
        capture_output=True,
        text=True
    )
    if result.stdout:
        print("  Active Python processes:")
        for line in result.stdout.strip().split('\n')[:5]:
            print(f"    {line[:80]}")
    else:
        print("  No Python processes found (or ps command unavailable)")
except:
    print("  ! Could not check processes")
print()

# Step 4: Verify files are uploaded
print("[4/4] Verifying updated files...")
files_to_check = [
    'utils/context_processors.py',
    'branch_system/settings.py',
    'accounting/views.py',
    'accounting/models.py',
]

all_ok = True
for file_path in files_to_check:
    full_path = BASE_DIR / file_path
    if full_path.exists():
        # Check modification time
        mtime = full_path.stat().st_mtime
        import time
        age = time.time() - mtime
        age_str = f"{age/60:.1f} minutes ago" if age < 3600 else f"{age/3600:.1f} hours ago"
        print(f"  ✓ {file_path} (modified {age_str})")
    else:
        print(f"  ✗ {file_path} NOT FOUND")
        all_ok = False

print()

if all_ok:
    print("=" * 60)
    print("Reload Complete!")
    print("=" * 60)
    print()
    print("The server should reload in a few seconds.")
    print()
    print("If you still get errors:")
    print("1. Check cPanel Error Log for the actual error")
    print("2. Try restarting through cPanel → Python App")
    print("3. Clear browser cache (Ctrl+Shift+R)")
    print()
    print("Wait 10-30 seconds then try: https://grazuri.uzuriapps.xyz/")
else:
    print("=" * 60)
    print("WARNING: Some files are missing!")
    print("=" * 60)
    print()
    print("Make sure you've uploaded all changed files to production:")
    print("- utils/context_processors.py")
    print("- branch_system/settings.py")
    print()
