# ~/flask/passenger_wsgi.py
import sys, os, traceback, site
from pathlib import Path

project_home = Path(__file__).resolve().parent
# Ensure your app directory is importable
if str(project_home) not in sys.path:
    sys.path.insert(0, str(project_home))

# Also add the venv site-packages explicitly (works even if UI setting is ignored)
venv_site = project_home / "env" / "lib" / f"python{sys.version_info.major}.{sys.version_info.minor}" / "site-packages"
if venv_site.is_dir():
    site.addsitedir(str(venv_site))

def application(environ, start_response):
    try:
        # Try importing Flask and your app
        import flask  # proves Flask is visible
        from app import app as flask_app
        # If we got this far, hand off to the real Flask app
        return flask_app.wsgi_app(environ, start_response)
    except Exception as e:
        # Show a plain-text traceback in the browser so we can see EXACTLY what's wrong
        start_response("500 Internal Server Error", [("Content-Type", "text/plain")])
        tb = traceback.format_exc()
        details = [
            f"sys.executable = {sys.executable}",
            f"sys.version    = {sys.version}",
            "sys.path:",
            *[f"  - {p}" for p in sys.path],
            "",
            "TRACEBACK:",
            tb,
        ]
        return [("\n".join(details)).encode("utf-8")]
