#!/usr/bin/env python3
"""
Run this on the server inside the backend venv to see why Passenger might crash:

  cd /home/wymc1073/social-analytics.virtual-mx.com/ftproot/backend
  source /path/to/venv/bin/activate   # or: source ~/virtualenv/.../bin/activate (path from Setup Python App)
  python check_app.py

Prints to stdout/stderr and writes to check_app_output.txt.
Download check_app_output.txt from the server if you run it via cPanel "Run script".
"""
import sys
import traceback
from pathlib import Path

OUTPUT_FILE = Path(__file__).resolve().parent / "check_app_output.txt"


def main():
    lines = []
    ok = False

    # Step 1: load what Passenger loads (passenger_wsgi.application)
    lines.append("=== Loading passenger_wsgi.application (same as Passenger) ===")
    print(lines[-1])
    try:
        from passenger_wsgi import application
        lines.append("OK: passenger_wsgi.application loaded.")
        print("OK: passenger_wsgi.application loaded.")
        ok = True
    except Exception:
        lines.append("FAIL on import:")
        lines.append(traceback.format_exc())
        print("FAIL on import:", file=sys.stderr)
        traceback.print_exc()
        try:
            OUTPUT_FILE.write_text("\n".join(lines))
        except Exception:
            pass
        return 1

    # Step 2: simulate one WSGI request (in case crash is on first request)
    lines.append("")
    lines.append("=== Simulating one WSGI request (GET /) ===")
    print(lines[-1])
    try:
        result = []
        start_response_called = []

        def start_response(status, headers, exc_info=None):
            start_response_called.append(True)
            result.append((status, list(headers)))

        env = {
            "REQUEST_METHOD": "GET",
            "PATH_INFO": "/",
            "SCRIPT_NAME": "",
            "QUERY_STRING": "",
            "SERVER_NAME": "localhost",
            "SERVER_PORT": "8000",
            "wsgi.input": None,
            "wsgi.version": (1, 0),
            "wsgi.url_scheme": "http",
            "wsgi.multithread": False,
            "wsgi.multiprocess": False,
            "wsgi.run_once": False,
        }
        body = b"".join(application(env, start_response))
        status = result[0][0] if result else "?"
        lines.append(f"OK: response status = {status}, body length = {len(body)}")
        print(f"OK: response status = {status}, body length = {len(body)}")
    except Exception:
        lines.append("FAIL on first request:")
        lines.append(traceback.format_exc())
        print("FAIL on first request:", file=sys.stderr)
        traceback.print_exc()
        ok = False

    try:
        OUTPUT_FILE.write_text("\n".join(lines))
    except Exception:
        pass
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())
