"""
passenger_wsgi.py — نقطة الانطلاق لتشغيل تطبيق بايثون على cPanel / CloudLinux (Phusion Passenger)
"""
import sys
import os
import traceback

# 1. إضافة مسار المجلد الحالي إلى مسارات بايثون
cwd = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, cwd)

# 2. ملف تسجيل الأخطاء المحلي داخل المجلد لسهولة المتابعة عبر cPanel File Manager
log_file = os.path.join(cwd, "passenger_error.log")

application = None
startup_error = None

try:
    # التحقق من توفر محول a2wsgi لتحويل ASGI (FastAPI) إلى WSGI (Passenger)
    from a2wsgi import ASGIMiddleware
    from search_api import app
    application = ASGIMiddleware(app)
except Exception as e:
    startup_error = traceback.format_exc()
    try:
        with open(log_file, "w", encoding="utf-8") as f:
            f.write(f"=== Meezan AI Python Passenger Error ===\n")
            f.write(f"Python Executable: {sys.executable}\n")
            f.write(f"Python Version: {sys.version}\n")
            f.write(f"Current Directory: {cwd}\n")
            f.write(f"Sys Path: {sys.path}\n\n")
            f.write("Traceback:\n")
            f.write(startup_error)
    except Exception:
        pass

# 3. في حال حدوث أي خطأ، يتم تقديم صفحة تشخيصية واضحة تفيد مدير الموقع بسبب الخطأ وطريقة حله
if startup_error or application is None:
    def application(environ, start_response):
        status = '500 Internal Server Error'
        
        # تفاصيل الحزم المفقودة الأكثر شيوعاً
        missing_a2wsgi = "No module named 'a2wsgi'" in startup_error
        db_error = "mysql.connector" in startup_error or "Access denied" in startup_error
        
        tips = []
        if missing_a2wsgi:
            tips.append("<li><strong>حزمة a2wsgi مفقودة:</strong> يرجى تثبيتها في بيئة بايثون عبر: <code>pip install a2wsgi</code></li>")
        if db_error:
            tips.append("<li><strong>بيانات قاعدة البيانات:</strong> تأكد من إعداد ملف <code>.env</code> داخل مجلد التطبيق ببيانات MySQL الصحيحة لسيرفر cPanel.</li>")
        tips.append("<li><strong>لتثبيت جميع المتطلبات:</strong> شغّل الأمر <code>pip install -r requirements.txt</code> داخل البيئة الافتراضية.</li>")

        tips_html = "\n".join(tips)
        
        html = f"""<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="utf-8">
    <title>تشخيص خدمة البحث الدلالي - ميزان AI</title>
    <style>
        body {{ font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; padding: 40px 20px; background: #0f172a; color: #f8fafc; direction: rtl; }}
        .card {{ background: #1e293b; border-radius: 12px; padding: 30px; border: 1px solid #334155; max-width: 950px; margin: 0 auto; box-shadow: 0 10px 25px rgba(0,0,0,0.3); }}
        h1 {{ color: #ef4444; font-size: 22px; margin-top: 0; }}
        .badge {{ background: #991b1b; color: #fecaca; padding: 4px 10px; border-radius: 6px; font-size: 13px; font-weight: normal; }}
        pre {{ background: #020617; padding: 18px; border-radius: 8px; overflow-x: auto; color: #f43f5e; direction: ltr; text-align: left; font-size: 13px; border: 1px solid #1e293b; line-height: 1.5; }}
        .help {{ margin-top: 25px; line-height: 1.8; color: #cbd5e1; background: #0f172a; padding: 20px; border-radius: 8px; border-right: 4px solid #38bdf8; }}
        code {{ background: #334155; padding: 2px 8px; border-radius: 4px; color: #38bdf8; font-family: monospace; direction: ltr; display: inline-block; }}
        ul {{ margin-top: 10px; padding-right: 20px; }}
        li {{ margin-bottom: 8px; }}
        .meta {{ font-size: 12px; color: #64748b; margin-top: 20px; direction: ltr; text-align: left; }}
    </style>
</head>
<body>
    <div class="card">
        <h1>❌ تعذر بدء تشغيل خدمة بايثون <span class="badge">Phusion Passenger</span></h1>
        <p>واجه خادم Passenger خطأً أثناء استيراد ملفات التطبيق. يوضح السجل الفني أدناه سبب الخطأ الدقيق:</p>
        <pre>{startup_error}</pre>
        <div class="help">
            <h3 style="margin-top:0; color:#38bdf8;">💡 خطوات الحل المقترحة:</h3>
            <ul>
                {tips_html}
            </ul>
        </div>
        <div class="meta">
            <strong>Python:</strong> {sys.executable}<br>
            <strong>Directory:</strong> {cwd}
        </div>
    </div>
</body>
</html>"""
        output = html.encode('utf-8')
        response_headers = [
            ('Content-type', 'text/html; charset=utf-8'),
            ('Content-Length', str(len(output)))
        ]
        start_response(status, response_headers)
        return [output]

