#!/usr/bin/env python3
"""
Server troubleshooting script for 403/404 errors
Run this on the server to diagnose Apache/Passenger issues
"""
import os
import sys

print("=" * 70)
print("TROUBLESHOOTING 403/404 ERRORS")
print("=" * 70)
print()

# Check current directory
current_dir = os.getcwd()
print(f"📁 Current directory: {current_dir}")
print()

# Check file permissions
print("📌 File Permissions Check:")
files_to_check = [
    'passenger_wsgi.py',
    '.htaccess',
    'app.py',
    'data/users.json',
    'templates/login.html'
]

for file in files_to_check:
    if os.path.exists(file):
        stat_info = os.stat(file)
        perms = oct(stat_info.st_mode)[-3:]
        print(f"   ✓ {file:<30} Permissions: {perms}")
    else:
        print(f"   ✗ {file:<30} NOT FOUND")
print()

# Check directory permissions
print("📌 Directory Permissions:")
dirs_to_check = ['.', 'templates', 'data', 'static', 'tmp']
for dir_path in dirs_to_check:
    if os.path.exists(dir_path):
        stat_info = os.stat(dir_path)
        perms = oct(stat_info.st_mode)[-3:]
        print(f"   ✓ {dir_path:<30} Permissions: {perms}")
    else:
        print(f"   ⚠️  {dir_path:<30} NOT FOUND (might be OK)")
print()

# Check for tmp/restart.txt
print("📌 Passenger Restart Check:")
if os.path.exists('tmp/restart.txt'):
    from datetime import datetime
    mtime = os.path.getmtime('tmp/restart.txt')
    mtime_str = datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S')
    print(f"   ✓ tmp/restart.txt exists (last modified: {mtime_str})")
else:
    print(f"   ✗ tmp/restart.txt NOT FOUND")
    print(f"   Create it with: mkdir -p tmp && touch tmp/restart.txt")
print()

# Check environment variables
print("📌 Environment Variables:")
print(f"   APPLICATION_ROOT: {os.environ.get('APPLICATION_ROOT', 'NOT SET')}")
print(f"   HOME: {os.environ.get('HOME', 'NOT SET')}")
print(f"   USER: {os.environ.get('USER', 'NOT SET')}")
print()

# Check .htaccess content
print("📌 .htaccess Configuration:")
if os.path.exists('.htaccess'):
    print(f"   ✓ .htaccess exists")
    with open('.htaccess', 'r') as f:
        content = f.read()
        if 'PassengerEnabled' in content:
            print(f"   ✓ PassengerEnabled directive found")
        else:
            print(f"   ✗ PassengerEnabled directive NOT FOUND")
        
        if 'PassengerAppRoot' in content:
            print(f"   ✓ PassengerAppRoot directive found")
            # Extract the path
            for line in content.split('\n'):
                if 'PassengerAppRoot' in line:
                    print(f"      Value: {line.strip()}")
        else:
            print(f"   ✗ PassengerAppRoot NOT FOUND")
        
        if 'PassengerPython' in content:
            print(f"   ✓ PassengerPython directive found")
            for line in content.split('\n'):
                if 'PassengerPython' in line:
                    print(f"      Value: {line.strip()}")
                    python_path = line.split()[-1] if len(line.split()) > 1 else ''
                    if os.path.exists(python_path):
                        print(f"      ✓ Python executable exists")
                    else:
                        print(f"      ✗ Python executable NOT FOUND at {python_path}")
else:
    print(f"   ✗ .htaccess NOT FOUND")
print()

# Try importing Flask
print("📌 Flask Import Test:")
try:
    sys.path.insert(0, current_dir)
    from app import app
    print(f"   ✓ Flask app imported successfully")
    print(f"   Routes registered: {len(list(app.url_map.iter_rules()))}")
except Exception as e:
    print(f"   ✗ Error importing app: {e}")
print()

# Recommendations
print("=" * 70)
print("COMMON FIXES FOR 403/404 ERRORS:")
print("=" * 70)
print()
print("1️⃣  RESTART PASSENGER:")
print("   mkdir -p tmp")
print("   touch tmp/restart.txt")
print()
print("2️⃣  CHECK FILE PERMISSIONS:")
print("   chmod 644 passenger_wsgi.py")
print("   chmod 644 .htaccess")
print("   chmod 755 .")
print()
print("3️⃣  VERIFY PATHS IN .htaccess:")
print("   PassengerAppRoot should point to: " + current_dir)
print()
print("4️⃣  CHECK APACHE ERROR LOG:")
print("   tail -50 ~/logs/error_log")
print("   (Look for Passenger errors)")
print()
print("5️⃣  VERIFY .htaccess IS BEING READ:")
print("   If AllowOverride is not set in Apache config, .htaccess is ignored")
print()
print("6️⃣  SIMPLER .htaccess (if still failing):")
print("   Try creating a minimal .htaccess with just:")
print("   PassengerEnabled on")
print()
print("=" * 70)
