import os
import sys
import traceback

# 1. Samakan working directory ke lokasi folder aplikasi
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(BASE_DIR)

if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)

# 2. Otomatis cari & muat site-packages dari Virtual Environment cPanel
import glob
home_dir = os.path.expanduser('~')
site_packages_pattern = os.path.join(home_dir, 'virtualenv', '*', '*', 'lib', 'python*', 'site-packages')
for sp in glob.glob(site_packages_pattern):
    if sp not in sys.path:
        sys.path.insert(0, sp)

# 3. Coba import aplikasi Flask
try:
    from app import app as application
except Exception as e:
    # Simpan log error ke file passenger_error.log untuk analisa
    log_file = os.path.join(BASE_DIR, 'passenger_error.log')
    with open(log_file, 'w') as f:
        f.write(traceback.format_exc())
    
    # Tampilkan traceback lengkap di browser jika terjadi error 500 saat startup
    error_details = traceback.format_exc()
    def application(environ, start_response):
        status = '500 Internal Server Error'
        output = f"""<!DOCTYPE html>
<html>
<head>
    <title>500 Internal Server Error - Python Startup Failure</title>
    <style>
        body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 30px; background: #0d1117; color: #c9d1d9; line-height: 1.6; }}
        .card {{ background: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 24px; max-width: 900px; margin: 0 auto; box-shadow: 0 10px 25px rgba(0,0,0,0.5); }}
        h2 {{ color: #f85149; margin-top: 0; display: flex; align-items: center; gap: 10px; }}
        pre {{ background: #0d1117; padding: 16px; border-radius: 6px; color: #ff7b72; overflow-x: auto; border: 1px solid #21262d; font-size: 13px; font-family: monospace; }}
        .tip {{ background: #1f6feb22; border-left: 4px solid #1f6feb; padding: 12px 16px; border-radius: 0 6px 6px 0; margin-top: 20px; }}
        code {{ background: #21262d; padding: 2px 6px; border-radius: 4px; color: #58a6ff; font-family: monospace; }}
    </style>
</head>
<body>
    <div class="card">
        <h2>⚠️ 500 Startup Error (Phusion Passenger)</h2>
        <p>Aplikasi gagal di-import oleh server web. Detail rincian error Python:</p>
        <pre>{error_details}</pre>
        <div class="tip">
            <strong>📌 Cara Perbaikan Error:</strong><br><br>
            1. Jika <code>ModuleNotFoundError: No module named 'cv2'</code> (atau module lain):<br>
            Buka Terminal cPanel, aktifkan virtual environment cPanel kamu, lalu jalankan:<br>
            <code>pip install opencv-python-headless</code><br>
            <code>pip install -r requirements.txt</code><br><br>
            2. Setelah install selesai, klik tombol <strong>Restart Application</strong> di cPanel Python App.
        </div>
    </div>
</body>
</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]

