import os
import sys

# CPanel Passenger WSGI entry point
# Adds the app directory to sys.path so Python can find app.py and .env
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)

# Force Pakistan Timezone (+5) so datetime.now() matches admin input
import time
os.environ['TZ'] = 'Asia/Karachi'
try:
    time.tzset()
except AttributeError:
    pass  # Windows fallback

# Load .env before importing app (so SMTP / secrets are available)
try:
    from dotenv import load_dotenv
    load_dotenv(os.path.join(BASE_DIR, ".env"))
except Exception:
    pass

try:
    from app import app as application  # noqa: F401
except Exception as e:
    import traceback
    error_detail = traceback.format_exc()
    
    with open(os.path.join(BASE_DIR, "passenger_error.log"), "w") as f:
        f.write(error_detail)
        
    def application(environ, start_response):
        status = '500 Internal Server Error'
        headers = [('Content-Type', 'text/plain')]
        start_response(status, headers)
        return [b"Application failed to start. Error:\n\n" + error_detail.encode('utf-8')]

