import sys
import os
import glob

# Ensure project directory is in sys.path
APP_DIR = os.path.dirname(__file__)
if APP_DIR not in sys.path:
    sys.path.insert(0, APP_DIR)

# Automatically locate and add virtualenv site-packages (CloudLinux cPanel)
venv_base = os.path.expanduser("~/virtualenv/autottcaption.site/3.10")
site_packages_pattern = os.path.join(venv_base, "lib", "python*", "site-packages")
for sp in glob.glob(site_packages_pattern):
    if sp not in sys.path:
        sys.path.insert(0, sp)

hardcoded_sp = "/home/ivuiiwlfhu/virtualenv/autottcaption.site/3.10/lib/python3.10/site-packages"
if os.path.exists(hardcoded_sp) and hardcoded_sp not in sys.path:
    sys.path.insert(0, hardcoded_sp)

try:
    # Import Flask app as WSGI application callable
    from server import app as application
except Exception as e:
    import traceback
    error_msg = traceback.format_exc()
    def application(environ, start_response):
        start_response('500 Internal Server Error', [('Content-Type', 'text/plain; charset=utf-8')])
        return [f"=== AUTOTTCAPTION PYTHON STARTUP ERROR ===\n\n{error_msg}".encode('utf-8')]
