#!/usr/bin/env python
"""
Check server error logs to find the exact error
"""

import os
from pathlib import Path
from datetime import datetime, timedelta

print("=" * 70)
print("CHECKING SERVER ERROR LOGS")
print("=" * 70)
print()

BASE_DIR = Path(__file__).resolve().parent

# Common log locations
log_paths = [
    BASE_DIR / 'logs' / 'error.log',
    BASE_DIR / 'logs' / 'django.log',
    BASE_DIR / 'error.log',
    Path('/home/xygbfpsg/logs/grazuri.uzuriapps.xyz.error.log'),
    Path('/home/xygbfpsg/logs/error_log'),
    Path('/var/log/apache2/error.log'),
    Path('/var/log/httpd/error_log'),
]

print("[1/2] Looking for error logs...")
found_logs = []

for log_path in log_paths:
    if log_path.exists():
        size = log_path.stat().st_size
        print(f"  ✓ Found: {log_path} ({size} bytes)")
        found_logs.append(log_path)
    else:
        print(f"  - Not found: {log_path}")

print()

if not found_logs:
    print("No error logs found in common locations.")
    print()
    print("Try these commands to find logs:")
    print("  ls -la ~/logs/")
    print("  ls -la logs/")
    print("  find ~ -name '*error*.log' -type f 2>/dev/null | head -10")
    print()
else:
    print("[2/2] Reading recent errors (last 50 lines)...")
    print("=" * 70)
    print()
    
    for log_path in found_logs[:2]:  # Only read first 2 logs
        print(f"LOG: {log_path}")
        print("-" * 70)
        try:
            with open(log_path, 'r', encoding='utf-8', errors='ignore') as f:
                lines = f.readlines()
                # Get last 50 lines
                recent_lines = lines[-50:] if len(lines) > 50 else lines
                
                for line in recent_lines:
                    print(line.rstrip())
                    
        except Exception as e:
            print(f"Could not read log: {e}")
        
        print()
        print("=" * 70)
        print()

print()
print("INSTRUCTIONS:")
print("=" * 70)
print()
print("If you see Python errors above, those are the actual issues.")
print()
print("Common errors to look for:")
print("- ImportError: module not found")
print("- AttributeError: missing attribute")
print("- TemplateDoesNotExist: missing template file")
print("- Database errors")
print()
print("If no errors shown above, try:")
print("1. tail -f ~/logs/*.error.log")
print("2. Check cPanel → Metrics → Errors")
print("3. Reload the page and immediately check logs")
print()
