import os
import sys
from pathlib import Path
 
# Try to load environment variables from a .env file if python-dotenv is available.
try:
    from dotenv import load_dotenv
    load_dotenv()
except Exception:
    # Not fatal: continue without loading .env
    pass
 
# Determine a safe project root path. Prefer PROJECT_ROOT_PATH if it exists
# and points to a real directory on the current filesystem. Otherwise fall
# back to the directory containing this wsgi file.
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = (os.getenv('PROJECT_ROOT_PATH') or '').strip()
 
path_to_use = None
if project_root:
    try:
        expanded = os.path.expanduser(project_root)
        if os.path.exists(expanded) and os.path.isdir(expanded):
            path_to_use = os.path.abspath(expanded)
    except Exception:
        path_to_use = None
 
if not path_to_use:
    path_to_use = current_dir
 
if path_to_use not in sys.path:
    sys.path.insert(0, path_to_use)
 
# Import the Flask app from run_backend.py. If this fails we'll write to stderr
# (visible in Apache error log) and re-raise so mod_wsgi reports the error.
try:
    from run_backend import app as application
except Exception as e:
    sys.stderr.write(f"WSGI import error: {e}\n")
    raise
 
