import sys
import os
import traceback

# Path to log startup errors
ERROR_LOG = os.path.join(os.path.dirname(__file__), "passenger_err.log")

try:
    # Setup paths for GoDaddy Passenger environment
    # Adjust PYTHON_VERSION and APP_DIR_NAME if they differ in your cPanel setup
    PYTHON_VERSION = "3.11"
    APP_DIR_NAME = "public_html/gather.storzkart.com"
    
    INTERP = os.path.expanduser(f"~/virtualenv/{APP_DIR_NAME}/{PYTHON_VERSION}/bin/python")
    
    # Graceful check for Virtualenv path configuration
    if not os.path.exists(INTERP):
        raise FileNotFoundError(
            f"Python interpreter not found at '{INTERP}'.\n\n"
            f"Troubleshooting steps:\n"
            f"1. Make sure you set up the Python App in cPanel with root directory matching '{APP_DIR_NAME}'.\n"
            f"2. Make sure you selected Python version '{PYTHON_VERSION}'. If you selected a different version (e.g. 3.9 or 3.11), please edit passenger_wsgi.py and update the PYTHON_VERSION variable at the top.\n"
            f"3. Check your cPanel home folder layout via File Manager."
        )

    if sys.executable != INTERP:
        os.execl(INTERP, INTERP, *sys.argv)

    sys.path.append(os.getcwd())

    from a2wsgi import ASGIMiddleware
    from app.main import app

    # Passenger WSGI requires the application to be a callable WSGI object named 'application'
    application = ASGIMiddleware(app)

except Exception as e:
    # Log the detailed traceback to a file in the app directory
    try:
        with open(ERROR_LOG, "a") as f:
            f.write("--- Error during passenger startup ---\n")
            traceback.print_exc(file=f)
            f.write("\n")
    except Exception:
        pass

    # Return a fallback WSGI response displaying the error details in the browser
    def application(environ, start_response):
        status = '500 Internal Server Error'
        headers = [('Content-Type', 'text/html; charset=utf-8')]
        start_response(status, headers)
        
        tb = traceback.format_exc()
        html = f"""
        <html>
        <head>
            <title>Startup Error - Jewel Zen Service</title>
            <style>
                body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; line-height: 1.6; padding: 30px; background-color: #f9f9fa; color: #333; }}
                .container {{ max-width: 800px; margin: 0 auto; background: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.05), 0 1px 3px rgba(0,0,0,0.1); border-top: 5px solid #dc3545; }}
                h1 {{ color: #dc3545; margin-top: 0; }}
                pre {{ background: #272822; color: #f8f8f2; padding: 15px; border-radius: 4px; overflow-x: auto; font-family: "Courier New", Courier, monospace; font-size: 14px; }}
                .footer {{ margin-top: 20px; font-size: 12px; color: #777; }}
            </style>
        </head>
        <body>
            <div class="container">
                <h1>Application Startup Error</h1>
                <p>An error occurred while trying to initialize the application. This is typically due to a missing package, incorrect interpreter path, or a database connection issue.</p>
                <h3>Traceback Details:</h3>
                <pre>{tb}</pre>
                <p>This trace has been logged to <code>passenger_err.log</code> inside your application folder.</p>
                <div class="footer">
                    Jewel Zen Service Deployment Diagnostics
                </div>
            </div>
        </body>
        </html>
        """
        return [html.encode('utf-8')]
