import sys
import os
import traceback

# Add application directory to path
sys.path.insert(0, os.path.dirname(__file__))

# Create a log file
log_file = os.path.join(os.path.dirname(__file__), 'app_debug.log')

try:
    # Log that we're starting
    with open(log_file, 'a') as f:
        f.write("=== Loading passenger_wsgi.py ===\n")
        f.write(f"Python path: {sys.path}\n")
    
    # Try to import the Flask app
    from app import app as _application
    
    with open(log_file, 'a') as f:
        f.write("Flask app imported successfully\n")
    
    def application(environ, start_response):
        return _application(environ, start_response)
    
except Exception as e:
    # Log the error
    with open(log_file, 'a') as f:
        f.write(f"ERROR: {str(e)}\n")
        f.write(traceback.format_exc())
    
    # Return error message to browser
    def application(environ, start_response):
        status = '500 Internal Server Error'
        error_msg = f"Application Error: {str(e)}"
        output = error_msg.encode()
        response_headers = [('Content-type', 'text/plain')]
        start_response(status, response_headers)
        return [output]
