"""
Passenger WSGI file for Flask application
Compatible with Python 3.13+
Auto-detects /product-finder subdirectory deployment
"""
import sys
import os

# Get the directory where this file is located
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))

# Add the application directory to Python path
sys.path.insert(0, CURRENT_DIR)

# Import the Flask application directly from app.py
# Note: app.py now auto-detects production environment
try:
    from app import app as application
    print("✓ Flask application loaded successfully")
    
except ImportError as e:
    # Fallback error handler that shows the actual error
    def application(environ, start_response):
        import traceback
        status = '500 Internal Server Error'
        error_details = f'Import Error: {str(e)}\n\nTraceback:\n{traceback.format_exc()}\n\nPython Path:\n{sys.path}'
        output = error_details.encode('utf-8')
        response_headers = [('Content-type', 'text/plain; charset=utf-8'),
                            ('Content-Length', str(len(output)))]
        start_response(status, response_headers)
        return [output]
    print(f"✗ Failed to import Flask app: {e}")

except Exception as e:
    # Catch any other startup errors
    def application(environ, start_response):
        import traceback
        status = '500 Internal Server Error'
        error_details = f'Startup Error: {str(e)}\n\nTraceback:\n{traceback.format_exc()}'
        output = error_details.encode('utf-8')
        response_headers = [('Content-type', 'text/plain; charset=utf-8'),
                            ('Content-Length', str(len(output)))]
        start_response(status, response_headers)
        return [output]
    print(f"✗ Error starting app: {e}")

# Passenger requires the application object to be named 'application'
