import sys
import os
import traceback

# ─── 1. تحديد مسار المشروع ───────────────────────
# نستخدم os.path.dirname(__file__) للحصول على المسار الحالي تلقائياً
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, PROJECT_ROOT)

# ─── 2. ضبط إعدادات Django ───────────────────────
os.environ['DJANGO_SETTINGS_MODULE'] = 'config.settings'

# ─── 3. أداة لتسجيل الأخطاء في ملف (للتبليغ عن مشاكل التشغيل) ───
def log_error(msg):
    log_file = os.path.join(PROJECT_ROOT, 'passenger_debug.log')
    with open(log_file, 'a', encoding='utf-8') as f:
        f.write(msg + '\n')

# ─── 4. تحميل التطبيق ──────────────────────────────
try:
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()
except Exception:
    log_error("CRITICAL: Django failed to start!")
    log_error(traceback.format_exc())
    
    # وظيفة بسيطة لإظهار الخطأ في المتصفح إذا فشل Django
    def application(environ, start_response):
        start_response('500 Internal Server Error', [('Content-Type', 'text/plain; charset=utf-8')])
        error_msg = f"خطأ في تشغيل Django:\n\n{traceback.format_exc()}"
        return [error_msg.encode('utf-8')]
